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 
13398 TEST_F(FormatTest, FormatStarDependingOnContext) {
13399   verifyFormat("void f(int *a);");
13400   verifyFormat("void f() { f(fint * b); }");
13401   verifyFormat("class A {\n  void f(int *a);\n};");
13402   verifyFormat("class A {\n  int *a;\n};");
13403   verifyFormat("namespace a {\n"
13404                "namespace b {\n"
13405                "class A {\n"
13406                "  void f() {}\n"
13407                "  int *a;\n"
13408                "};\n"
13409                "} // namespace b\n"
13410                "} // namespace a");
13411 }
13412 
13413 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13414   verifyFormat("while");
13415   verifyFormat("operator");
13416 }
13417 
13418 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13419   // This code would be painfully slow to format if we didn't skip it.
13420   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
13421                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13422                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13423                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13424                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13425                    "A(1, 1)\n"
13426                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13427                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13428                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13429                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13430                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13431                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13432                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
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   // Deeply nested part is untouched, rest is formatted.
13437   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13438             format(std::string("int    i;\n") + Code + "int    j;\n",
13439                    getLLVMStyle(), SC_ExpectIncomplete));
13440 }
13441 
13442 //===----------------------------------------------------------------------===//
13443 // Objective-C tests.
13444 //===----------------------------------------------------------------------===//
13445 
13446 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13447   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13448   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13449             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13450   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13451   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13452   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13453             format("-(NSInteger)Method3:(id)anObject;"));
13454   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13455             format("-(NSInteger)Method4:(id)anObject;"));
13456   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13457             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13458   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13459             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13460   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13461             "forAllCells:(BOOL)flag;",
13462             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13463                    "forAllCells:(BOOL)flag;"));
13464 
13465   // Very long objectiveC method declaration.
13466   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13467                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13468   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13469                "                    inRange:(NSRange)range\n"
13470                "                   outRange:(NSRange)out_range\n"
13471                "                  outRange1:(NSRange)out_range1\n"
13472                "                  outRange2:(NSRange)out_range2\n"
13473                "                  outRange3:(NSRange)out_range3\n"
13474                "                  outRange4:(NSRange)out_range4\n"
13475                "                  outRange5:(NSRange)out_range5\n"
13476                "                  outRange6:(NSRange)out_range6\n"
13477                "                  outRange7:(NSRange)out_range7\n"
13478                "                  outRange8:(NSRange)out_range8\n"
13479                "                  outRange9:(NSRange)out_range9;");
13480 
13481   // When the function name has to be wrapped.
13482   FormatStyle Style = getLLVMStyle();
13483   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13484   // and always indents instead.
13485   Style.IndentWrappedFunctionNames = false;
13486   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13487                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13488                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13489                "}",
13490                Style);
13491   Style.IndentWrappedFunctionNames = true;
13492   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13493                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13494                "               anotherName:(NSString)dddddddddddddd {\n"
13495                "}",
13496                Style);
13497 
13498   verifyFormat("- (int)sum:(vector<int>)numbers;");
13499   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13500   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13501   // protocol lists (but not for template classes):
13502   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13503 
13504   verifyFormat("- (int (*)())foo:(int (*)())f;");
13505   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13506 
13507   // If there's no return type (very rare in practice!), LLVM and Google style
13508   // agree.
13509   verifyFormat("- foo;");
13510   verifyFormat("- foo:(int)f;");
13511   verifyGoogleFormat("- foo:(int)foo;");
13512 }
13513 
13514 TEST_F(FormatTest, BreaksStringLiterals) {
13515   EXPECT_EQ("\"some text \"\n"
13516             "\"other\";",
13517             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13518   EXPECT_EQ("\"some text \"\n"
13519             "\"other\";",
13520             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13521   EXPECT_EQ(
13522       "#define A  \\\n"
13523       "  \"some \"  \\\n"
13524       "  \"text \"  \\\n"
13525       "  \"other\";",
13526       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13527   EXPECT_EQ(
13528       "#define A  \\\n"
13529       "  \"so \"    \\\n"
13530       "  \"text \"  \\\n"
13531       "  \"other\";",
13532       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13533 
13534   EXPECT_EQ("\"some text\"",
13535             format("\"some text\"", getLLVMStyleWithColumns(1)));
13536   EXPECT_EQ("\"some text\"",
13537             format("\"some text\"", getLLVMStyleWithColumns(11)));
13538   EXPECT_EQ("\"some \"\n"
13539             "\"text\"",
13540             format("\"some text\"", getLLVMStyleWithColumns(10)));
13541   EXPECT_EQ("\"some \"\n"
13542             "\"text\"",
13543             format("\"some text\"", getLLVMStyleWithColumns(7)));
13544   EXPECT_EQ("\"some\"\n"
13545             "\" tex\"\n"
13546             "\"t\"",
13547             format("\"some text\"", getLLVMStyleWithColumns(6)));
13548   EXPECT_EQ("\"some\"\n"
13549             "\" tex\"\n"
13550             "\" and\"",
13551             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13552   EXPECT_EQ("\"some\"\n"
13553             "\"/tex\"\n"
13554             "\"/and\"",
13555             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13556 
13557   EXPECT_EQ("variable =\n"
13558             "    \"long string \"\n"
13559             "    \"literal\";",
13560             format("variable = \"long string literal\";",
13561                    getLLVMStyleWithColumns(20)));
13562 
13563   EXPECT_EQ("variable = f(\n"
13564             "    \"long string \"\n"
13565             "    \"literal\",\n"
13566             "    short,\n"
13567             "    loooooooooooooooooooong);",
13568             format("variable = f(\"long string literal\", short, "
13569                    "loooooooooooooooooooong);",
13570                    getLLVMStyleWithColumns(20)));
13571 
13572   EXPECT_EQ(
13573       "f(g(\"long string \"\n"
13574       "    \"literal\"),\n"
13575       "  b);",
13576       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13577   EXPECT_EQ("f(g(\"long string \"\n"
13578             "    \"literal\",\n"
13579             "    a),\n"
13580             "  b);",
13581             format("f(g(\"long string literal\", a), b);",
13582                    getLLVMStyleWithColumns(20)));
13583   EXPECT_EQ(
13584       "f(\"one two\".split(\n"
13585       "    variable));",
13586       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13587   EXPECT_EQ("f(\"one two three four five six \"\n"
13588             "  \"seven\".split(\n"
13589             "      really_looooong_variable));",
13590             format("f(\"one two three four five six seven\"."
13591                    "split(really_looooong_variable));",
13592                    getLLVMStyleWithColumns(33)));
13593 
13594   EXPECT_EQ("f(\"some \"\n"
13595             "  \"text\",\n"
13596             "  other);",
13597             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13598 
13599   // Only break as a last resort.
13600   verifyFormat(
13601       "aaaaaaaaaaaaaaaaaaaa(\n"
13602       "    aaaaaaaaaaaaaaaaaaaa,\n"
13603       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13604 
13605   EXPECT_EQ("\"splitmea\"\n"
13606             "\"trandomp\"\n"
13607             "\"oint\"",
13608             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13609 
13610   EXPECT_EQ("\"split/\"\n"
13611             "\"pathat/\"\n"
13612             "\"slashes\"",
13613             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13614 
13615   EXPECT_EQ("\"split/\"\n"
13616             "\"pathat/\"\n"
13617             "\"slashes\"",
13618             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13619   EXPECT_EQ("\"split at \"\n"
13620             "\"spaces/at/\"\n"
13621             "\"slashes.at.any$\"\n"
13622             "\"non-alphanumeric%\"\n"
13623             "\"1111111111characte\"\n"
13624             "\"rs\"",
13625             format("\"split at "
13626                    "spaces/at/"
13627                    "slashes.at."
13628                    "any$non-"
13629                    "alphanumeric%"
13630                    "1111111111characte"
13631                    "rs\"",
13632                    getLLVMStyleWithColumns(20)));
13633 
13634   // Verify that splitting the strings understands
13635   // Style::AlwaysBreakBeforeMultilineStrings.
13636   EXPECT_EQ("aaaaaaaaaaaa(\n"
13637             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13638             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13639             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13640                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13641                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13642                    getGoogleStyle()));
13643   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13644             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13645             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13646                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13647                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13648                    getGoogleStyle()));
13649   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13650             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13651             format("llvm::outs() << "
13652                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13653                    "aaaaaaaaaaaaaaaaaaa\";"));
13654   EXPECT_EQ("ffff(\n"
13655             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13656             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13657             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13658                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13659                    getGoogleStyle()));
13660 
13661   FormatStyle Style = getLLVMStyleWithColumns(12);
13662   Style.BreakStringLiterals = false;
13663   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13664 
13665   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13666   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13667   EXPECT_EQ("#define A \\\n"
13668             "  \"some \" \\\n"
13669             "  \"text \" \\\n"
13670             "  \"other\";",
13671             format("#define A \"some text other\";", AlignLeft));
13672 }
13673 
13674 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13675   EXPECT_EQ("C a = \"some more \"\n"
13676             "      \"text\";",
13677             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13678 }
13679 
13680 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13681   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13682   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13683   EXPECT_EQ("int i = a(b());",
13684             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13685 }
13686 
13687 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13688   EXPECT_EQ(
13689       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13690       "(\n"
13691       "    \"x\t\");",
13692       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13693              "aaaaaaa("
13694              "\"x\t\");"));
13695 }
13696 
13697 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13698   EXPECT_EQ(
13699       "u8\"utf8 string \"\n"
13700       "u8\"literal\";",
13701       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13702   EXPECT_EQ(
13703       "u\"utf16 string \"\n"
13704       "u\"literal\";",
13705       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13706   EXPECT_EQ(
13707       "U\"utf32 string \"\n"
13708       "U\"literal\";",
13709       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13710   EXPECT_EQ("L\"wide string \"\n"
13711             "L\"literal\";",
13712             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13713   EXPECT_EQ("@\"NSString \"\n"
13714             "@\"literal\";",
13715             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13716   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13717 
13718   // This input makes clang-format try to split the incomplete unicode escape
13719   // sequence, which used to lead to a crasher.
13720   verifyNoCrash(
13721       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13722       getLLVMStyleWithColumns(60));
13723 }
13724 
13725 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13726   FormatStyle Style = getGoogleStyleWithColumns(15);
13727   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13728   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13729   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13730   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13731   EXPECT_EQ("u8R\"x(raw literal)x\";",
13732             format("u8R\"x(raw literal)x\";", Style));
13733 }
13734 
13735 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13736   FormatStyle Style = getLLVMStyleWithColumns(20);
13737   EXPECT_EQ(
13738       "_T(\"aaaaaaaaaaaaaa\")\n"
13739       "_T(\"aaaaaaaaaaaaaa\")\n"
13740       "_T(\"aaaaaaaaaaaa\")",
13741       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13742   EXPECT_EQ("f(x,\n"
13743             "  _T(\"aaaaaaaaaaaa\")\n"
13744             "  _T(\"aaa\"),\n"
13745             "  z);",
13746             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13747 
13748   // FIXME: Handle embedded spaces in one iteration.
13749   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13750   //            "_T(\"aaaaaaaaaaaaa\")\n"
13751   //            "_T(\"aaaaaaaaaaaaa\")\n"
13752   //            "_T(\"a\")",
13753   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13754   //                   getLLVMStyleWithColumns(20)));
13755   EXPECT_EQ(
13756       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13757       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13758   EXPECT_EQ("f(\n"
13759             "#if !TEST\n"
13760             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13761             "#endif\n"
13762             ");",
13763             format("f(\n"
13764                    "#if !TEST\n"
13765                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13766                    "#endif\n"
13767                    ");"));
13768   EXPECT_EQ("f(\n"
13769             "\n"
13770             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13771             format("f(\n"
13772                    "\n"
13773                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13774   // Regression test for accessing tokens past the end of a vector in the
13775   // TokenLexer.
13776   verifyNoCrash(R"(_T(
13777 "
13778 )
13779 )");
13780 }
13781 
13782 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13783   // In a function call with two operands, the second can be broken with no line
13784   // break before it.
13785   EXPECT_EQ(
13786       "func(a, \"long long \"\n"
13787       "        \"long long\");",
13788       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13789   // In a function call with three operands, the second must be broken with a
13790   // line break before it.
13791   EXPECT_EQ("func(a,\n"
13792             "     \"long long long \"\n"
13793             "     \"long\",\n"
13794             "     c);",
13795             format("func(a, \"long long long long\", c);",
13796                    getLLVMStyleWithColumns(24)));
13797   // In a function call with three operands, the third must be broken with a
13798   // line break before it.
13799   EXPECT_EQ("func(a, b,\n"
13800             "     \"long long long \"\n"
13801             "     \"long\");",
13802             format("func(a, b, \"long long long long\");",
13803                    getLLVMStyleWithColumns(24)));
13804   // In a function call with three operands, both the second and the third must
13805   // be broken with a line break before them.
13806   EXPECT_EQ("func(a,\n"
13807             "     \"long long long \"\n"
13808             "     \"long\",\n"
13809             "     \"long long long \"\n"
13810             "     \"long\");",
13811             format("func(a, \"long long long long\", \"long long long long\");",
13812                    getLLVMStyleWithColumns(24)));
13813   // In a chain of << with two operands, the second can be broken with no line
13814   // break before it.
13815   EXPECT_EQ("a << \"line line \"\n"
13816             "     \"line\";",
13817             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13818   // In a chain of << with three operands, the second can be broken with no line
13819   // break before it.
13820   EXPECT_EQ(
13821       "abcde << \"line \"\n"
13822       "         \"line line\"\n"
13823       "      << c;",
13824       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13825   // In a chain of << with three operands, the third must be broken with a line
13826   // break before it.
13827   EXPECT_EQ(
13828       "a << b\n"
13829       "  << \"line line \"\n"
13830       "     \"line\";",
13831       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13832   // In a chain of << with three operands, the second can be broken with no line
13833   // break before it and the third must be broken with a line break before it.
13834   EXPECT_EQ("abcd << \"line line \"\n"
13835             "        \"line\"\n"
13836             "     << \"line line \"\n"
13837             "        \"line\";",
13838             format("abcd << \"line line line\" << \"line line line\";",
13839                    getLLVMStyleWithColumns(20)));
13840   // In a chain of binary operators with two operands, the second can be broken
13841   // with no line break before it.
13842   EXPECT_EQ(
13843       "abcd + \"line line \"\n"
13844       "       \"line line\";",
13845       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13846   // In a chain of binary operators with three operands, the second must be
13847   // broken with a line break before it.
13848   EXPECT_EQ("abcd +\n"
13849             "    \"line line \"\n"
13850             "    \"line line\" +\n"
13851             "    e;",
13852             format("abcd + \"line line line line\" + e;",
13853                    getLLVMStyleWithColumns(20)));
13854   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13855   // the first must be broken with a line break before it.
13856   FormatStyle Style = getLLVMStyleWithColumns(25);
13857   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13858   EXPECT_EQ("someFunction(\n"
13859             "    \"long long long \"\n"
13860             "    \"long\",\n"
13861             "    a);",
13862             format("someFunction(\"long long long long\", a);", Style));
13863 }
13864 
13865 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13866   EXPECT_EQ(
13867       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13868       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13869       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13870       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13871              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13872              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13873 }
13874 
13875 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13876   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13877             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13878   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13879             "multiline raw string literal xxxxxxxxxxxxxx\n"
13880             ")x\",\n"
13881             "              a),\n"
13882             "            b);",
13883             format("fffffffffff(g(R\"x(\n"
13884                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13885                    ")x\", a), b);",
13886                    getGoogleStyleWithColumns(20)));
13887   EXPECT_EQ("fffffffffff(\n"
13888             "    g(R\"x(qqq\n"
13889             "multiline raw string literal xxxxxxxxxxxxxx\n"
13890             ")x\",\n"
13891             "      a),\n"
13892             "    b);",
13893             format("fffffffffff(g(R\"x(qqq\n"
13894                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13895                    ")x\", a), b);",
13896                    getGoogleStyleWithColumns(20)));
13897 
13898   EXPECT_EQ("fffffffffff(R\"x(\n"
13899             "multiline raw string literal xxxxxxxxxxxxxx\n"
13900             ")x\");",
13901             format("fffffffffff(R\"x(\n"
13902                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13903                    ")x\");",
13904                    getGoogleStyleWithColumns(20)));
13905   EXPECT_EQ("fffffffffff(R\"x(\n"
13906             "multiline raw string literal xxxxxxxxxxxxxx\n"
13907             ")x\" + bbbbbb);",
13908             format("fffffffffff(R\"x(\n"
13909                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13910                    ")x\" +   bbbbbb);",
13911                    getGoogleStyleWithColumns(20)));
13912   EXPECT_EQ("fffffffffff(\n"
13913             "    R\"x(\n"
13914             "multiline raw string literal xxxxxxxxxxxxxx\n"
13915             ")x\" +\n"
13916             "    bbbbbb);",
13917             format("fffffffffff(\n"
13918                    " R\"x(\n"
13919                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13920                    ")x\" + bbbbbb);",
13921                    getGoogleStyleWithColumns(20)));
13922   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13923             format("fffffffffff(\n"
13924                    " R\"(single line raw string)\" + bbbbbb);"));
13925 }
13926 
13927 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13928   verifyFormat("string a = \"unterminated;");
13929   EXPECT_EQ("function(\"unterminated,\n"
13930             "         OtherParameter);",
13931             format("function(  \"unterminated,\n"
13932                    "    OtherParameter);"));
13933 }
13934 
13935 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13936   FormatStyle Style = getLLVMStyle();
13937   Style.Standard = FormatStyle::LS_Cpp03;
13938   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13939             format("#define x(_a) printf(\"foo\"_a);", Style));
13940 }
13941 
13942 TEST_F(FormatTest, CppLexVersion) {
13943   FormatStyle Style = getLLVMStyle();
13944   // Formatting of x * y differs if x is a type.
13945   verifyFormat("void foo() { MACRO(a * b); }", Style);
13946   verifyFormat("void foo() { MACRO(int *b); }", Style);
13947 
13948   // LLVM style uses latest lexer.
13949   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13950   Style.Standard = FormatStyle::LS_Cpp17;
13951   // But in c++17, char8_t isn't a keyword.
13952   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13953 }
13954 
13955 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13956 
13957 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13958   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13959             "             \"ddeeefff\");",
13960             format("someFunction(\"aaabbbcccdddeeefff\");",
13961                    getLLVMStyleWithColumns(25)));
13962   EXPECT_EQ("someFunction1234567890(\n"
13963             "    \"aaabbbcccdddeeefff\");",
13964             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13965                    getLLVMStyleWithColumns(26)));
13966   EXPECT_EQ("someFunction1234567890(\n"
13967             "    \"aaabbbcccdddeeeff\"\n"
13968             "    \"f\");",
13969             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13970                    getLLVMStyleWithColumns(25)));
13971   EXPECT_EQ("someFunction1234567890(\n"
13972             "    \"aaabbbcccdddeeeff\"\n"
13973             "    \"f\");",
13974             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13975                    getLLVMStyleWithColumns(24)));
13976   EXPECT_EQ("someFunction(\n"
13977             "    \"aaabbbcc ddde \"\n"
13978             "    \"efff\");",
13979             format("someFunction(\"aaabbbcc ddde efff\");",
13980                    getLLVMStyleWithColumns(25)));
13981   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13982             "             \"ddeeefff\");",
13983             format("someFunction(\"aaabbbccc ddeeefff\");",
13984                    getLLVMStyleWithColumns(25)));
13985   EXPECT_EQ("someFunction1234567890(\n"
13986             "    \"aaabb \"\n"
13987             "    \"cccdddeeefff\");",
13988             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13989                    getLLVMStyleWithColumns(25)));
13990   EXPECT_EQ("#define A          \\\n"
13991             "  string s =       \\\n"
13992             "      \"123456789\"  \\\n"
13993             "      \"0\";         \\\n"
13994             "  int i;",
13995             format("#define A string s = \"1234567890\"; int i;",
13996                    getLLVMStyleWithColumns(20)));
13997   EXPECT_EQ("someFunction(\n"
13998             "    \"aaabbbcc \"\n"
13999             "    \"dddeeefff\");",
14000             format("someFunction(\"aaabbbcc dddeeefff\");",
14001                    getLLVMStyleWithColumns(25)));
14002 }
14003 
14004 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
14005   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
14006   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
14007   EXPECT_EQ("\"test\"\n"
14008             "\"\\n\"",
14009             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
14010   EXPECT_EQ("\"tes\\\\\"\n"
14011             "\"n\"",
14012             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
14013   EXPECT_EQ("\"\\\\\\\\\"\n"
14014             "\"\\n\"",
14015             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
14016   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
14017   EXPECT_EQ("\"\\uff01\"\n"
14018             "\"test\"",
14019             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
14020   EXPECT_EQ("\"\\Uff01ff02\"",
14021             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
14022   EXPECT_EQ("\"\\x000000000001\"\n"
14023             "\"next\"",
14024             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
14025   EXPECT_EQ("\"\\x000000000001next\"",
14026             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
14027   EXPECT_EQ("\"\\x000000000001\"",
14028             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
14029   EXPECT_EQ("\"test\"\n"
14030             "\"\\000000\"\n"
14031             "\"000001\"",
14032             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
14033   EXPECT_EQ("\"test\\000\"\n"
14034             "\"00000000\"\n"
14035             "\"1\"",
14036             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
14037 }
14038 
14039 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
14040   verifyFormat("void f() {\n"
14041                "  return g() {}\n"
14042                "  void h() {}");
14043   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
14044                "g();\n"
14045                "}");
14046 }
14047 
14048 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
14049   verifyFormat(
14050       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
14051 }
14052 
14053 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
14054   verifyFormat("class X {\n"
14055                "  void f() {\n"
14056                "  }\n"
14057                "};",
14058                getLLVMStyleWithColumns(12));
14059 }
14060 
14061 TEST_F(FormatTest, ConfigurableIndentWidth) {
14062   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
14063   EightIndent.IndentWidth = 8;
14064   EightIndent.ContinuationIndentWidth = 8;
14065   verifyFormat("void f() {\n"
14066                "        someFunction();\n"
14067                "        if (true) {\n"
14068                "                f();\n"
14069                "        }\n"
14070                "}",
14071                EightIndent);
14072   verifyFormat("class X {\n"
14073                "        void f() {\n"
14074                "        }\n"
14075                "};",
14076                EightIndent);
14077   verifyFormat("int x[] = {\n"
14078                "        call(),\n"
14079                "        call()};",
14080                EightIndent);
14081 }
14082 
14083 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
14084   verifyFormat("double\n"
14085                "f();",
14086                getLLVMStyleWithColumns(8));
14087 }
14088 
14089 TEST_F(FormatTest, ConfigurableUseOfTab) {
14090   FormatStyle Tab = getLLVMStyleWithColumns(42);
14091   Tab.IndentWidth = 8;
14092   Tab.UseTab = FormatStyle::UT_Always;
14093   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14094 
14095   EXPECT_EQ("if (aaaaaaaa && // q\n"
14096             "    bb)\t\t// w\n"
14097             "\t;",
14098             format("if (aaaaaaaa &&// q\n"
14099                    "bb)// w\n"
14100                    ";",
14101                    Tab));
14102   EXPECT_EQ("if (aaa && bbb) // w\n"
14103             "\t;",
14104             format("if(aaa&&bbb)// w\n"
14105                    ";",
14106                    Tab));
14107 
14108   verifyFormat("class X {\n"
14109                "\tvoid f() {\n"
14110                "\t\tsomeFunction(parameter1,\n"
14111                "\t\t\t     parameter2);\n"
14112                "\t}\n"
14113                "};",
14114                Tab);
14115   verifyFormat("#define A                        \\\n"
14116                "\tvoid f() {               \\\n"
14117                "\t\tsomeFunction(    \\\n"
14118                "\t\t    parameter1,  \\\n"
14119                "\t\t    parameter2); \\\n"
14120                "\t}",
14121                Tab);
14122   verifyFormat("int a;\t      // x\n"
14123                "int bbbbbbbb; // x\n",
14124                Tab);
14125 
14126   Tab.TabWidth = 4;
14127   Tab.IndentWidth = 8;
14128   verifyFormat("class TabWidth4Indent8 {\n"
14129                "\t\tvoid f() {\n"
14130                "\t\t\t\tsomeFunction(parameter1,\n"
14131                "\t\t\t\t\t\t\t parameter2);\n"
14132                "\t\t}\n"
14133                "};",
14134                Tab);
14135 
14136   Tab.TabWidth = 4;
14137   Tab.IndentWidth = 4;
14138   verifyFormat("class TabWidth4Indent4 {\n"
14139                "\tvoid f() {\n"
14140                "\t\tsomeFunction(parameter1,\n"
14141                "\t\t\t\t\t parameter2);\n"
14142                "\t}\n"
14143                "};",
14144                Tab);
14145 
14146   Tab.TabWidth = 8;
14147   Tab.IndentWidth = 4;
14148   verifyFormat("class TabWidth8Indent4 {\n"
14149                "    void f() {\n"
14150                "\tsomeFunction(parameter1,\n"
14151                "\t\t     parameter2);\n"
14152                "    }\n"
14153                "};",
14154                Tab);
14155 
14156   Tab.TabWidth = 8;
14157   Tab.IndentWidth = 8;
14158   EXPECT_EQ("/*\n"
14159             "\t      a\t\tcomment\n"
14160             "\t      in multiple lines\n"
14161             "       */",
14162             format("   /*\t \t \n"
14163                    " \t \t a\t\tcomment\t \t\n"
14164                    " \t \t in multiple lines\t\n"
14165                    " \t  */",
14166                    Tab));
14167 
14168   Tab.UseTab = FormatStyle::UT_ForIndentation;
14169   verifyFormat("{\n"
14170                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14171                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14172                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14173                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14174                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14175                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14176                "};",
14177                Tab);
14178   verifyFormat("enum AA {\n"
14179                "\ta1, // Force multiple lines\n"
14180                "\ta2,\n"
14181                "\ta3\n"
14182                "};",
14183                Tab);
14184   EXPECT_EQ("if (aaaaaaaa && // q\n"
14185             "    bb)         // w\n"
14186             "\t;",
14187             format("if (aaaaaaaa &&// q\n"
14188                    "bb)// w\n"
14189                    ";",
14190                    Tab));
14191   verifyFormat("class X {\n"
14192                "\tvoid f() {\n"
14193                "\t\tsomeFunction(parameter1,\n"
14194                "\t\t             parameter2);\n"
14195                "\t}\n"
14196                "};",
14197                Tab);
14198   verifyFormat("{\n"
14199                "\tQ(\n"
14200                "\t    {\n"
14201                "\t\t    int a;\n"
14202                "\t\t    someFunction(aaaaaaaa,\n"
14203                "\t\t                 bbbbbbb);\n"
14204                "\t    },\n"
14205                "\t    p);\n"
14206                "}",
14207                Tab);
14208   EXPECT_EQ("{\n"
14209             "\t/* aaaa\n"
14210             "\t   bbbb */\n"
14211             "}",
14212             format("{\n"
14213                    "/* aaaa\n"
14214                    "   bbbb */\n"
14215                    "}",
14216                    Tab));
14217   EXPECT_EQ("{\n"
14218             "\t/*\n"
14219             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14220             "\t  bbbbbbbbbbbbb\n"
14221             "\t*/\n"
14222             "}",
14223             format("{\n"
14224                    "/*\n"
14225                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14226                    "*/\n"
14227                    "}",
14228                    Tab));
14229   EXPECT_EQ("{\n"
14230             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14231             "\t// bbbbbbbbbbbbb\n"
14232             "}",
14233             format("{\n"
14234                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14235                    "}",
14236                    Tab));
14237   EXPECT_EQ("{\n"
14238             "\t/*\n"
14239             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14240             "\t  bbbbbbbbbbbbb\n"
14241             "\t*/\n"
14242             "}",
14243             format("{\n"
14244                    "\t/*\n"
14245                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14246                    "\t*/\n"
14247                    "}",
14248                    Tab));
14249   EXPECT_EQ("{\n"
14250             "\t/*\n"
14251             "\n"
14252             "\t*/\n"
14253             "}",
14254             format("{\n"
14255                    "\t/*\n"
14256                    "\n"
14257                    "\t*/\n"
14258                    "}",
14259                    Tab));
14260   EXPECT_EQ("{\n"
14261             "\t/*\n"
14262             " asdf\n"
14263             "\t*/\n"
14264             "}",
14265             format("{\n"
14266                    "\t/*\n"
14267                    " asdf\n"
14268                    "\t*/\n"
14269                    "}",
14270                    Tab));
14271 
14272   verifyFormat("void f() {\n"
14273                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14274                "\t            : bbbbbbbbbbbbbbbbbb\n"
14275                "}",
14276                Tab);
14277   FormatStyle TabNoBreak = Tab;
14278   TabNoBreak.BreakBeforeTernaryOperators = false;
14279   verifyFormat("void f() {\n"
14280                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14281                "\t              bbbbbbbbbbbbbbbbbb\n"
14282                "}",
14283                TabNoBreak);
14284   verifyFormat("void f() {\n"
14285                "\treturn true ?\n"
14286                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14287                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14288                "}",
14289                TabNoBreak);
14290 
14291   Tab.UseTab = FormatStyle::UT_Never;
14292   EXPECT_EQ("/*\n"
14293             "              a\t\tcomment\n"
14294             "              in multiple lines\n"
14295             "       */",
14296             format("   /*\t \t \n"
14297                    " \t \t a\t\tcomment\t \t\n"
14298                    " \t \t in multiple lines\t\n"
14299                    " \t  */",
14300                    Tab));
14301   EXPECT_EQ("/* some\n"
14302             "   comment */",
14303             format(" \t \t /* some\n"
14304                    " \t \t    comment */",
14305                    Tab));
14306   EXPECT_EQ("int a; /* some\n"
14307             "   comment */",
14308             format(" \t \t int a; /* some\n"
14309                    " \t \t    comment */",
14310                    Tab));
14311 
14312   EXPECT_EQ("int a; /* some\n"
14313             "comment */",
14314             format(" \t \t int\ta; /* some\n"
14315                    " \t \t    comment */",
14316                    Tab));
14317   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14318             "    comment */",
14319             format(" \t \t f(\"\t\t\"); /* some\n"
14320                    " \t \t    comment */",
14321                    Tab));
14322   EXPECT_EQ("{\n"
14323             "        /*\n"
14324             "         * Comment\n"
14325             "         */\n"
14326             "        int i;\n"
14327             "}",
14328             format("{\n"
14329                    "\t/*\n"
14330                    "\t * Comment\n"
14331                    "\t */\n"
14332                    "\t int i;\n"
14333                    "}",
14334                    Tab));
14335 
14336   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14337   Tab.TabWidth = 8;
14338   Tab.IndentWidth = 8;
14339   EXPECT_EQ("if (aaaaaaaa && // q\n"
14340             "    bb)         // w\n"
14341             "\t;",
14342             format("if (aaaaaaaa &&// q\n"
14343                    "bb)// w\n"
14344                    ";",
14345                    Tab));
14346   EXPECT_EQ("if (aaa && bbb) // w\n"
14347             "\t;",
14348             format("if(aaa&&bbb)// w\n"
14349                    ";",
14350                    Tab));
14351   verifyFormat("class X {\n"
14352                "\tvoid f() {\n"
14353                "\t\tsomeFunction(parameter1,\n"
14354                "\t\t\t     parameter2);\n"
14355                "\t}\n"
14356                "};",
14357                Tab);
14358   verifyFormat("#define A                        \\\n"
14359                "\tvoid f() {               \\\n"
14360                "\t\tsomeFunction(    \\\n"
14361                "\t\t    parameter1,  \\\n"
14362                "\t\t    parameter2); \\\n"
14363                "\t}",
14364                Tab);
14365   Tab.TabWidth = 4;
14366   Tab.IndentWidth = 8;
14367   verifyFormat("class TabWidth4Indent8 {\n"
14368                "\t\tvoid f() {\n"
14369                "\t\t\t\tsomeFunction(parameter1,\n"
14370                "\t\t\t\t\t\t\t parameter2);\n"
14371                "\t\t}\n"
14372                "};",
14373                Tab);
14374   Tab.TabWidth = 4;
14375   Tab.IndentWidth = 4;
14376   verifyFormat("class TabWidth4Indent4 {\n"
14377                "\tvoid f() {\n"
14378                "\t\tsomeFunction(parameter1,\n"
14379                "\t\t\t\t\t parameter2);\n"
14380                "\t}\n"
14381                "};",
14382                Tab);
14383   Tab.TabWidth = 8;
14384   Tab.IndentWidth = 4;
14385   verifyFormat("class TabWidth8Indent4 {\n"
14386                "    void f() {\n"
14387                "\tsomeFunction(parameter1,\n"
14388                "\t\t     parameter2);\n"
14389                "    }\n"
14390                "};",
14391                Tab);
14392   Tab.TabWidth = 8;
14393   Tab.IndentWidth = 8;
14394   EXPECT_EQ("/*\n"
14395             "\t      a\t\tcomment\n"
14396             "\t      in multiple lines\n"
14397             "       */",
14398             format("   /*\t \t \n"
14399                    " \t \t a\t\tcomment\t \t\n"
14400                    " \t \t in multiple lines\t\n"
14401                    " \t  */",
14402                    Tab));
14403   verifyFormat("{\n"
14404                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14405                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14406                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14407                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14408                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14409                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14410                "};",
14411                Tab);
14412   verifyFormat("enum AA {\n"
14413                "\ta1, // Force multiple lines\n"
14414                "\ta2,\n"
14415                "\ta3\n"
14416                "};",
14417                Tab);
14418   EXPECT_EQ("if (aaaaaaaa && // q\n"
14419             "    bb)         // w\n"
14420             "\t;",
14421             format("if (aaaaaaaa &&// q\n"
14422                    "bb)// w\n"
14423                    ";",
14424                    Tab));
14425   verifyFormat("class X {\n"
14426                "\tvoid f() {\n"
14427                "\t\tsomeFunction(parameter1,\n"
14428                "\t\t\t     parameter2);\n"
14429                "\t}\n"
14430                "};",
14431                Tab);
14432   verifyFormat("{\n"
14433                "\tQ(\n"
14434                "\t    {\n"
14435                "\t\t    int a;\n"
14436                "\t\t    someFunction(aaaaaaaa,\n"
14437                "\t\t\t\t bbbbbbb);\n"
14438                "\t    },\n"
14439                "\t    p);\n"
14440                "}",
14441                Tab);
14442   EXPECT_EQ("{\n"
14443             "\t/* aaaa\n"
14444             "\t   bbbb */\n"
14445             "}",
14446             format("{\n"
14447                    "/* aaaa\n"
14448                    "   bbbb */\n"
14449                    "}",
14450                    Tab));
14451   EXPECT_EQ("{\n"
14452             "\t/*\n"
14453             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14454             "\t  bbbbbbbbbbbbb\n"
14455             "\t*/\n"
14456             "}",
14457             format("{\n"
14458                    "/*\n"
14459                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14460                    "*/\n"
14461                    "}",
14462                    Tab));
14463   EXPECT_EQ("{\n"
14464             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14465             "\t// bbbbbbbbbbbbb\n"
14466             "}",
14467             format("{\n"
14468                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14469                    "}",
14470                    Tab));
14471   EXPECT_EQ("{\n"
14472             "\t/*\n"
14473             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14474             "\t  bbbbbbbbbbbbb\n"
14475             "\t*/\n"
14476             "}",
14477             format("{\n"
14478                    "\t/*\n"
14479                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14480                    "\t*/\n"
14481                    "}",
14482                    Tab));
14483   EXPECT_EQ("{\n"
14484             "\t/*\n"
14485             "\n"
14486             "\t*/\n"
14487             "}",
14488             format("{\n"
14489                    "\t/*\n"
14490                    "\n"
14491                    "\t*/\n"
14492                    "}",
14493                    Tab));
14494   EXPECT_EQ("{\n"
14495             "\t/*\n"
14496             " asdf\n"
14497             "\t*/\n"
14498             "}",
14499             format("{\n"
14500                    "\t/*\n"
14501                    " asdf\n"
14502                    "\t*/\n"
14503                    "}",
14504                    Tab));
14505   EXPECT_EQ("/* some\n"
14506             "   comment */",
14507             format(" \t \t /* some\n"
14508                    " \t \t    comment */",
14509                    Tab));
14510   EXPECT_EQ("int a; /* some\n"
14511             "   comment */",
14512             format(" \t \t int a; /* some\n"
14513                    " \t \t    comment */",
14514                    Tab));
14515   EXPECT_EQ("int a; /* some\n"
14516             "comment */",
14517             format(" \t \t int\ta; /* some\n"
14518                    " \t \t    comment */",
14519                    Tab));
14520   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14521             "    comment */",
14522             format(" \t \t f(\"\t\t\"); /* some\n"
14523                    " \t \t    comment */",
14524                    Tab));
14525   EXPECT_EQ("{\n"
14526             "\t/*\n"
14527             "\t * Comment\n"
14528             "\t */\n"
14529             "\tint i;\n"
14530             "}",
14531             format("{\n"
14532                    "\t/*\n"
14533                    "\t * Comment\n"
14534                    "\t */\n"
14535                    "\t int i;\n"
14536                    "}",
14537                    Tab));
14538   Tab.TabWidth = 2;
14539   Tab.IndentWidth = 2;
14540   EXPECT_EQ("{\n"
14541             "\t/* aaaa\n"
14542             "\t\t bbbb */\n"
14543             "}",
14544             format("{\n"
14545                    "/* aaaa\n"
14546                    "\t bbbb */\n"
14547                    "}",
14548                    Tab));
14549   EXPECT_EQ("{\n"
14550             "\t/*\n"
14551             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14552             "\t\tbbbbbbbbbbbbb\n"
14553             "\t*/\n"
14554             "}",
14555             format("{\n"
14556                    "/*\n"
14557                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14558                    "*/\n"
14559                    "}",
14560                    Tab));
14561   Tab.AlignConsecutiveAssignments.Enabled = true;
14562   Tab.AlignConsecutiveDeclarations.Enabled = true;
14563   Tab.TabWidth = 4;
14564   Tab.IndentWidth = 4;
14565   verifyFormat("class Assign {\n"
14566                "\tvoid f() {\n"
14567                "\t\tint         x      = 123;\n"
14568                "\t\tint         random = 4;\n"
14569                "\t\tstd::string alphabet =\n"
14570                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14571                "\t}\n"
14572                "};",
14573                Tab);
14574 
14575   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14576   Tab.TabWidth = 8;
14577   Tab.IndentWidth = 8;
14578   EXPECT_EQ("if (aaaaaaaa && // q\n"
14579             "    bb)         // w\n"
14580             "\t;",
14581             format("if (aaaaaaaa &&// q\n"
14582                    "bb)// w\n"
14583                    ";",
14584                    Tab));
14585   EXPECT_EQ("if (aaa && bbb) // w\n"
14586             "\t;",
14587             format("if(aaa&&bbb)// w\n"
14588                    ";",
14589                    Tab));
14590   verifyFormat("class X {\n"
14591                "\tvoid f() {\n"
14592                "\t\tsomeFunction(parameter1,\n"
14593                "\t\t             parameter2);\n"
14594                "\t}\n"
14595                "};",
14596                Tab);
14597   verifyFormat("#define A                        \\\n"
14598                "\tvoid f() {               \\\n"
14599                "\t\tsomeFunction(    \\\n"
14600                "\t\t    parameter1,  \\\n"
14601                "\t\t    parameter2); \\\n"
14602                "\t}",
14603                Tab);
14604   Tab.TabWidth = 4;
14605   Tab.IndentWidth = 8;
14606   verifyFormat("class TabWidth4Indent8 {\n"
14607                "\t\tvoid f() {\n"
14608                "\t\t\t\tsomeFunction(parameter1,\n"
14609                "\t\t\t\t             parameter2);\n"
14610                "\t\t}\n"
14611                "};",
14612                Tab);
14613   Tab.TabWidth = 4;
14614   Tab.IndentWidth = 4;
14615   verifyFormat("class TabWidth4Indent4 {\n"
14616                "\tvoid f() {\n"
14617                "\t\tsomeFunction(parameter1,\n"
14618                "\t\t             parameter2);\n"
14619                "\t}\n"
14620                "};",
14621                Tab);
14622   Tab.TabWidth = 8;
14623   Tab.IndentWidth = 4;
14624   verifyFormat("class TabWidth8Indent4 {\n"
14625                "    void f() {\n"
14626                "\tsomeFunction(parameter1,\n"
14627                "\t             parameter2);\n"
14628                "    }\n"
14629                "};",
14630                Tab);
14631   Tab.TabWidth = 8;
14632   Tab.IndentWidth = 8;
14633   EXPECT_EQ("/*\n"
14634             "              a\t\tcomment\n"
14635             "              in multiple lines\n"
14636             "       */",
14637             format("   /*\t \t \n"
14638                    " \t \t a\t\tcomment\t \t\n"
14639                    " \t \t in multiple lines\t\n"
14640                    " \t  */",
14641                    Tab));
14642   verifyFormat("{\n"
14643                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14644                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14645                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14646                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14647                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14648                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14649                "};",
14650                Tab);
14651   verifyFormat("enum AA {\n"
14652                "\ta1, // Force multiple lines\n"
14653                "\ta2,\n"
14654                "\ta3\n"
14655                "};",
14656                Tab);
14657   EXPECT_EQ("if (aaaaaaaa && // q\n"
14658             "    bb)         // w\n"
14659             "\t;",
14660             format("if (aaaaaaaa &&// q\n"
14661                    "bb)// w\n"
14662                    ";",
14663                    Tab));
14664   verifyFormat("class X {\n"
14665                "\tvoid f() {\n"
14666                "\t\tsomeFunction(parameter1,\n"
14667                "\t\t             parameter2);\n"
14668                "\t}\n"
14669                "};",
14670                Tab);
14671   verifyFormat("{\n"
14672                "\tQ(\n"
14673                "\t    {\n"
14674                "\t\t    int a;\n"
14675                "\t\t    someFunction(aaaaaaaa,\n"
14676                "\t\t                 bbbbbbb);\n"
14677                "\t    },\n"
14678                "\t    p);\n"
14679                "}",
14680                Tab);
14681   EXPECT_EQ("{\n"
14682             "\t/* aaaa\n"
14683             "\t   bbbb */\n"
14684             "}",
14685             format("{\n"
14686                    "/* aaaa\n"
14687                    "   bbbb */\n"
14688                    "}",
14689                    Tab));
14690   EXPECT_EQ("{\n"
14691             "\t/*\n"
14692             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14693             "\t  bbbbbbbbbbbbb\n"
14694             "\t*/\n"
14695             "}",
14696             format("{\n"
14697                    "/*\n"
14698                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14699                    "*/\n"
14700                    "}",
14701                    Tab));
14702   EXPECT_EQ("{\n"
14703             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14704             "\t// bbbbbbbbbbbbb\n"
14705             "}",
14706             format("{\n"
14707                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14708                    "}",
14709                    Tab));
14710   EXPECT_EQ("{\n"
14711             "\t/*\n"
14712             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14713             "\t  bbbbbbbbbbbbb\n"
14714             "\t*/\n"
14715             "}",
14716             format("{\n"
14717                    "\t/*\n"
14718                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14719                    "\t*/\n"
14720                    "}",
14721                    Tab));
14722   EXPECT_EQ("{\n"
14723             "\t/*\n"
14724             "\n"
14725             "\t*/\n"
14726             "}",
14727             format("{\n"
14728                    "\t/*\n"
14729                    "\n"
14730                    "\t*/\n"
14731                    "}",
14732                    Tab));
14733   EXPECT_EQ("{\n"
14734             "\t/*\n"
14735             " asdf\n"
14736             "\t*/\n"
14737             "}",
14738             format("{\n"
14739                    "\t/*\n"
14740                    " asdf\n"
14741                    "\t*/\n"
14742                    "}",
14743                    Tab));
14744   EXPECT_EQ("/* some\n"
14745             "   comment */",
14746             format(" \t \t /* some\n"
14747                    " \t \t    comment */",
14748                    Tab));
14749   EXPECT_EQ("int a; /* some\n"
14750             "   comment */",
14751             format(" \t \t int a; /* some\n"
14752                    " \t \t    comment */",
14753                    Tab));
14754   EXPECT_EQ("int a; /* some\n"
14755             "comment */",
14756             format(" \t \t int\ta; /* some\n"
14757                    " \t \t    comment */",
14758                    Tab));
14759   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14760             "    comment */",
14761             format(" \t \t f(\"\t\t\"); /* some\n"
14762                    " \t \t    comment */",
14763                    Tab));
14764   EXPECT_EQ("{\n"
14765             "\t/*\n"
14766             "\t * Comment\n"
14767             "\t */\n"
14768             "\tint i;\n"
14769             "}",
14770             format("{\n"
14771                    "\t/*\n"
14772                    "\t * Comment\n"
14773                    "\t */\n"
14774                    "\t int i;\n"
14775                    "}",
14776                    Tab));
14777   Tab.TabWidth = 2;
14778   Tab.IndentWidth = 2;
14779   EXPECT_EQ("{\n"
14780             "\t/* aaaa\n"
14781             "\t   bbbb */\n"
14782             "}",
14783             format("{\n"
14784                    "/* aaaa\n"
14785                    "   bbbb */\n"
14786                    "}",
14787                    Tab));
14788   EXPECT_EQ("{\n"
14789             "\t/*\n"
14790             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14791             "\t  bbbbbbbbbbbbb\n"
14792             "\t*/\n"
14793             "}",
14794             format("{\n"
14795                    "/*\n"
14796                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14797                    "*/\n"
14798                    "}",
14799                    Tab));
14800   Tab.AlignConsecutiveAssignments.Enabled = true;
14801   Tab.AlignConsecutiveDeclarations.Enabled = true;
14802   Tab.TabWidth = 4;
14803   Tab.IndentWidth = 4;
14804   verifyFormat("class Assign {\n"
14805                "\tvoid f() {\n"
14806                "\t\tint         x      = 123;\n"
14807                "\t\tint         random = 4;\n"
14808                "\t\tstd::string alphabet =\n"
14809                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14810                "\t}\n"
14811                "};",
14812                Tab);
14813   Tab.AlignOperands = FormatStyle::OAS_Align;
14814   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14815                "                 cccccccccccccccccccc;",
14816                Tab);
14817   // no alignment
14818   verifyFormat("int aaaaaaaaaa =\n"
14819                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14820                Tab);
14821   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14822                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14823                "                        : 333333333333333;",
14824                Tab);
14825   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14826   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14827   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14828                "               + cccccccccccccccccccc;",
14829                Tab);
14830 }
14831 
14832 TEST_F(FormatTest, ZeroTabWidth) {
14833   FormatStyle Tab = getLLVMStyleWithColumns(42);
14834   Tab.IndentWidth = 8;
14835   Tab.UseTab = FormatStyle::UT_Never;
14836   Tab.TabWidth = 0;
14837   EXPECT_EQ("void a(){\n"
14838             "    // line starts with '\t'\n"
14839             "};",
14840             format("void a(){\n"
14841                    "\t// line starts with '\t'\n"
14842                    "};",
14843                    Tab));
14844 
14845   EXPECT_EQ("void a(){\n"
14846             "    // line starts with '\t'\n"
14847             "};",
14848             format("void a(){\n"
14849                    "\t\t// line starts with '\t'\n"
14850                    "};",
14851                    Tab));
14852 
14853   Tab.UseTab = FormatStyle::UT_ForIndentation;
14854   EXPECT_EQ("void a(){\n"
14855             "    // line starts with '\t'\n"
14856             "};",
14857             format("void a(){\n"
14858                    "\t// line starts with '\t'\n"
14859                    "};",
14860                    Tab));
14861 
14862   EXPECT_EQ("void a(){\n"
14863             "    // line starts with '\t'\n"
14864             "};",
14865             format("void a(){\n"
14866                    "\t\t// line starts with '\t'\n"
14867                    "};",
14868                    Tab));
14869 
14870   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14871   EXPECT_EQ("void a(){\n"
14872             "    // line starts with '\t'\n"
14873             "};",
14874             format("void a(){\n"
14875                    "\t// line starts with '\t'\n"
14876                    "};",
14877                    Tab));
14878 
14879   EXPECT_EQ("void a(){\n"
14880             "    // line starts with '\t'\n"
14881             "};",
14882             format("void a(){\n"
14883                    "\t\t// line starts with '\t'\n"
14884                    "};",
14885                    Tab));
14886 
14887   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14888   EXPECT_EQ("void a(){\n"
14889             "    // line starts with '\t'\n"
14890             "};",
14891             format("void a(){\n"
14892                    "\t// line starts with '\t'\n"
14893                    "};",
14894                    Tab));
14895 
14896   EXPECT_EQ("void a(){\n"
14897             "    // line starts with '\t'\n"
14898             "};",
14899             format("void a(){\n"
14900                    "\t\t// line starts with '\t'\n"
14901                    "};",
14902                    Tab));
14903 
14904   Tab.UseTab = FormatStyle::UT_Always;
14905   EXPECT_EQ("void a(){\n"
14906             "// line starts with '\t'\n"
14907             "};",
14908             format("void a(){\n"
14909                    "\t// line starts with '\t'\n"
14910                    "};",
14911                    Tab));
14912 
14913   EXPECT_EQ("void a(){\n"
14914             "// line starts with '\t'\n"
14915             "};",
14916             format("void a(){\n"
14917                    "\t\t// line starts with '\t'\n"
14918                    "};",
14919                    Tab));
14920 }
14921 
14922 TEST_F(FormatTest, CalculatesOriginalColumn) {
14923   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14924             "q\"; /* some\n"
14925             "       comment */",
14926             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14927                    "q\"; /* some\n"
14928                    "       comment */",
14929                    getLLVMStyle()));
14930   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14931             "/* some\n"
14932             "   comment */",
14933             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14934                    " /* some\n"
14935                    "    comment */",
14936                    getLLVMStyle()));
14937   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14938             "qqq\n"
14939             "/* some\n"
14940             "   comment */",
14941             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14942                    "qqq\n"
14943                    " /* some\n"
14944                    "    comment */",
14945                    getLLVMStyle()));
14946   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14947             "wwww; /* some\n"
14948             "         comment */",
14949             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14950                    "wwww; /* some\n"
14951                    "         comment */",
14952                    getLLVMStyle()));
14953 }
14954 
14955 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14956   FormatStyle NoSpace = getLLVMStyle();
14957   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14958 
14959   verifyFormat("while(true)\n"
14960                "  continue;",
14961                NoSpace);
14962   verifyFormat("for(;;)\n"
14963                "  continue;",
14964                NoSpace);
14965   verifyFormat("if(true)\n"
14966                "  f();\n"
14967                "else if(true)\n"
14968                "  f();",
14969                NoSpace);
14970   verifyFormat("do {\n"
14971                "  do_something();\n"
14972                "} while(something());",
14973                NoSpace);
14974   verifyFormat("switch(x) {\n"
14975                "default:\n"
14976                "  break;\n"
14977                "}",
14978                NoSpace);
14979   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14980   verifyFormat("size_t x = sizeof(x);", NoSpace);
14981   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14982   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14983   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14984   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14985   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14986   verifyFormat("alignas(128) char a[128];", NoSpace);
14987   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14988   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14989   verifyFormat("int f() throw(Deprecated);", NoSpace);
14990   verifyFormat("typedef void (*cb)(int);", NoSpace);
14991   verifyFormat("T A::operator()();", NoSpace);
14992   verifyFormat("X A::operator++(T);", NoSpace);
14993   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14994 
14995   FormatStyle Space = getLLVMStyle();
14996   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14997 
14998   verifyFormat("int f ();", Space);
14999   verifyFormat("void f (int a, T b) {\n"
15000                "  while (true)\n"
15001                "    continue;\n"
15002                "}",
15003                Space);
15004   verifyFormat("if (true)\n"
15005                "  f ();\n"
15006                "else if (true)\n"
15007                "  f ();",
15008                Space);
15009   verifyFormat("do {\n"
15010                "  do_something ();\n"
15011                "} while (something ());",
15012                Space);
15013   verifyFormat("switch (x) {\n"
15014                "default:\n"
15015                "  break;\n"
15016                "}",
15017                Space);
15018   verifyFormat("A::A () : a (1) {}", Space);
15019   verifyFormat("void f () __attribute__ ((asdf));", Space);
15020   verifyFormat("*(&a + 1);\n"
15021                "&((&a)[1]);\n"
15022                "a[(b + c) * d];\n"
15023                "(((a + 1) * 2) + 3) * 4;",
15024                Space);
15025   verifyFormat("#define A(x) x", Space);
15026   verifyFormat("#define A (x) x", Space);
15027   verifyFormat("#if defined(x)\n"
15028                "#endif",
15029                Space);
15030   verifyFormat("auto i = std::make_unique<int> (5);", Space);
15031   verifyFormat("size_t x = sizeof (x);", Space);
15032   verifyFormat("auto f (int x) -> decltype (x);", Space);
15033   verifyFormat("auto f (int x) -> typeof (x);", Space);
15034   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
15035   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
15036   verifyFormat("int f (T x) noexcept (x.create ());", Space);
15037   verifyFormat("alignas (128) char a[128];", Space);
15038   verifyFormat("size_t x = alignof (MyType);", Space);
15039   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
15040   verifyFormat("int f () throw (Deprecated);", Space);
15041   verifyFormat("typedef void (*cb) (int);", Space);
15042   // FIXME these tests regressed behaviour.
15043   // verifyFormat("T A::operator() ();", Space);
15044   // verifyFormat("X A::operator++ (T);", Space);
15045   verifyFormat("auto lambda = [] () { return 0; };", Space);
15046   verifyFormat("int x = int (y);", Space);
15047 
15048   FormatStyle SomeSpace = getLLVMStyle();
15049   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
15050 
15051   verifyFormat("[]() -> float {}", SomeSpace);
15052   verifyFormat("[] (auto foo) {}", SomeSpace);
15053   verifyFormat("[foo]() -> int {}", SomeSpace);
15054   verifyFormat("int f();", SomeSpace);
15055   verifyFormat("void f (int a, T b) {\n"
15056                "  while (true)\n"
15057                "    continue;\n"
15058                "}",
15059                SomeSpace);
15060   verifyFormat("if (true)\n"
15061                "  f();\n"
15062                "else if (true)\n"
15063                "  f();",
15064                SomeSpace);
15065   verifyFormat("do {\n"
15066                "  do_something();\n"
15067                "} while (something());",
15068                SomeSpace);
15069   verifyFormat("switch (x) {\n"
15070                "default:\n"
15071                "  break;\n"
15072                "}",
15073                SomeSpace);
15074   verifyFormat("A::A() : a (1) {}", SomeSpace);
15075   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
15076   verifyFormat("*(&a + 1);\n"
15077                "&((&a)[1]);\n"
15078                "a[(b + c) * d];\n"
15079                "(((a + 1) * 2) + 3) * 4;",
15080                SomeSpace);
15081   verifyFormat("#define A(x) x", SomeSpace);
15082   verifyFormat("#define A (x) x", SomeSpace);
15083   verifyFormat("#if defined(x)\n"
15084                "#endif",
15085                SomeSpace);
15086   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
15087   verifyFormat("size_t x = sizeof (x);", SomeSpace);
15088   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
15089   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
15090   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
15091   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
15092   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
15093   verifyFormat("alignas (128) char a[128];", SomeSpace);
15094   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
15095   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15096                SomeSpace);
15097   verifyFormat("int f() throw (Deprecated);", SomeSpace);
15098   verifyFormat("typedef void (*cb) (int);", SomeSpace);
15099   verifyFormat("T A::operator()();", SomeSpace);
15100   // FIXME these tests regressed behaviour.
15101   // verifyFormat("X A::operator++ (T);", SomeSpace);
15102   verifyFormat("int x = int (y);", SomeSpace);
15103   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
15104 
15105   FormatStyle SpaceControlStatements = getLLVMStyle();
15106   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15107   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
15108 
15109   verifyFormat("while (true)\n"
15110                "  continue;",
15111                SpaceControlStatements);
15112   verifyFormat("if (true)\n"
15113                "  f();\n"
15114                "else if (true)\n"
15115                "  f();",
15116                SpaceControlStatements);
15117   verifyFormat("for (;;) {\n"
15118                "  do_something();\n"
15119                "}",
15120                SpaceControlStatements);
15121   verifyFormat("do {\n"
15122                "  do_something();\n"
15123                "} while (something());",
15124                SpaceControlStatements);
15125   verifyFormat("switch (x) {\n"
15126                "default:\n"
15127                "  break;\n"
15128                "}",
15129                SpaceControlStatements);
15130 
15131   FormatStyle SpaceFuncDecl = getLLVMStyle();
15132   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15133   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
15134 
15135   verifyFormat("int f ();", SpaceFuncDecl);
15136   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
15137   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
15138   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
15139   verifyFormat("#define A(x) x", SpaceFuncDecl);
15140   verifyFormat("#define A (x) x", SpaceFuncDecl);
15141   verifyFormat("#if defined(x)\n"
15142                "#endif",
15143                SpaceFuncDecl);
15144   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
15145   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
15146   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
15147   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
15148   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
15149   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
15150   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
15151   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
15152   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
15153   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15154                SpaceFuncDecl);
15155   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
15156   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
15157   // FIXME these tests regressed behaviour.
15158   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
15159   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
15160   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
15161   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
15162   verifyFormat("int x = int(y);", SpaceFuncDecl);
15163   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15164                SpaceFuncDecl);
15165 
15166   FormatStyle SpaceFuncDef = getLLVMStyle();
15167   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15168   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
15169 
15170   verifyFormat("int f();", SpaceFuncDef);
15171   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
15172   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
15173   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
15174   verifyFormat("#define A(x) x", SpaceFuncDef);
15175   verifyFormat("#define A (x) x", SpaceFuncDef);
15176   verifyFormat("#if defined(x)\n"
15177                "#endif",
15178                SpaceFuncDef);
15179   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
15180   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
15181   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
15182   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
15183   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
15184   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
15185   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
15186   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
15187   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
15188   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15189                SpaceFuncDef);
15190   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
15191   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
15192   verifyFormat("T A::operator()();", SpaceFuncDef);
15193   verifyFormat("X A::operator++(T);", SpaceFuncDef);
15194   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
15195   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
15196   verifyFormat("int x = int(y);", SpaceFuncDef);
15197   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15198                SpaceFuncDef);
15199 
15200   FormatStyle SpaceIfMacros = getLLVMStyle();
15201   SpaceIfMacros.IfMacros.clear();
15202   SpaceIfMacros.IfMacros.push_back("MYIF");
15203   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15204   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15205   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15206   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15207   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15208 
15209   FormatStyle SpaceForeachMacros = getLLVMStyle();
15210   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15211             FormatStyle::SBS_Never);
15212   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15213   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15214   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15215   verifyFormat("for (;;) {\n"
15216                "}",
15217                SpaceForeachMacros);
15218   verifyFormat("foreach (Item *item, itemlist) {\n"
15219                "}",
15220                SpaceForeachMacros);
15221   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15222                "}",
15223                SpaceForeachMacros);
15224   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15225                "}",
15226                SpaceForeachMacros);
15227   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15228 
15229   FormatStyle SomeSpace2 = getLLVMStyle();
15230   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15231   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15232   verifyFormat("[]() -> float {}", SomeSpace2);
15233   verifyFormat("[] (auto foo) {}", SomeSpace2);
15234   verifyFormat("[foo]() -> int {}", SomeSpace2);
15235   verifyFormat("int f();", SomeSpace2);
15236   verifyFormat("void f (int a, T b) {\n"
15237                "  while (true)\n"
15238                "    continue;\n"
15239                "}",
15240                SomeSpace2);
15241   verifyFormat("if (true)\n"
15242                "  f();\n"
15243                "else if (true)\n"
15244                "  f();",
15245                SomeSpace2);
15246   verifyFormat("do {\n"
15247                "  do_something();\n"
15248                "} while (something());",
15249                SomeSpace2);
15250   verifyFormat("switch (x) {\n"
15251                "default:\n"
15252                "  break;\n"
15253                "}",
15254                SomeSpace2);
15255   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15256   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15257   verifyFormat("*(&a + 1);\n"
15258                "&((&a)[1]);\n"
15259                "a[(b + c) * d];\n"
15260                "(((a + 1) * 2) + 3) * 4;",
15261                SomeSpace2);
15262   verifyFormat("#define A(x) x", SomeSpace2);
15263   verifyFormat("#define A (x) x", SomeSpace2);
15264   verifyFormat("#if defined(x)\n"
15265                "#endif",
15266                SomeSpace2);
15267   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15268   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15269   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15270   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15271   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15272   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15273   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15274   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15275   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15276   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15277                SomeSpace2);
15278   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15279   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15280   verifyFormat("T A::operator()();", SomeSpace2);
15281   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15282   verifyFormat("int x = int (y);", SomeSpace2);
15283   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15284 
15285   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15286   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15287   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15288       .AfterOverloadedOperator = true;
15289 
15290   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15291   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15292   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15293   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15294 
15295   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15296       .AfterOverloadedOperator = false;
15297 
15298   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15299   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15300   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15301   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15302 
15303   auto SpaceAfterRequires = getLLVMStyle();
15304   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15305   EXPECT_FALSE(
15306       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15307   EXPECT_FALSE(
15308       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15309   verifyFormat("void f(auto x)\n"
15310                "  requires requires(int i) { x + i; }\n"
15311                "{}",
15312                SpaceAfterRequires);
15313   verifyFormat("void f(auto x)\n"
15314                "  requires(requires(int i) { x + i; })\n"
15315                "{}",
15316                SpaceAfterRequires);
15317   verifyFormat("if (requires(int i) { x + i; })\n"
15318                "  return;",
15319                SpaceAfterRequires);
15320   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15321   verifyFormat("template <typename T>\n"
15322                "  requires(Foo<T>)\n"
15323                "class Bar;",
15324                SpaceAfterRequires);
15325 
15326   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15327   verifyFormat("void f(auto x)\n"
15328                "  requires requires(int i) { x + i; }\n"
15329                "{}",
15330                SpaceAfterRequires);
15331   verifyFormat("void f(auto x)\n"
15332                "  requires (requires(int i) { x + i; })\n"
15333                "{}",
15334                SpaceAfterRequires);
15335   verifyFormat("if (requires(int i) { x + i; })\n"
15336                "  return;",
15337                SpaceAfterRequires);
15338   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15339   verifyFormat("template <typename T>\n"
15340                "  requires (Foo<T>)\n"
15341                "class Bar;",
15342                SpaceAfterRequires);
15343 
15344   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15345   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15346   verifyFormat("void f(auto x)\n"
15347                "  requires requires (int i) { x + i; }\n"
15348                "{}",
15349                SpaceAfterRequires);
15350   verifyFormat("void f(auto x)\n"
15351                "  requires(requires (int i) { x + i; })\n"
15352                "{}",
15353                SpaceAfterRequires);
15354   verifyFormat("if (requires (int i) { x + i; })\n"
15355                "  return;",
15356                SpaceAfterRequires);
15357   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15358   verifyFormat("template <typename T>\n"
15359                "  requires(Foo<T>)\n"
15360                "class Bar;",
15361                SpaceAfterRequires);
15362 
15363   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15364   verifyFormat("void f(auto x)\n"
15365                "  requires requires (int i) { x + i; }\n"
15366                "{}",
15367                SpaceAfterRequires);
15368   verifyFormat("void f(auto x)\n"
15369                "  requires (requires (int i) { x + i; })\n"
15370                "{}",
15371                SpaceAfterRequires);
15372   verifyFormat("if (requires (int i) { x + i; })\n"
15373                "  return;",
15374                SpaceAfterRequires);
15375   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15376   verifyFormat("template <typename T>\n"
15377                "  requires (Foo<T>)\n"
15378                "class Bar;",
15379                SpaceAfterRequires);
15380 }
15381 
15382 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15383   FormatStyle Spaces = getLLVMStyle();
15384   Spaces.SpaceAfterLogicalNot = true;
15385 
15386   verifyFormat("bool x = ! y", Spaces);
15387   verifyFormat("if (! isFailure())", Spaces);
15388   verifyFormat("if (! (a && b))", Spaces);
15389   verifyFormat("\"Error!\"", Spaces);
15390   verifyFormat("! ! x", Spaces);
15391 }
15392 
15393 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15394   FormatStyle Spaces = getLLVMStyle();
15395 
15396   Spaces.SpacesInParentheses = true;
15397   verifyFormat("do_something( ::globalVar );", Spaces);
15398   verifyFormat("call( x, y, z );", Spaces);
15399   verifyFormat("call();", Spaces);
15400   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15401   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15402                Spaces);
15403   verifyFormat("while ( (bool)1 )\n"
15404                "  continue;",
15405                Spaces);
15406   verifyFormat("for ( ;; )\n"
15407                "  continue;",
15408                Spaces);
15409   verifyFormat("if ( true )\n"
15410                "  f();\n"
15411                "else if ( true )\n"
15412                "  f();",
15413                Spaces);
15414   verifyFormat("do {\n"
15415                "  do_something( (int)i );\n"
15416                "} while ( something() );",
15417                Spaces);
15418   verifyFormat("switch ( x ) {\n"
15419                "default:\n"
15420                "  break;\n"
15421                "}",
15422                Spaces);
15423 
15424   Spaces.SpacesInParentheses = false;
15425   Spaces.SpacesInCStyleCastParentheses = true;
15426   verifyFormat("Type *A = ( Type * )P;", Spaces);
15427   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15428   verifyFormat("x = ( int32 )y;", Spaces);
15429   verifyFormat("int a = ( int )(2.0f);", Spaces);
15430   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15431   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15432   verifyFormat("#define x (( int )-1)", Spaces);
15433 
15434   // Run the first set of tests again with:
15435   Spaces.SpacesInParentheses = false;
15436   Spaces.SpaceInEmptyParentheses = true;
15437   Spaces.SpacesInCStyleCastParentheses = true;
15438   verifyFormat("call(x, y, z);", Spaces);
15439   verifyFormat("call( );", Spaces);
15440   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15441   verifyFormat("while (( bool )1)\n"
15442                "  continue;",
15443                Spaces);
15444   verifyFormat("for (;;)\n"
15445                "  continue;",
15446                Spaces);
15447   verifyFormat("if (true)\n"
15448                "  f( );\n"
15449                "else if (true)\n"
15450                "  f( );",
15451                Spaces);
15452   verifyFormat("do {\n"
15453                "  do_something(( int )i);\n"
15454                "} while (something( ));",
15455                Spaces);
15456   verifyFormat("switch (x) {\n"
15457                "default:\n"
15458                "  break;\n"
15459                "}",
15460                Spaces);
15461 
15462   // Run the first set of tests again with:
15463   Spaces.SpaceAfterCStyleCast = true;
15464   verifyFormat("call(x, y, z);", Spaces);
15465   verifyFormat("call( );", Spaces);
15466   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15467   verifyFormat("while (( bool ) 1)\n"
15468                "  continue;",
15469                Spaces);
15470   verifyFormat("for (;;)\n"
15471                "  continue;",
15472                Spaces);
15473   verifyFormat("if (true)\n"
15474                "  f( );\n"
15475                "else if (true)\n"
15476                "  f( );",
15477                Spaces);
15478   verifyFormat("do {\n"
15479                "  do_something(( int ) i);\n"
15480                "} while (something( ));",
15481                Spaces);
15482   verifyFormat("switch (x) {\n"
15483                "default:\n"
15484                "  break;\n"
15485                "}",
15486                Spaces);
15487   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15488   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15489   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15490   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15491   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15492 
15493   // Run subset of tests again with:
15494   Spaces.SpacesInCStyleCastParentheses = false;
15495   Spaces.SpaceAfterCStyleCast = true;
15496   verifyFormat("while ((bool) 1)\n"
15497                "  continue;",
15498                Spaces);
15499   verifyFormat("do {\n"
15500                "  do_something((int) i);\n"
15501                "} while (something( ));",
15502                Spaces);
15503 
15504   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15505   verifyFormat("size_t idx = (size_t) a;", Spaces);
15506   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15507   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15508   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15509   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15510   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15511   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15512   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15513   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15514   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15515   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15516   Spaces.ColumnLimit = 80;
15517   Spaces.IndentWidth = 4;
15518   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15519   verifyFormat("void foo( ) {\n"
15520                "    size_t foo = (*(function))(\n"
15521                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15522                "BarrrrrrrrrrrrLong,\n"
15523                "        FoooooooooLooooong);\n"
15524                "}",
15525                Spaces);
15526   Spaces.SpaceAfterCStyleCast = false;
15527   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15528   verifyFormat("size_t idx = (size_t)a;", Spaces);
15529   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15530   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15531   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15532   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15533   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15534 
15535   verifyFormat("void foo( ) {\n"
15536                "    size_t foo = (*(function))(\n"
15537                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15538                "BarrrrrrrrrrrrLong,\n"
15539                "        FoooooooooLooooong);\n"
15540                "}",
15541                Spaces);
15542 }
15543 
15544 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15545   verifyFormat("int a[5];");
15546   verifyFormat("a[3] += 42;");
15547 
15548   FormatStyle Spaces = getLLVMStyle();
15549   Spaces.SpacesInSquareBrackets = true;
15550   // Not lambdas.
15551   verifyFormat("int a[ 5 ];", Spaces);
15552   verifyFormat("a[ 3 ] += 42;", Spaces);
15553   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15554   verifyFormat("double &operator[](int i) { return 0; }\n"
15555                "int i;",
15556                Spaces);
15557   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15558   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15559   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15560   // Lambdas.
15561   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15562   verifyFormat("return [ i, args... ] {};", Spaces);
15563   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15564   verifyFormat("int foo = [ = ]() {};", Spaces);
15565   verifyFormat("int foo = [ & ]() {};", Spaces);
15566   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15567   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15568 }
15569 
15570 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15571   FormatStyle NoSpaceStyle = getLLVMStyle();
15572   verifyFormat("int a[5];", NoSpaceStyle);
15573   verifyFormat("a[3] += 42;", NoSpaceStyle);
15574 
15575   verifyFormat("int a[1];", NoSpaceStyle);
15576   verifyFormat("int 1 [a];", NoSpaceStyle);
15577   verifyFormat("int a[1][2];", NoSpaceStyle);
15578   verifyFormat("a[7] = 5;", NoSpaceStyle);
15579   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15580   verifyFormat("f([] {})", NoSpaceStyle);
15581 
15582   FormatStyle Space = getLLVMStyle();
15583   Space.SpaceBeforeSquareBrackets = true;
15584   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15585   verifyFormat("return [i, args...] {};", Space);
15586 
15587   verifyFormat("int a [5];", Space);
15588   verifyFormat("a [3] += 42;", Space);
15589   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15590   verifyFormat("double &operator[](int i) { return 0; }\n"
15591                "int i;",
15592                Space);
15593   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15594   verifyFormat("int i = a [a][a]->f();", Space);
15595   verifyFormat("int i = (*b) [a]->f();", Space);
15596 
15597   verifyFormat("int a [1];", Space);
15598   verifyFormat("int 1 [a];", Space);
15599   verifyFormat("int a [1][2];", Space);
15600   verifyFormat("a [7] = 5;", Space);
15601   verifyFormat("int a = (f()) [23];", Space);
15602   verifyFormat("f([] {})", Space);
15603 }
15604 
15605 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15606   verifyFormat("int a = 5;");
15607   verifyFormat("a += 42;");
15608   verifyFormat("a or_eq 8;");
15609 
15610   FormatStyle Spaces = getLLVMStyle();
15611   Spaces.SpaceBeforeAssignmentOperators = false;
15612   verifyFormat("int a= 5;", Spaces);
15613   verifyFormat("a+= 42;", Spaces);
15614   verifyFormat("a or_eq 8;", Spaces);
15615 }
15616 
15617 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15618   verifyFormat("class Foo : public Bar {};");
15619   verifyFormat("Foo::Foo() : foo(1) {}");
15620   verifyFormat("for (auto a : b) {\n}");
15621   verifyFormat("int x = a ? b : c;");
15622   verifyFormat("{\n"
15623                "label0:\n"
15624                "  int x = 0;\n"
15625                "}");
15626   verifyFormat("switch (x) {\n"
15627                "case 1:\n"
15628                "default:\n"
15629                "}");
15630   verifyFormat("switch (allBraces) {\n"
15631                "case 1: {\n"
15632                "  break;\n"
15633                "}\n"
15634                "case 2: {\n"
15635                "  [[fallthrough]];\n"
15636                "}\n"
15637                "default: {\n"
15638                "  break;\n"
15639                "}\n"
15640                "}");
15641 
15642   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15643   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15644   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15645   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15646   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15647   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15648   verifyFormat("{\n"
15649                "label1:\n"
15650                "  int x = 0;\n"
15651                "}",
15652                CtorInitializerStyle);
15653   verifyFormat("switch (x) {\n"
15654                "case 1:\n"
15655                "default:\n"
15656                "}",
15657                CtorInitializerStyle);
15658   verifyFormat("switch (allBraces) {\n"
15659                "case 1: {\n"
15660                "  break;\n"
15661                "}\n"
15662                "case 2: {\n"
15663                "  [[fallthrough]];\n"
15664                "}\n"
15665                "default: {\n"
15666                "  break;\n"
15667                "}\n"
15668                "}",
15669                CtorInitializerStyle);
15670   CtorInitializerStyle.BreakConstructorInitializers =
15671       FormatStyle::BCIS_AfterColon;
15672   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15673                "    aaaaaaaaaaaaaaaa(1),\n"
15674                "    bbbbbbbbbbbbbbbb(2) {}",
15675                CtorInitializerStyle);
15676   CtorInitializerStyle.BreakConstructorInitializers =
15677       FormatStyle::BCIS_BeforeComma;
15678   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15679                "    : aaaaaaaaaaaaaaaa(1)\n"
15680                "    , bbbbbbbbbbbbbbbb(2) {}",
15681                CtorInitializerStyle);
15682   CtorInitializerStyle.BreakConstructorInitializers =
15683       FormatStyle::BCIS_BeforeColon;
15684   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15685                "    : aaaaaaaaaaaaaaaa(1),\n"
15686                "      bbbbbbbbbbbbbbbb(2) {}",
15687                CtorInitializerStyle);
15688   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15689   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15690                ": aaaaaaaaaaaaaaaa(1),\n"
15691                "  bbbbbbbbbbbbbbbb(2) {}",
15692                CtorInitializerStyle);
15693 
15694   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15695   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15696   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15697   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15698   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15699   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15700   verifyFormat("{\n"
15701                "label2:\n"
15702                "  int x = 0;\n"
15703                "}",
15704                InheritanceStyle);
15705   verifyFormat("switch (x) {\n"
15706                "case 1:\n"
15707                "default:\n"
15708                "}",
15709                InheritanceStyle);
15710   verifyFormat("switch (allBraces) {\n"
15711                "case 1: {\n"
15712                "  break;\n"
15713                "}\n"
15714                "case 2: {\n"
15715                "  [[fallthrough]];\n"
15716                "}\n"
15717                "default: {\n"
15718                "  break;\n"
15719                "}\n"
15720                "}",
15721                InheritanceStyle);
15722   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15723   verifyFormat("class Foooooooooooooooooooooo\n"
15724                "    : public aaaaaaaaaaaaaaaaaa,\n"
15725                "      public bbbbbbbbbbbbbbbbbb {\n"
15726                "}",
15727                InheritanceStyle);
15728   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15729   verifyFormat("class Foooooooooooooooooooooo:\n"
15730                "    public aaaaaaaaaaaaaaaaaa,\n"
15731                "    public bbbbbbbbbbbbbbbbbb {\n"
15732                "}",
15733                InheritanceStyle);
15734   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15735   verifyFormat("class Foooooooooooooooooooooo\n"
15736                "    : public aaaaaaaaaaaaaaaaaa\n"
15737                "    , public bbbbbbbbbbbbbbbbbb {\n"
15738                "}",
15739                InheritanceStyle);
15740   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15741   verifyFormat("class Foooooooooooooooooooooo\n"
15742                "    : public aaaaaaaaaaaaaaaaaa,\n"
15743                "      public bbbbbbbbbbbbbbbbbb {\n"
15744                "}",
15745                InheritanceStyle);
15746   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15747   verifyFormat("class Foooooooooooooooooooooo\n"
15748                ": public aaaaaaaaaaaaaaaaaa,\n"
15749                "  public bbbbbbbbbbbbbbbbbb {}",
15750                InheritanceStyle);
15751 
15752   FormatStyle ForLoopStyle = getLLVMStyle();
15753   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15754   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15755   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15756   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15757   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15758   verifyFormat("{\n"
15759                "label2:\n"
15760                "  int x = 0;\n"
15761                "}",
15762                ForLoopStyle);
15763   verifyFormat("switch (x) {\n"
15764                "case 1:\n"
15765                "default:\n"
15766                "}",
15767                ForLoopStyle);
15768   verifyFormat("switch (allBraces) {\n"
15769                "case 1: {\n"
15770                "  break;\n"
15771                "}\n"
15772                "case 2: {\n"
15773                "  [[fallthrough]];\n"
15774                "}\n"
15775                "default: {\n"
15776                "  break;\n"
15777                "}\n"
15778                "}",
15779                ForLoopStyle);
15780 
15781   FormatStyle CaseStyle = getLLVMStyle();
15782   CaseStyle.SpaceBeforeCaseColon = true;
15783   verifyFormat("class Foo : public Bar {};", CaseStyle);
15784   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15785   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15786   verifyFormat("int x = a ? b : c;", CaseStyle);
15787   verifyFormat("switch (x) {\n"
15788                "case 1 :\n"
15789                "default :\n"
15790                "}",
15791                CaseStyle);
15792   verifyFormat("switch (allBraces) {\n"
15793                "case 1 : {\n"
15794                "  break;\n"
15795                "}\n"
15796                "case 2 : {\n"
15797                "  [[fallthrough]];\n"
15798                "}\n"
15799                "default : {\n"
15800                "  break;\n"
15801                "}\n"
15802                "}",
15803                CaseStyle);
15804 
15805   FormatStyle NoSpaceStyle = getLLVMStyle();
15806   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15807   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15808   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15809   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15810   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15811   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15812   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15813   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15814   verifyFormat("{\n"
15815                "label3:\n"
15816                "  int x = 0;\n"
15817                "}",
15818                NoSpaceStyle);
15819   verifyFormat("switch (x) {\n"
15820                "case 1:\n"
15821                "default:\n"
15822                "}",
15823                NoSpaceStyle);
15824   verifyFormat("switch (allBraces) {\n"
15825                "case 1: {\n"
15826                "  break;\n"
15827                "}\n"
15828                "case 2: {\n"
15829                "  [[fallthrough]];\n"
15830                "}\n"
15831                "default: {\n"
15832                "  break;\n"
15833                "}\n"
15834                "}",
15835                NoSpaceStyle);
15836 
15837   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15838   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15839   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15840   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15841   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15842   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15843   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15844   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15845   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15846   verifyFormat("{\n"
15847                "label3:\n"
15848                "  int x = 0;\n"
15849                "}",
15850                InvertedSpaceStyle);
15851   verifyFormat("switch (x) {\n"
15852                "case 1 :\n"
15853                "case 2 : {\n"
15854                "  break;\n"
15855                "}\n"
15856                "default :\n"
15857                "  break;\n"
15858                "}",
15859                InvertedSpaceStyle);
15860   verifyFormat("switch (allBraces) {\n"
15861                "case 1 : {\n"
15862                "  break;\n"
15863                "}\n"
15864                "case 2 : {\n"
15865                "  [[fallthrough]];\n"
15866                "}\n"
15867                "default : {\n"
15868                "  break;\n"
15869                "}\n"
15870                "}",
15871                InvertedSpaceStyle);
15872 }
15873 
15874 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15875   FormatStyle Style = getLLVMStyle();
15876 
15877   Style.PointerAlignment = FormatStyle::PAS_Left;
15878   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15879   verifyFormat("void* const* x = NULL;", Style);
15880 
15881 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15882   do {                                                                         \
15883     Style.PointerAlignment = FormatStyle::Pointers;                            \
15884     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15885     verifyFormat(Code, Style);                                                 \
15886   } while (false)
15887 
15888   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15889   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15890   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15891 
15892   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15893   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15894   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15895 
15896   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15897   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15898   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15899 
15900   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15901   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15902   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15903 
15904   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15905   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15906                         SAPQ_Default);
15907   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15908                         SAPQ_Default);
15909 
15910   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15911   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15912                         SAPQ_Before);
15913   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15914                         SAPQ_Before);
15915 
15916   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15917   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15918   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15919                         SAPQ_After);
15920 
15921   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15922   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15923   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15924 
15925 #undef verifyQualifierSpaces
15926 
15927   FormatStyle Spaces = getLLVMStyle();
15928   Spaces.AttributeMacros.push_back("qualified");
15929   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15930   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15931   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15932   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15933   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15934   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15935   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15936   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
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 
15943   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15944   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15945   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15946   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15947   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15948   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15949   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15950   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15951   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15952   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15953   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15954   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15955   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15956   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15957   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15958 
15959   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15960   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15961   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15962   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15963   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15964   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15965   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15966   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15967 }
15968 
15969 TEST_F(FormatTest, AlignConsecutiveMacros) {
15970   FormatStyle Style = getLLVMStyle();
15971   Style.AlignConsecutiveAssignments.Enabled = true;
15972   Style.AlignConsecutiveDeclarations.Enabled = true;
15973 
15974   verifyFormat("#define a 3\n"
15975                "#define bbbb 4\n"
15976                "#define ccc (5)",
15977                Style);
15978 
15979   verifyFormat("#define f(x) (x * x)\n"
15980                "#define fff(x, y, z) (x * y + z)\n"
15981                "#define ffff(x, y) (x - y)",
15982                Style);
15983 
15984   verifyFormat("#define foo(x, y) (x + y)\n"
15985                "#define bar (5, 6)(2 + 2)",
15986                Style);
15987 
15988   verifyFormat("#define a 3\n"
15989                "#define bbbb 4\n"
15990                "#define ccc (5)\n"
15991                "#define f(x) (x * x)\n"
15992                "#define fff(x, y, z) (x * y + z)\n"
15993                "#define ffff(x, y) (x - y)",
15994                Style);
15995 
15996   Style.AlignConsecutiveMacros.Enabled = true;
15997   verifyFormat("#define a    3\n"
15998                "#define bbbb 4\n"
15999                "#define ccc  (5)",
16000                Style);
16001 
16002   verifyFormat("#define f(x)         (x * x)\n"
16003                "#define fff(x, y, z) (x * y + z)\n"
16004                "#define ffff(x, y)   (x - y)",
16005                Style);
16006 
16007   verifyFormat("#define foo(x, y) (x + y)\n"
16008                "#define bar       (5, 6)(2 + 2)",
16009                Style);
16010 
16011   verifyFormat("#define a            3\n"
16012                "#define bbbb         4\n"
16013                "#define ccc          (5)\n"
16014                "#define f(x)         (x * x)\n"
16015                "#define fff(x, y, z) (x * y + z)\n"
16016                "#define ffff(x, y)   (x - y)",
16017                Style);
16018 
16019   verifyFormat("#define a         5\n"
16020                "#define foo(x, y) (x + y)\n"
16021                "#define CCC       (6)\n"
16022                "auto lambda = []() {\n"
16023                "  auto  ii = 0;\n"
16024                "  float j  = 0;\n"
16025                "  return 0;\n"
16026                "};\n"
16027                "int   i  = 0;\n"
16028                "float i2 = 0;\n"
16029                "auto  v  = type{\n"
16030                "    i = 1,   //\n"
16031                "    (i = 2), //\n"
16032                "    i = 3    //\n"
16033                "};",
16034                Style);
16035 
16036   Style.AlignConsecutiveMacros.Enabled = false;
16037   Style.ColumnLimit = 20;
16038 
16039   verifyFormat("#define a          \\\n"
16040                "  \"aabbbbbbbbbbbb\"\n"
16041                "#define D          \\\n"
16042                "  \"aabbbbbbbbbbbb\" \\\n"
16043                "  \"ccddeeeeeeeee\"\n"
16044                "#define B          \\\n"
16045                "  \"QQQQQQQQQQQQQ\"  \\\n"
16046                "  \"FFFFFFFFFFFFF\"  \\\n"
16047                "  \"LLLLLLLL\"\n",
16048                Style);
16049 
16050   Style.AlignConsecutiveMacros.Enabled = true;
16051   verifyFormat("#define a          \\\n"
16052                "  \"aabbbbbbbbbbbb\"\n"
16053                "#define D          \\\n"
16054                "  \"aabbbbbbbbbbbb\" \\\n"
16055                "  \"ccddeeeeeeeee\"\n"
16056                "#define B          \\\n"
16057                "  \"QQQQQQQQQQQQQ\"  \\\n"
16058                "  \"FFFFFFFFFFFFF\"  \\\n"
16059                "  \"LLLLLLLL\"\n",
16060                Style);
16061 
16062   // Test across comments
16063   Style.MaxEmptyLinesToKeep = 10;
16064   Style.ReflowComments = false;
16065   Style.AlignConsecutiveMacros.AcrossComments = true;
16066   EXPECT_EQ("#define a    3\n"
16067             "// line comment\n"
16068             "#define bbbb 4\n"
16069             "#define ccc  (5)",
16070             format("#define a 3\n"
16071                    "// line comment\n"
16072                    "#define bbbb 4\n"
16073                    "#define ccc (5)",
16074                    Style));
16075 
16076   EXPECT_EQ("#define a    3\n"
16077             "/* block comment */\n"
16078             "#define bbbb 4\n"
16079             "#define ccc  (5)",
16080             format("#define a  3\n"
16081                    "/* block comment */\n"
16082                    "#define bbbb 4\n"
16083                    "#define ccc (5)",
16084                    Style));
16085 
16086   EXPECT_EQ("#define a    3\n"
16087             "/* multi-line *\n"
16088             " * block comment */\n"
16089             "#define bbbb 4\n"
16090             "#define ccc  (5)",
16091             format("#define a 3\n"
16092                    "/* multi-line *\n"
16093                    " * block comment */\n"
16094                    "#define bbbb 4\n"
16095                    "#define ccc (5)",
16096                    Style));
16097 
16098   EXPECT_EQ("#define a    3\n"
16099             "// multi-line line comment\n"
16100             "//\n"
16101             "#define bbbb 4\n"
16102             "#define ccc  (5)",
16103             format("#define a  3\n"
16104                    "// multi-line line comment\n"
16105                    "//\n"
16106                    "#define bbbb 4\n"
16107                    "#define ccc (5)",
16108                    Style));
16109 
16110   EXPECT_EQ("#define a 3\n"
16111             "// empty lines still break.\n"
16112             "\n"
16113             "#define bbbb 4\n"
16114             "#define ccc  (5)",
16115             format("#define a     3\n"
16116                    "// empty lines still break.\n"
16117                    "\n"
16118                    "#define bbbb     4\n"
16119                    "#define ccc  (5)",
16120                    Style));
16121 
16122   // Test across empty lines
16123   Style.AlignConsecutiveMacros.AcrossComments = false;
16124   Style.AlignConsecutiveMacros.AcrossEmptyLines = true;
16125   EXPECT_EQ("#define a    3\n"
16126             "\n"
16127             "#define bbbb 4\n"
16128             "#define ccc  (5)",
16129             format("#define a 3\n"
16130                    "\n"
16131                    "#define bbbb 4\n"
16132                    "#define ccc (5)",
16133                    Style));
16134 
16135   EXPECT_EQ("#define a    3\n"
16136             "\n"
16137             "\n"
16138             "\n"
16139             "#define bbbb 4\n"
16140             "#define ccc  (5)",
16141             format("#define a        3\n"
16142                    "\n"
16143                    "\n"
16144                    "\n"
16145                    "#define bbbb 4\n"
16146                    "#define ccc (5)",
16147                    Style));
16148 
16149   EXPECT_EQ("#define a 3\n"
16150             "// comments should break alignment\n"
16151             "//\n"
16152             "#define bbbb 4\n"
16153             "#define ccc  (5)",
16154             format("#define a        3\n"
16155                    "// comments should break alignment\n"
16156                    "//\n"
16157                    "#define bbbb 4\n"
16158                    "#define ccc (5)",
16159                    Style));
16160 
16161   // Test across empty lines and comments
16162   Style.AlignConsecutiveMacros.AcrossComments = true;
16163   verifyFormat("#define a    3\n"
16164                "\n"
16165                "// line comment\n"
16166                "#define bbbb 4\n"
16167                "#define ccc  (5)",
16168                Style);
16169 
16170   EXPECT_EQ("#define a    3\n"
16171             "\n"
16172             "\n"
16173             "/* multi-line *\n"
16174             " * block comment */\n"
16175             "\n"
16176             "\n"
16177             "#define bbbb 4\n"
16178             "#define ccc  (5)",
16179             format("#define a 3\n"
16180                    "\n"
16181                    "\n"
16182                    "/* multi-line *\n"
16183                    " * block comment */\n"
16184                    "\n"
16185                    "\n"
16186                    "#define bbbb 4\n"
16187                    "#define ccc (5)",
16188                    Style));
16189 
16190   EXPECT_EQ("#define a    3\n"
16191             "\n"
16192             "\n"
16193             "/* multi-line *\n"
16194             " * block comment */\n"
16195             "\n"
16196             "\n"
16197             "#define bbbb 4\n"
16198             "#define ccc  (5)",
16199             format("#define a 3\n"
16200                    "\n"
16201                    "\n"
16202                    "/* multi-line *\n"
16203                    " * block comment */\n"
16204                    "\n"
16205                    "\n"
16206                    "#define bbbb 4\n"
16207                    "#define ccc       (5)",
16208                    Style));
16209 }
16210 
16211 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16212   FormatStyle Alignment = getLLVMStyle();
16213   Alignment.AlignConsecutiveMacros.Enabled = true;
16214   Alignment.AlignConsecutiveAssignments.Enabled = true;
16215   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16216 
16217   Alignment.MaxEmptyLinesToKeep = 10;
16218   /* Test alignment across empty lines */
16219   EXPECT_EQ("int a           = 5;\n"
16220             "\n"
16221             "int oneTwoThree = 123;",
16222             format("int a       = 5;\n"
16223                    "\n"
16224                    "int oneTwoThree= 123;",
16225                    Alignment));
16226   EXPECT_EQ("int a           = 5;\n"
16227             "int one         = 1;\n"
16228             "\n"
16229             "int oneTwoThree = 123;",
16230             format("int a = 5;\n"
16231                    "int one = 1;\n"
16232                    "\n"
16233                    "int oneTwoThree = 123;",
16234                    Alignment));
16235   EXPECT_EQ("int a           = 5;\n"
16236             "int one         = 1;\n"
16237             "\n"
16238             "int oneTwoThree = 123;\n"
16239             "int oneTwo      = 12;",
16240             format("int a = 5;\n"
16241                    "int one = 1;\n"
16242                    "\n"
16243                    "int oneTwoThree = 123;\n"
16244                    "int oneTwo = 12;",
16245                    Alignment));
16246 
16247   /* Test across comments */
16248   EXPECT_EQ("int a = 5;\n"
16249             "/* block comment */\n"
16250             "int oneTwoThree = 123;",
16251             format("int a = 5;\n"
16252                    "/* block comment */\n"
16253                    "int oneTwoThree=123;",
16254                    Alignment));
16255 
16256   EXPECT_EQ("int a = 5;\n"
16257             "// line comment\n"
16258             "int oneTwoThree = 123;",
16259             format("int a = 5;\n"
16260                    "// line comment\n"
16261                    "int oneTwoThree=123;",
16262                    Alignment));
16263 
16264   /* Test across comments and newlines */
16265   EXPECT_EQ("int a = 5;\n"
16266             "\n"
16267             "/* block comment */\n"
16268             "int oneTwoThree = 123;",
16269             format("int a = 5;\n"
16270                    "\n"
16271                    "/* block comment */\n"
16272                    "int oneTwoThree=123;",
16273                    Alignment));
16274 
16275   EXPECT_EQ("int a = 5;\n"
16276             "\n"
16277             "// line comment\n"
16278             "int oneTwoThree = 123;",
16279             format("int a = 5;\n"
16280                    "\n"
16281                    "// line comment\n"
16282                    "int oneTwoThree=123;",
16283                    Alignment));
16284 }
16285 
16286 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16287   FormatStyle Alignment = getLLVMStyle();
16288   Alignment.AlignConsecutiveDeclarations.Enabled = true;
16289   Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true;
16290   Alignment.AlignConsecutiveDeclarations.AcrossComments = true;
16291 
16292   Alignment.MaxEmptyLinesToKeep = 10;
16293   /* Test alignment across empty lines */
16294   EXPECT_EQ("int         a = 5;\n"
16295             "\n"
16296             "float const oneTwoThree = 123;",
16297             format("int a = 5;\n"
16298                    "\n"
16299                    "float const oneTwoThree = 123;",
16300                    Alignment));
16301   EXPECT_EQ("int         a = 5;\n"
16302             "float const one = 1;\n"
16303             "\n"
16304             "int         oneTwoThree = 123;",
16305             format("int a = 5;\n"
16306                    "float const one = 1;\n"
16307                    "\n"
16308                    "int oneTwoThree = 123;",
16309                    Alignment));
16310 
16311   /* Test across comments */
16312   EXPECT_EQ("float const a = 5;\n"
16313             "/* block comment */\n"
16314             "int         oneTwoThree = 123;",
16315             format("float const a = 5;\n"
16316                    "/* block comment */\n"
16317                    "int oneTwoThree=123;",
16318                    Alignment));
16319 
16320   EXPECT_EQ("float const a = 5;\n"
16321             "// line comment\n"
16322             "int         oneTwoThree = 123;",
16323             format("float const a = 5;\n"
16324                    "// line comment\n"
16325                    "int oneTwoThree=123;",
16326                    Alignment));
16327 
16328   /* Test across comments and newlines */
16329   EXPECT_EQ("float const a = 5;\n"
16330             "\n"
16331             "/* block comment */\n"
16332             "int         oneTwoThree = 123;",
16333             format("float const a = 5;\n"
16334                    "\n"
16335                    "/* block comment */\n"
16336                    "int         oneTwoThree=123;",
16337                    Alignment));
16338 
16339   EXPECT_EQ("float const a = 5;\n"
16340             "\n"
16341             "// line comment\n"
16342             "int         oneTwoThree = 123;",
16343             format("float const a = 5;\n"
16344                    "\n"
16345                    "// line comment\n"
16346                    "int oneTwoThree=123;",
16347                    Alignment));
16348 }
16349 
16350 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16351   FormatStyle Alignment = getLLVMStyle();
16352   Alignment.AlignConsecutiveBitFields.Enabled = true;
16353   Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true;
16354   Alignment.AlignConsecutiveBitFields.AcrossComments = true;
16355 
16356   Alignment.MaxEmptyLinesToKeep = 10;
16357   /* Test alignment across empty lines */
16358   EXPECT_EQ("int a            : 5;\n"
16359             "\n"
16360             "int longbitfield : 6;",
16361             format("int a : 5;\n"
16362                    "\n"
16363                    "int longbitfield : 6;",
16364                    Alignment));
16365   EXPECT_EQ("int a            : 5;\n"
16366             "int one          : 1;\n"
16367             "\n"
16368             "int longbitfield : 6;",
16369             format("int a : 5;\n"
16370                    "int one : 1;\n"
16371                    "\n"
16372                    "int longbitfield : 6;",
16373                    Alignment));
16374 
16375   /* Test across comments */
16376   EXPECT_EQ("int a            : 5;\n"
16377             "/* block comment */\n"
16378             "int longbitfield : 6;",
16379             format("int a : 5;\n"
16380                    "/* block comment */\n"
16381                    "int longbitfield : 6;",
16382                    Alignment));
16383   EXPECT_EQ("int a            : 5;\n"
16384             "int one          : 1;\n"
16385             "// line comment\n"
16386             "int longbitfield : 6;",
16387             format("int a : 5;\n"
16388                    "int one : 1;\n"
16389                    "// line comment\n"
16390                    "int longbitfield : 6;",
16391                    Alignment));
16392 
16393   /* Test across comments and newlines */
16394   EXPECT_EQ("int a            : 5;\n"
16395             "/* block comment */\n"
16396             "\n"
16397             "int longbitfield : 6;",
16398             format("int a : 5;\n"
16399                    "/* block comment */\n"
16400                    "\n"
16401                    "int longbitfield : 6;",
16402                    Alignment));
16403   EXPECT_EQ("int a            : 5;\n"
16404             "int one          : 1;\n"
16405             "\n"
16406             "// line comment\n"
16407             "\n"
16408             "int longbitfield : 6;",
16409             format("int a : 5;\n"
16410                    "int one : 1;\n"
16411                    "\n"
16412                    "// line comment \n"
16413                    "\n"
16414                    "int longbitfield : 6;",
16415                    Alignment));
16416 }
16417 
16418 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16419   FormatStyle Alignment = getLLVMStyle();
16420   Alignment.AlignConsecutiveMacros.Enabled = true;
16421   Alignment.AlignConsecutiveAssignments.Enabled = true;
16422   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16423 
16424   Alignment.MaxEmptyLinesToKeep = 10;
16425   /* Test alignment across empty lines */
16426   EXPECT_EQ("int a = 5;\n"
16427             "\n"
16428             "int oneTwoThree = 123;",
16429             format("int a       = 5;\n"
16430                    "\n"
16431                    "int oneTwoThree= 123;",
16432                    Alignment));
16433   EXPECT_EQ("int a   = 5;\n"
16434             "int one = 1;\n"
16435             "\n"
16436             "int oneTwoThree = 123;",
16437             format("int a = 5;\n"
16438                    "int one = 1;\n"
16439                    "\n"
16440                    "int oneTwoThree = 123;",
16441                    Alignment));
16442 
16443   /* Test across comments */
16444   EXPECT_EQ("int a           = 5;\n"
16445             "/* block comment */\n"
16446             "int oneTwoThree = 123;",
16447             format("int a = 5;\n"
16448                    "/* block comment */\n"
16449                    "int oneTwoThree=123;",
16450                    Alignment));
16451 
16452   EXPECT_EQ("int a           = 5;\n"
16453             "// line comment\n"
16454             "int oneTwoThree = 123;",
16455             format("int a = 5;\n"
16456                    "// line comment\n"
16457                    "int oneTwoThree=123;",
16458                    Alignment));
16459 
16460   EXPECT_EQ("int a           = 5;\n"
16461             "/*\n"
16462             " * multi-line block comment\n"
16463             " */\n"
16464             "int oneTwoThree = 123;",
16465             format("int a = 5;\n"
16466                    "/*\n"
16467                    " * multi-line block comment\n"
16468                    " */\n"
16469                    "int oneTwoThree=123;",
16470                    Alignment));
16471 
16472   EXPECT_EQ("int a           = 5;\n"
16473             "//\n"
16474             "// multi-line line comment\n"
16475             "//\n"
16476             "int oneTwoThree = 123;",
16477             format("int a = 5;\n"
16478                    "//\n"
16479                    "// multi-line line comment\n"
16480                    "//\n"
16481                    "int oneTwoThree=123;",
16482                    Alignment));
16483 
16484   /* Test across comments and newlines */
16485   EXPECT_EQ("int a = 5;\n"
16486             "\n"
16487             "/* block comment */\n"
16488             "int oneTwoThree = 123;",
16489             format("int a = 5;\n"
16490                    "\n"
16491                    "/* block comment */\n"
16492                    "int oneTwoThree=123;",
16493                    Alignment));
16494 
16495   EXPECT_EQ("int a = 5;\n"
16496             "\n"
16497             "// line comment\n"
16498             "int oneTwoThree = 123;",
16499             format("int a = 5;\n"
16500                    "\n"
16501                    "// line comment\n"
16502                    "int oneTwoThree=123;",
16503                    Alignment));
16504 }
16505 
16506 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16507   FormatStyle Alignment = getLLVMStyle();
16508   Alignment.AlignConsecutiveMacros.Enabled = true;
16509   Alignment.AlignConsecutiveAssignments.Enabled = true;
16510   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16511   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16512   verifyFormat("int a           = 5;\n"
16513                "int oneTwoThree = 123;",
16514                Alignment);
16515   verifyFormat("int a           = method();\n"
16516                "int oneTwoThree = 133;",
16517                Alignment);
16518   verifyFormat("a &= 5;\n"
16519                "bcd *= 5;\n"
16520                "ghtyf += 5;\n"
16521                "dvfvdb -= 5;\n"
16522                "a /= 5;\n"
16523                "vdsvsv %= 5;\n"
16524                "sfdbddfbdfbb ^= 5;\n"
16525                "dvsdsv |= 5;\n"
16526                "int dsvvdvsdvvv = 123;",
16527                Alignment);
16528   verifyFormat("int i = 1, j = 10;\n"
16529                "something = 2000;",
16530                Alignment);
16531   verifyFormat("something = 2000;\n"
16532                "int i = 1, j = 10;\n",
16533                Alignment);
16534   verifyFormat("something = 2000;\n"
16535                "another   = 911;\n"
16536                "int i = 1, j = 10;\n"
16537                "oneMore = 1;\n"
16538                "i       = 2;",
16539                Alignment);
16540   verifyFormat("int a   = 5;\n"
16541                "int one = 1;\n"
16542                "method();\n"
16543                "int oneTwoThree = 123;\n"
16544                "int oneTwo      = 12;",
16545                Alignment);
16546   verifyFormat("int oneTwoThree = 123;\n"
16547                "int oneTwo      = 12;\n"
16548                "method();\n",
16549                Alignment);
16550   verifyFormat("int oneTwoThree = 123; // comment\n"
16551                "int oneTwo      = 12;  // comment",
16552                Alignment);
16553 
16554   // Bug 25167
16555   /* Uncomment when fixed
16556     verifyFormat("#if A\n"
16557                  "#else\n"
16558                  "int aaaaaaaa = 12;\n"
16559                  "#endif\n"
16560                  "#if B\n"
16561                  "#else\n"
16562                  "int a = 12;\n"
16563                  "#endif\n",
16564                  Alignment);
16565     verifyFormat("enum foo {\n"
16566                  "#if A\n"
16567                  "#else\n"
16568                  "  aaaaaaaa = 12;\n"
16569                  "#endif\n"
16570                  "#if B\n"
16571                  "#else\n"
16572                  "  a = 12;\n"
16573                  "#endif\n"
16574                  "};\n",
16575                  Alignment);
16576   */
16577 
16578   Alignment.MaxEmptyLinesToKeep = 10;
16579   /* Test alignment across empty lines */
16580   EXPECT_EQ("int a           = 5;\n"
16581             "\n"
16582             "int oneTwoThree = 123;",
16583             format("int a       = 5;\n"
16584                    "\n"
16585                    "int oneTwoThree= 123;",
16586                    Alignment));
16587   EXPECT_EQ("int a           = 5;\n"
16588             "int one         = 1;\n"
16589             "\n"
16590             "int oneTwoThree = 123;",
16591             format("int a = 5;\n"
16592                    "int one = 1;\n"
16593                    "\n"
16594                    "int oneTwoThree = 123;",
16595                    Alignment));
16596   EXPECT_EQ("int a           = 5;\n"
16597             "int one         = 1;\n"
16598             "\n"
16599             "int oneTwoThree = 123;\n"
16600             "int oneTwo      = 12;",
16601             format("int a = 5;\n"
16602                    "int one = 1;\n"
16603                    "\n"
16604                    "int oneTwoThree = 123;\n"
16605                    "int oneTwo = 12;",
16606                    Alignment));
16607 
16608   /* Test across comments */
16609   EXPECT_EQ("int a           = 5;\n"
16610             "/* block comment */\n"
16611             "int oneTwoThree = 123;",
16612             format("int a = 5;\n"
16613                    "/* block comment */\n"
16614                    "int oneTwoThree=123;",
16615                    Alignment));
16616 
16617   EXPECT_EQ("int a           = 5;\n"
16618             "// line comment\n"
16619             "int oneTwoThree = 123;",
16620             format("int a = 5;\n"
16621                    "// line comment\n"
16622                    "int oneTwoThree=123;",
16623                    Alignment));
16624 
16625   /* Test across comments and newlines */
16626   EXPECT_EQ("int a           = 5;\n"
16627             "\n"
16628             "/* block comment */\n"
16629             "int oneTwoThree = 123;",
16630             format("int a = 5;\n"
16631                    "\n"
16632                    "/* block comment */\n"
16633                    "int oneTwoThree=123;",
16634                    Alignment));
16635 
16636   EXPECT_EQ("int a           = 5;\n"
16637             "\n"
16638             "// line comment\n"
16639             "int oneTwoThree = 123;",
16640             format("int a = 5;\n"
16641                    "\n"
16642                    "// line comment\n"
16643                    "int oneTwoThree=123;",
16644                    Alignment));
16645 
16646   EXPECT_EQ("int a           = 5;\n"
16647             "//\n"
16648             "// multi-line line comment\n"
16649             "//\n"
16650             "int oneTwoThree = 123;",
16651             format("int a = 5;\n"
16652                    "//\n"
16653                    "// multi-line line comment\n"
16654                    "//\n"
16655                    "int oneTwoThree=123;",
16656                    Alignment));
16657 
16658   EXPECT_EQ("int a           = 5;\n"
16659             "/*\n"
16660             " *  multi-line block comment\n"
16661             " */\n"
16662             "int oneTwoThree = 123;",
16663             format("int a = 5;\n"
16664                    "/*\n"
16665                    " *  multi-line block comment\n"
16666                    " */\n"
16667                    "int oneTwoThree=123;",
16668                    Alignment));
16669 
16670   EXPECT_EQ("int a           = 5;\n"
16671             "\n"
16672             "/* block comment */\n"
16673             "\n"
16674             "\n"
16675             "\n"
16676             "int oneTwoThree = 123;",
16677             format("int a = 5;\n"
16678                    "\n"
16679                    "/* block comment */\n"
16680                    "\n"
16681                    "\n"
16682                    "\n"
16683                    "int oneTwoThree=123;",
16684                    Alignment));
16685 
16686   EXPECT_EQ("int a           = 5;\n"
16687             "\n"
16688             "// line comment\n"
16689             "\n"
16690             "\n"
16691             "\n"
16692             "int oneTwoThree = 123;",
16693             format("int a = 5;\n"
16694                    "\n"
16695                    "// line comment\n"
16696                    "\n"
16697                    "\n"
16698                    "\n"
16699                    "int oneTwoThree=123;",
16700                    Alignment));
16701 
16702   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16703   verifyFormat("#define A \\\n"
16704                "  int aaaa       = 12; \\\n"
16705                "  int b          = 23; \\\n"
16706                "  int ccc        = 234; \\\n"
16707                "  int dddddddddd = 2345;",
16708                Alignment);
16709   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16710   verifyFormat("#define A               \\\n"
16711                "  int aaaa       = 12;  \\\n"
16712                "  int b          = 23;  \\\n"
16713                "  int ccc        = 234; \\\n"
16714                "  int dddddddddd = 2345;",
16715                Alignment);
16716   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16717   verifyFormat("#define A                                                      "
16718                "                \\\n"
16719                "  int aaaa       = 12;                                         "
16720                "                \\\n"
16721                "  int b          = 23;                                         "
16722                "                \\\n"
16723                "  int ccc        = 234;                                        "
16724                "                \\\n"
16725                "  int dddddddddd = 2345;",
16726                Alignment);
16727   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16728                "k = 4, int l = 5,\n"
16729                "                  int m = 6) {\n"
16730                "  int j      = 10;\n"
16731                "  otherThing = 1;\n"
16732                "}",
16733                Alignment);
16734   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16735                "  int i   = 1;\n"
16736                "  int j   = 2;\n"
16737                "  int big = 10000;\n"
16738                "}",
16739                Alignment);
16740   verifyFormat("class C {\n"
16741                "public:\n"
16742                "  int i            = 1;\n"
16743                "  virtual void f() = 0;\n"
16744                "};",
16745                Alignment);
16746   verifyFormat("int i = 1;\n"
16747                "if (SomeType t = getSomething()) {\n"
16748                "}\n"
16749                "int j   = 2;\n"
16750                "int big = 10000;",
16751                Alignment);
16752   verifyFormat("int j = 7;\n"
16753                "for (int k = 0; k < N; ++k) {\n"
16754                "}\n"
16755                "int j   = 2;\n"
16756                "int big = 10000;\n"
16757                "}",
16758                Alignment);
16759   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16760   verifyFormat("int i = 1;\n"
16761                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16762                "    = someLooooooooooooooooongFunction();\n"
16763                "int j = 2;",
16764                Alignment);
16765   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16766   verifyFormat("int i = 1;\n"
16767                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16768                "    someLooooooooooooooooongFunction();\n"
16769                "int j = 2;",
16770                Alignment);
16771 
16772   verifyFormat("auto lambda = []() {\n"
16773                "  auto i = 0;\n"
16774                "  return 0;\n"
16775                "};\n"
16776                "int i  = 0;\n"
16777                "auto v = type{\n"
16778                "    i = 1,   //\n"
16779                "    (i = 2), //\n"
16780                "    i = 3    //\n"
16781                "};",
16782                Alignment);
16783 
16784   verifyFormat(
16785       "int i      = 1;\n"
16786       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16787       "                          loooooooooooooooooooooongParameterB);\n"
16788       "int j      = 2;",
16789       Alignment);
16790 
16791   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16792                "          typename B   = very_long_type_name_1,\n"
16793                "          typename T_2 = very_long_type_name_2>\n"
16794                "auto foo() {}\n",
16795                Alignment);
16796   verifyFormat("int a, b = 1;\n"
16797                "int c  = 2;\n"
16798                "int dd = 3;\n",
16799                Alignment);
16800   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16801                "float b[1][] = {{3.f}};\n",
16802                Alignment);
16803   verifyFormat("for (int i = 0; i < 1; i++)\n"
16804                "  int x = 1;\n",
16805                Alignment);
16806   verifyFormat("for (i = 0; i < 1; i++)\n"
16807                "  x = 1;\n"
16808                "y = 1;\n",
16809                Alignment);
16810 
16811   Alignment.ReflowComments = true;
16812   Alignment.ColumnLimit = 50;
16813   EXPECT_EQ("int x   = 0;\n"
16814             "int yy  = 1; /// specificlennospace\n"
16815             "int zzz = 2;\n",
16816             format("int x   = 0;\n"
16817                    "int yy  = 1; ///specificlennospace\n"
16818                    "int zzz = 2;\n",
16819                    Alignment));
16820 }
16821 
16822 TEST_F(FormatTest, AlignCompoundAssignments) {
16823   FormatStyle Alignment = getLLVMStyle();
16824   Alignment.AlignConsecutiveAssignments.Enabled = true;
16825   Alignment.AlignConsecutiveAssignments.AlignCompound = true;
16826   Alignment.AlignConsecutiveAssignments.PadOperators = false;
16827   verifyFormat("sfdbddfbdfbb    = 5;\n"
16828                "dvsdsv          = 5;\n"
16829                "int dsvvdvsdvvv = 123;",
16830                Alignment);
16831   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16832                "dvsdsv         |= 5;\n"
16833                "int dsvvdvsdvvv = 123;",
16834                Alignment);
16835   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16836                "dvsdsv        <<= 5;\n"
16837                "int dsvvdvsdvvv = 123;",
16838                Alignment);
16839   // Test that `<=` is not treated as a compound assignment.
16840   verifyFormat("aa &= 5;\n"
16841                "b <= 10;\n"
16842                "c = 15;",
16843                Alignment);
16844   Alignment.AlignConsecutiveAssignments.PadOperators = true;
16845   verifyFormat("sfdbddfbdfbb    = 5;\n"
16846                "dvsdsv          = 5;\n"
16847                "int dsvvdvsdvvv = 123;",
16848                Alignment);
16849   verifyFormat("sfdbddfbdfbb    ^= 5;\n"
16850                "dvsdsv          |= 5;\n"
16851                "int dsvvdvsdvvv  = 123;",
16852                Alignment);
16853   verifyFormat("sfdbddfbdfbb     ^= 5;\n"
16854                "dvsdsv          <<= 5;\n"
16855                "int dsvvdvsdvvv   = 123;",
16856                Alignment);
16857   EXPECT_EQ("a   += 5;\n"
16858             "one  = 1;\n"
16859             "\n"
16860             "oneTwoThree = 123;\n",
16861             format("a += 5;\n"
16862                    "one = 1;\n"
16863                    "\n"
16864                    "oneTwoThree = 123;\n",
16865                    Alignment));
16866   EXPECT_EQ("a   += 5;\n"
16867             "one  = 1;\n"
16868             "//\n"
16869             "oneTwoThree = 123;\n",
16870             format("a += 5;\n"
16871                    "one = 1;\n"
16872                    "//\n"
16873                    "oneTwoThree = 123;\n",
16874                    Alignment));
16875   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16876   EXPECT_EQ("a           += 5;\n"
16877             "one          = 1;\n"
16878             "\n"
16879             "oneTwoThree  = 123;\n",
16880             format("a += 5;\n"
16881                    "one = 1;\n"
16882                    "\n"
16883                    "oneTwoThree = 123;\n",
16884                    Alignment));
16885   EXPECT_EQ("a   += 5;\n"
16886             "one  = 1;\n"
16887             "//\n"
16888             "oneTwoThree = 123;\n",
16889             format("a += 5;\n"
16890                    "one = 1;\n"
16891                    "//\n"
16892                    "oneTwoThree = 123;\n",
16893                    Alignment));
16894   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false;
16895   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16896   EXPECT_EQ("a   += 5;\n"
16897             "one  = 1;\n"
16898             "\n"
16899             "oneTwoThree = 123;\n",
16900             format("a += 5;\n"
16901                    "one = 1;\n"
16902                    "\n"
16903                    "oneTwoThree = 123;\n",
16904                    Alignment));
16905   EXPECT_EQ("a           += 5;\n"
16906             "one          = 1;\n"
16907             "//\n"
16908             "oneTwoThree  = 123;\n",
16909             format("a += 5;\n"
16910                    "one = 1;\n"
16911                    "//\n"
16912                    "oneTwoThree = 123;\n",
16913                    Alignment));
16914   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16915   EXPECT_EQ("a            += 5;\n"
16916             "one         >>= 1;\n"
16917             "\n"
16918             "oneTwoThree   = 123;\n",
16919             format("a += 5;\n"
16920                    "one >>= 1;\n"
16921                    "\n"
16922                    "oneTwoThree = 123;\n",
16923                    Alignment));
16924   EXPECT_EQ("a            += 5;\n"
16925             "one           = 1;\n"
16926             "//\n"
16927             "oneTwoThree <<= 123;\n",
16928             format("a += 5;\n"
16929                    "one = 1;\n"
16930                    "//\n"
16931                    "oneTwoThree <<= 123;\n",
16932                    Alignment));
16933 }
16934 
16935 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16936   FormatStyle Alignment = getLLVMStyle();
16937   Alignment.AlignConsecutiveMacros.Enabled = true;
16938   verifyFormat("int a = 5;\n"
16939                "int oneTwoThree = 123;",
16940                Alignment);
16941   verifyFormat("int a = 5;\n"
16942                "int oneTwoThree = 123;",
16943                Alignment);
16944 
16945   Alignment.AlignConsecutiveAssignments.Enabled = true;
16946   verifyFormat("int a           = 5;\n"
16947                "int oneTwoThree = 123;",
16948                Alignment);
16949   verifyFormat("int a           = method();\n"
16950                "int oneTwoThree = 133;",
16951                Alignment);
16952   verifyFormat("aa <= 5;\n"
16953                "a &= 5;\n"
16954                "bcd *= 5;\n"
16955                "ghtyf += 5;\n"
16956                "dvfvdb -= 5;\n"
16957                "a /= 5;\n"
16958                "vdsvsv %= 5;\n"
16959                "sfdbddfbdfbb ^= 5;\n"
16960                "dvsdsv |= 5;\n"
16961                "int dsvvdvsdvvv = 123;",
16962                Alignment);
16963   verifyFormat("int i = 1, j = 10;\n"
16964                "something = 2000;",
16965                Alignment);
16966   verifyFormat("something = 2000;\n"
16967                "int i = 1, j = 10;\n",
16968                Alignment);
16969   verifyFormat("something = 2000;\n"
16970                "another   = 911;\n"
16971                "int i = 1, j = 10;\n"
16972                "oneMore = 1;\n"
16973                "i       = 2;",
16974                Alignment);
16975   verifyFormat("int a   = 5;\n"
16976                "int one = 1;\n"
16977                "method();\n"
16978                "int oneTwoThree = 123;\n"
16979                "int oneTwo      = 12;",
16980                Alignment);
16981   verifyFormat("int oneTwoThree = 123;\n"
16982                "int oneTwo      = 12;\n"
16983                "method();\n",
16984                Alignment);
16985   verifyFormat("int oneTwoThree = 123; // comment\n"
16986                "int oneTwo      = 12;  // comment",
16987                Alignment);
16988   verifyFormat("int f()         = default;\n"
16989                "int &operator() = default;\n"
16990                "int &operator=() {",
16991                Alignment);
16992   verifyFormat("int f()         = delete;\n"
16993                "int &operator() = delete;\n"
16994                "int &operator=() {",
16995                Alignment);
16996   verifyFormat("int f()         = default; // comment\n"
16997                "int &operator() = default; // comment\n"
16998                "int &operator=() {",
16999                Alignment);
17000   verifyFormat("int f()         = default;\n"
17001                "int &operator() = default;\n"
17002                "int &operator==() {",
17003                Alignment);
17004   verifyFormat("int f()         = default;\n"
17005                "int &operator() = default;\n"
17006                "int &operator<=() {",
17007                Alignment);
17008   verifyFormat("int f()         = default;\n"
17009                "int &operator() = default;\n"
17010                "int &operator!=() {",
17011                Alignment);
17012   verifyFormat("int f()         = default;\n"
17013                "int &operator() = default;\n"
17014                "int &operator=();",
17015                Alignment);
17016   verifyFormat("int f()         = delete;\n"
17017                "int &operator() = delete;\n"
17018                "int &operator=();",
17019                Alignment);
17020   verifyFormat("/* long long padding */ int f() = default;\n"
17021                "int &operator()                 = default;\n"
17022                "int &operator/**/ =();",
17023                Alignment);
17024   // https://llvm.org/PR33697
17025   FormatStyle AlignmentWithPenalty = getLLVMStyle();
17026   AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true;
17027   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
17028   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
17029                "  void f() = delete;\n"
17030                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
17031                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
17032                "};\n",
17033                AlignmentWithPenalty);
17034 
17035   // Bug 25167
17036   /* Uncomment when fixed
17037     verifyFormat("#if A\n"
17038                  "#else\n"
17039                  "int aaaaaaaa = 12;\n"
17040                  "#endif\n"
17041                  "#if B\n"
17042                  "#else\n"
17043                  "int a = 12;\n"
17044                  "#endif\n",
17045                  Alignment);
17046     verifyFormat("enum foo {\n"
17047                  "#if A\n"
17048                  "#else\n"
17049                  "  aaaaaaaa = 12;\n"
17050                  "#endif\n"
17051                  "#if B\n"
17052                  "#else\n"
17053                  "  a = 12;\n"
17054                  "#endif\n"
17055                  "};\n",
17056                  Alignment);
17057   */
17058 
17059   EXPECT_EQ("int a = 5;\n"
17060             "\n"
17061             "int oneTwoThree = 123;",
17062             format("int a       = 5;\n"
17063                    "\n"
17064                    "int oneTwoThree= 123;",
17065                    Alignment));
17066   EXPECT_EQ("int a   = 5;\n"
17067             "int one = 1;\n"
17068             "\n"
17069             "int oneTwoThree = 123;",
17070             format("int a = 5;\n"
17071                    "int one = 1;\n"
17072                    "\n"
17073                    "int oneTwoThree = 123;",
17074                    Alignment));
17075   EXPECT_EQ("int a   = 5;\n"
17076             "int one = 1;\n"
17077             "\n"
17078             "int oneTwoThree = 123;\n"
17079             "int oneTwo      = 12;",
17080             format("int a = 5;\n"
17081                    "int one = 1;\n"
17082                    "\n"
17083                    "int oneTwoThree = 123;\n"
17084                    "int oneTwo = 12;",
17085                    Alignment));
17086   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17087   verifyFormat("#define A \\\n"
17088                "  int aaaa       = 12; \\\n"
17089                "  int b          = 23; \\\n"
17090                "  int ccc        = 234; \\\n"
17091                "  int dddddddddd = 2345;",
17092                Alignment);
17093   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17094   verifyFormat("#define A               \\\n"
17095                "  int aaaa       = 12;  \\\n"
17096                "  int b          = 23;  \\\n"
17097                "  int ccc        = 234; \\\n"
17098                "  int dddddddddd = 2345;",
17099                Alignment);
17100   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17101   verifyFormat("#define A                                                      "
17102                "                \\\n"
17103                "  int aaaa       = 12;                                         "
17104                "                \\\n"
17105                "  int b          = 23;                                         "
17106                "                \\\n"
17107                "  int ccc        = 234;                                        "
17108                "                \\\n"
17109                "  int dddddddddd = 2345;",
17110                Alignment);
17111   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17112                "k = 4, int l = 5,\n"
17113                "                  int m = 6) {\n"
17114                "  int j      = 10;\n"
17115                "  otherThing = 1;\n"
17116                "}",
17117                Alignment);
17118   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17119                "  int i   = 1;\n"
17120                "  int j   = 2;\n"
17121                "  int big = 10000;\n"
17122                "}",
17123                Alignment);
17124   verifyFormat("class C {\n"
17125                "public:\n"
17126                "  int i            = 1;\n"
17127                "  virtual void f() = 0;\n"
17128                "};",
17129                Alignment);
17130   verifyFormat("int i = 1;\n"
17131                "if (SomeType t = getSomething()) {\n"
17132                "}\n"
17133                "int j   = 2;\n"
17134                "int big = 10000;",
17135                Alignment);
17136   verifyFormat("int j = 7;\n"
17137                "for (int k = 0; k < N; ++k) {\n"
17138                "}\n"
17139                "int j   = 2;\n"
17140                "int big = 10000;\n"
17141                "}",
17142                Alignment);
17143   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17144   verifyFormat("int i = 1;\n"
17145                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17146                "    = someLooooooooooooooooongFunction();\n"
17147                "int j = 2;",
17148                Alignment);
17149   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17150   verifyFormat("int i = 1;\n"
17151                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17152                "    someLooooooooooooooooongFunction();\n"
17153                "int j = 2;",
17154                Alignment);
17155 
17156   verifyFormat("auto lambda = []() {\n"
17157                "  auto i = 0;\n"
17158                "  return 0;\n"
17159                "};\n"
17160                "int i  = 0;\n"
17161                "auto v = type{\n"
17162                "    i = 1,   //\n"
17163                "    (i = 2), //\n"
17164                "    i = 3    //\n"
17165                "};",
17166                Alignment);
17167 
17168   verifyFormat(
17169       "int i      = 1;\n"
17170       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17171       "                          loooooooooooooooooooooongParameterB);\n"
17172       "int j      = 2;",
17173       Alignment);
17174 
17175   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17176                "          typename B   = very_long_type_name_1,\n"
17177                "          typename T_2 = very_long_type_name_2>\n"
17178                "auto foo() {}\n",
17179                Alignment);
17180   verifyFormat("int a, b = 1;\n"
17181                "int c  = 2;\n"
17182                "int dd = 3;\n",
17183                Alignment);
17184   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17185                "float b[1][] = {{3.f}};\n",
17186                Alignment);
17187   verifyFormat("for (int i = 0; i < 1; i++)\n"
17188                "  int x = 1;\n",
17189                Alignment);
17190   verifyFormat("for (i = 0; i < 1; i++)\n"
17191                "  x = 1;\n"
17192                "y = 1;\n",
17193                Alignment);
17194 
17195   EXPECT_EQ(Alignment.ReflowComments, true);
17196   Alignment.ColumnLimit = 50;
17197   EXPECT_EQ("int x   = 0;\n"
17198             "int yy  = 1; /// specificlennospace\n"
17199             "int zzz = 2;\n",
17200             format("int x   = 0;\n"
17201                    "int yy  = 1; ///specificlennospace\n"
17202                    "int zzz = 2;\n",
17203                    Alignment));
17204 
17205   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17206                "auto b                     = [] {\n"
17207                "  f();\n"
17208                "  return;\n"
17209                "};",
17210                Alignment);
17211   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17212                "auto b                     = g([] {\n"
17213                "  f();\n"
17214                "  return;\n"
17215                "});",
17216                Alignment);
17217   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17218                "auto b                     = g(param, [] {\n"
17219                "  f();\n"
17220                "  return;\n"
17221                "});",
17222                Alignment);
17223   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17224                "auto b                     = [] {\n"
17225                "  if (condition) {\n"
17226                "    return;\n"
17227                "  }\n"
17228                "};",
17229                Alignment);
17230 
17231   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17232                "           ccc ? aaaaa : bbbbb,\n"
17233                "           dddddddddddddddddddddddddd);",
17234                Alignment);
17235   // FIXME: https://llvm.org/PR53497
17236   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
17237   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17238   //              "    ccc ? aaaaa : bbbbb,\n"
17239   //              "    dddddddddddddddddddddddddd);",
17240   //              Alignment);
17241 }
17242 
17243 TEST_F(FormatTest, AlignConsecutiveBitFields) {
17244   FormatStyle Alignment = getLLVMStyle();
17245   Alignment.AlignConsecutiveBitFields.Enabled = true;
17246   verifyFormat("int const a     : 5;\n"
17247                "int oneTwoThree : 23;",
17248                Alignment);
17249 
17250   // Initializers are allowed starting with c++2a
17251   verifyFormat("int const a     : 5 = 1;\n"
17252                "int oneTwoThree : 23 = 0;",
17253                Alignment);
17254 
17255   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17256   verifyFormat("int const a           : 5;\n"
17257                "int       oneTwoThree : 23;",
17258                Alignment);
17259 
17260   verifyFormat("int const a           : 5;  // comment\n"
17261                "int       oneTwoThree : 23; // comment",
17262                Alignment);
17263 
17264   verifyFormat("int const a           : 5 = 1;\n"
17265                "int       oneTwoThree : 23 = 0;",
17266                Alignment);
17267 
17268   Alignment.AlignConsecutiveAssignments.Enabled = true;
17269   verifyFormat("int const a           : 5  = 1;\n"
17270                "int       oneTwoThree : 23 = 0;",
17271                Alignment);
17272   verifyFormat("int const a           : 5  = {1};\n"
17273                "int       oneTwoThree : 23 = 0;",
17274                Alignment);
17275 
17276   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
17277   verifyFormat("int const a          :5;\n"
17278                "int       oneTwoThree:23;",
17279                Alignment);
17280 
17281   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
17282   verifyFormat("int const a           :5;\n"
17283                "int       oneTwoThree :23;",
17284                Alignment);
17285 
17286   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
17287   verifyFormat("int const a          : 5;\n"
17288                "int       oneTwoThree: 23;",
17289                Alignment);
17290 
17291   // Known limitations: ':' is only recognized as a bitfield colon when
17292   // followed by a number.
17293   /*
17294   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
17295                "int a           : 5;",
17296                Alignment);
17297   */
17298 }
17299 
17300 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
17301   FormatStyle Alignment = getLLVMStyle();
17302   Alignment.AlignConsecutiveMacros.Enabled = true;
17303   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17304   verifyFormat("float const a = 5;\n"
17305                "int oneTwoThree = 123;",
17306                Alignment);
17307   verifyFormat("int a = 5;\n"
17308                "float const oneTwoThree = 123;",
17309                Alignment);
17310 
17311   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17312   verifyFormat("float const a = 5;\n"
17313                "int         oneTwoThree = 123;",
17314                Alignment);
17315   verifyFormat("int         a = method();\n"
17316                "float const oneTwoThree = 133;",
17317                Alignment);
17318   verifyFormat("int i = 1, j = 10;\n"
17319                "something = 2000;",
17320                Alignment);
17321   verifyFormat("something = 2000;\n"
17322                "int i = 1, j = 10;\n",
17323                Alignment);
17324   verifyFormat("float      something = 2000;\n"
17325                "double     another = 911;\n"
17326                "int        i = 1, j = 10;\n"
17327                "const int *oneMore = 1;\n"
17328                "unsigned   i = 2;",
17329                Alignment);
17330   verifyFormat("float a = 5;\n"
17331                "int   one = 1;\n"
17332                "method();\n"
17333                "const double       oneTwoThree = 123;\n"
17334                "const unsigned int oneTwo = 12;",
17335                Alignment);
17336   verifyFormat("int      oneTwoThree{0}; // comment\n"
17337                "unsigned oneTwo;         // comment",
17338                Alignment);
17339   verifyFormat("unsigned int       *a;\n"
17340                "int                *b;\n"
17341                "unsigned int Const *c;\n"
17342                "unsigned int const *d;\n"
17343                "unsigned int Const &e;\n"
17344                "unsigned int const &f;",
17345                Alignment);
17346   verifyFormat("Const unsigned int *c;\n"
17347                "const unsigned int *d;\n"
17348                "Const unsigned int &e;\n"
17349                "const unsigned int &f;\n"
17350                "const unsigned      g;\n"
17351                "Const unsigned      h;",
17352                Alignment);
17353   EXPECT_EQ("float const a = 5;\n"
17354             "\n"
17355             "int oneTwoThree = 123;",
17356             format("float const   a = 5;\n"
17357                    "\n"
17358                    "int           oneTwoThree= 123;",
17359                    Alignment));
17360   EXPECT_EQ("float a = 5;\n"
17361             "int   one = 1;\n"
17362             "\n"
17363             "unsigned oneTwoThree = 123;",
17364             format("float    a = 5;\n"
17365                    "int      one = 1;\n"
17366                    "\n"
17367                    "unsigned oneTwoThree = 123;",
17368                    Alignment));
17369   EXPECT_EQ("float a = 5;\n"
17370             "int   one = 1;\n"
17371             "\n"
17372             "unsigned oneTwoThree = 123;\n"
17373             "int      oneTwo = 12;",
17374             format("float    a = 5;\n"
17375                    "int one = 1;\n"
17376                    "\n"
17377                    "unsigned oneTwoThree = 123;\n"
17378                    "int oneTwo = 12;",
17379                    Alignment));
17380   // Function prototype alignment
17381   verifyFormat("int    a();\n"
17382                "double b();",
17383                Alignment);
17384   verifyFormat("int    a(int x);\n"
17385                "double b();",
17386                Alignment);
17387   unsigned OldColumnLimit = Alignment.ColumnLimit;
17388   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17389   // otherwise the function parameters will be re-flowed onto a single line.
17390   Alignment.ColumnLimit = 0;
17391   EXPECT_EQ("int    a(int   x,\n"
17392             "         float y);\n"
17393             "double b(int    x,\n"
17394             "         double y);",
17395             format("int a(int x,\n"
17396                    " float y);\n"
17397                    "double b(int x,\n"
17398                    " double y);",
17399                    Alignment));
17400   // This ensures that function parameters of function declarations are
17401   // correctly indented when their owning functions are indented.
17402   // The failure case here is for 'double y' to not be indented enough.
17403   EXPECT_EQ("double a(int x);\n"
17404             "int    b(int    y,\n"
17405             "         double z);",
17406             format("double a(int x);\n"
17407                    "int b(int y,\n"
17408                    " double z);",
17409                    Alignment));
17410   // Set ColumnLimit low so that we induce wrapping immediately after
17411   // the function name and opening paren.
17412   Alignment.ColumnLimit = 13;
17413   verifyFormat("int function(\n"
17414                "    int  x,\n"
17415                "    bool y);",
17416                Alignment);
17417   Alignment.ColumnLimit = OldColumnLimit;
17418   // Ensure function pointers don't screw up recursive alignment
17419   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17420                "double b();",
17421                Alignment);
17422   Alignment.AlignConsecutiveAssignments.Enabled = true;
17423   // Ensure recursive alignment is broken by function braces, so that the
17424   // "a = 1" does not align with subsequent assignments inside the function
17425   // body.
17426   verifyFormat("int func(int a = 1) {\n"
17427                "  int b  = 2;\n"
17428                "  int cc = 3;\n"
17429                "}",
17430                Alignment);
17431   verifyFormat("float      something = 2000;\n"
17432                "double     another   = 911;\n"
17433                "int        i = 1, j = 10;\n"
17434                "const int *oneMore = 1;\n"
17435                "unsigned   i       = 2;",
17436                Alignment);
17437   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17438                "unsigned oneTwo      = 0;   // comment",
17439                Alignment);
17440   // Make sure that scope is correctly tracked, in the absence of braces
17441   verifyFormat("for (int i = 0; i < n; i++)\n"
17442                "  j = i;\n"
17443                "double x = 1;\n",
17444                Alignment);
17445   verifyFormat("if (int i = 0)\n"
17446                "  j = i;\n"
17447                "double x = 1;\n",
17448                Alignment);
17449   // Ensure operator[] and operator() are comprehended
17450   verifyFormat("struct test {\n"
17451                "  long long int foo();\n"
17452                "  int           operator[](int a);\n"
17453                "  double        bar();\n"
17454                "};\n",
17455                Alignment);
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   // http://llvm.org/PR52914
17463   verifyFormat("char *a[]     = {\"a\", // comment\n"
17464                "                 \"bb\"};\n"
17465                "int   bbbbbbb = 0;",
17466                Alignment);
17467 
17468   // PAS_Right
17469   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17470             "  int const i   = 1;\n"
17471             "  int      *j   = 2;\n"
17472             "  int       big = 10000;\n"
17473             "\n"
17474             "  unsigned oneTwoThree = 123;\n"
17475             "  int      oneTwo      = 12;\n"
17476             "  method();\n"
17477             "  float k  = 2;\n"
17478             "  int   ll = 10000;\n"
17479             "}",
17480             format("void SomeFunction(int parameter= 0) {\n"
17481                    " int const  i= 1;\n"
17482                    "  int *j=2;\n"
17483                    " int big  =  10000;\n"
17484                    "\n"
17485                    "unsigned oneTwoThree  =123;\n"
17486                    "int oneTwo = 12;\n"
17487                    "  method();\n"
17488                    "float k= 2;\n"
17489                    "int ll=10000;\n"
17490                    "}",
17491                    Alignment));
17492   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17493             "  int const i   = 1;\n"
17494             "  int     **j   = 2, ***k;\n"
17495             "  int      &k   = i;\n"
17496             "  int     &&l   = i + j;\n"
17497             "  int       big = 10000;\n"
17498             "\n"
17499             "  unsigned oneTwoThree = 123;\n"
17500             "  int      oneTwo      = 12;\n"
17501             "  method();\n"
17502             "  float k  = 2;\n"
17503             "  int   ll = 10000;\n"
17504             "}",
17505             format("void SomeFunction(int parameter= 0) {\n"
17506                    " int const  i= 1;\n"
17507                    "  int **j=2,***k;\n"
17508                    "int &k=i;\n"
17509                    "int &&l=i+j;\n"
17510                    " int big  =  10000;\n"
17511                    "\n"
17512                    "unsigned oneTwoThree  =123;\n"
17513                    "int oneTwo = 12;\n"
17514                    "  method();\n"
17515                    "float k= 2;\n"
17516                    "int ll=10000;\n"
17517                    "}",
17518                    Alignment));
17519   // variables are aligned at their name, pointers are at the right most
17520   // position
17521   verifyFormat("int   *a;\n"
17522                "int  **b;\n"
17523                "int ***c;\n"
17524                "int    foobar;\n",
17525                Alignment);
17526 
17527   // PAS_Left
17528   FormatStyle AlignmentLeft = Alignment;
17529   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17530   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17531             "  int const i   = 1;\n"
17532             "  int*      j   = 2;\n"
17533             "  int       big = 10000;\n"
17534             "\n"
17535             "  unsigned oneTwoThree = 123;\n"
17536             "  int      oneTwo      = 12;\n"
17537             "  method();\n"
17538             "  float k  = 2;\n"
17539             "  int   ll = 10000;\n"
17540             "}",
17541             format("void SomeFunction(int parameter= 0) {\n"
17542                    " int const  i= 1;\n"
17543                    "  int *j=2;\n"
17544                    " int big  =  10000;\n"
17545                    "\n"
17546                    "unsigned oneTwoThree  =123;\n"
17547                    "int oneTwo = 12;\n"
17548                    "  method();\n"
17549                    "float k= 2;\n"
17550                    "int ll=10000;\n"
17551                    "}",
17552                    AlignmentLeft));
17553   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17554             "  int const i   = 1;\n"
17555             "  int**     j   = 2;\n"
17556             "  int&      k   = i;\n"
17557             "  int&&     l   = i + j;\n"
17558             "  int       big = 10000;\n"
17559             "\n"
17560             "  unsigned oneTwoThree = 123;\n"
17561             "  int      oneTwo      = 12;\n"
17562             "  method();\n"
17563             "  float k  = 2;\n"
17564             "  int   ll = 10000;\n"
17565             "}",
17566             format("void SomeFunction(int parameter= 0) {\n"
17567                    " int const  i= 1;\n"
17568                    "  int **j=2;\n"
17569                    "int &k=i;\n"
17570                    "int &&l=i+j;\n"
17571                    " int big  =  10000;\n"
17572                    "\n"
17573                    "unsigned oneTwoThree  =123;\n"
17574                    "int oneTwo = 12;\n"
17575                    "  method();\n"
17576                    "float k= 2;\n"
17577                    "int ll=10000;\n"
17578                    "}",
17579                    AlignmentLeft));
17580   // variables are aligned at their name, pointers are at the left most position
17581   verifyFormat("int*   a;\n"
17582                "int**  b;\n"
17583                "int*** c;\n"
17584                "int    foobar;\n",
17585                AlignmentLeft);
17586 
17587   // PAS_Middle
17588   FormatStyle AlignmentMiddle = Alignment;
17589   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17590   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17591             "  int const i   = 1;\n"
17592             "  int *     j   = 2;\n"
17593             "  int       big = 10000;\n"
17594             "\n"
17595             "  unsigned oneTwoThree = 123;\n"
17596             "  int      oneTwo      = 12;\n"
17597             "  method();\n"
17598             "  float k  = 2;\n"
17599             "  int   ll = 10000;\n"
17600             "}",
17601             format("void SomeFunction(int parameter= 0) {\n"
17602                    " int const  i= 1;\n"
17603                    "  int *j=2;\n"
17604                    " int big  =  10000;\n"
17605                    "\n"
17606                    "unsigned oneTwoThree  =123;\n"
17607                    "int oneTwo = 12;\n"
17608                    "  method();\n"
17609                    "float k= 2;\n"
17610                    "int ll=10000;\n"
17611                    "}",
17612                    AlignmentMiddle));
17613   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17614             "  int const i   = 1;\n"
17615             "  int **    j   = 2, ***k;\n"
17616             "  int &     k   = i;\n"
17617             "  int &&    l   = i + j;\n"
17618             "  int       big = 10000;\n"
17619             "\n"
17620             "  unsigned oneTwoThree = 123;\n"
17621             "  int      oneTwo      = 12;\n"
17622             "  method();\n"
17623             "  float k  = 2;\n"
17624             "  int   ll = 10000;\n"
17625             "}",
17626             format("void SomeFunction(int parameter= 0) {\n"
17627                    " int const  i= 1;\n"
17628                    "  int **j=2,***k;\n"
17629                    "int &k=i;\n"
17630                    "int &&l=i+j;\n"
17631                    " int big  =  10000;\n"
17632                    "\n"
17633                    "unsigned oneTwoThree  =123;\n"
17634                    "int oneTwo = 12;\n"
17635                    "  method();\n"
17636                    "float k= 2;\n"
17637                    "int ll=10000;\n"
17638                    "}",
17639                    AlignmentMiddle));
17640   // variables are aligned at their name, pointers are in the middle
17641   verifyFormat("int *   a;\n"
17642                "int *   b;\n"
17643                "int *** c;\n"
17644                "int     foobar;\n",
17645                AlignmentMiddle);
17646 
17647   Alignment.AlignConsecutiveAssignments.Enabled = false;
17648   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17649   verifyFormat("#define A \\\n"
17650                "  int       aaaa = 12; \\\n"
17651                "  float     b = 23; \\\n"
17652                "  const int ccc = 234; \\\n"
17653                "  unsigned  dddddddddd = 2345;",
17654                Alignment);
17655   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17656   verifyFormat("#define A              \\\n"
17657                "  int       aaaa = 12; \\\n"
17658                "  float     b = 23;    \\\n"
17659                "  const int ccc = 234; \\\n"
17660                "  unsigned  dddddddddd = 2345;",
17661                Alignment);
17662   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17663   Alignment.ColumnLimit = 30;
17664   verifyFormat("#define A                    \\\n"
17665                "  int       aaaa = 12;       \\\n"
17666                "  float     b = 23;          \\\n"
17667                "  const int ccc = 234;       \\\n"
17668                "  int       dddddddddd = 2345;",
17669                Alignment);
17670   Alignment.ColumnLimit = 80;
17671   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17672                "k = 4, int l = 5,\n"
17673                "                  int m = 6) {\n"
17674                "  const int j = 10;\n"
17675                "  otherThing = 1;\n"
17676                "}",
17677                Alignment);
17678   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17679                "  int const i = 1;\n"
17680                "  int      *j = 2;\n"
17681                "  int       big = 10000;\n"
17682                "}",
17683                Alignment);
17684   verifyFormat("class C {\n"
17685                "public:\n"
17686                "  int          i = 1;\n"
17687                "  virtual void f() = 0;\n"
17688                "};",
17689                Alignment);
17690   verifyFormat("float i = 1;\n"
17691                "if (SomeType t = getSomething()) {\n"
17692                "}\n"
17693                "const unsigned j = 2;\n"
17694                "int            big = 10000;",
17695                Alignment);
17696   verifyFormat("float j = 7;\n"
17697                "for (int k = 0; k < N; ++k) {\n"
17698                "}\n"
17699                "unsigned j = 2;\n"
17700                "int      big = 10000;\n"
17701                "}",
17702                Alignment);
17703   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17704   verifyFormat("float              i = 1;\n"
17705                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17706                "    = someLooooooooooooooooongFunction();\n"
17707                "int j = 2;",
17708                Alignment);
17709   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17710   verifyFormat("int                i = 1;\n"
17711                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17712                "    someLooooooooooooooooongFunction();\n"
17713                "int j = 2;",
17714                Alignment);
17715 
17716   Alignment.AlignConsecutiveAssignments.Enabled = true;
17717   verifyFormat("auto lambda = []() {\n"
17718                "  auto  ii = 0;\n"
17719                "  float j  = 0;\n"
17720                "  return 0;\n"
17721                "};\n"
17722                "int   i  = 0;\n"
17723                "float i2 = 0;\n"
17724                "auto  v  = type{\n"
17725                "    i = 1,   //\n"
17726                "    (i = 2), //\n"
17727                "    i = 3    //\n"
17728                "};",
17729                Alignment);
17730   Alignment.AlignConsecutiveAssignments.Enabled = false;
17731 
17732   verifyFormat(
17733       "int      i = 1;\n"
17734       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17735       "                          loooooooooooooooooooooongParameterB);\n"
17736       "int      j = 2;",
17737       Alignment);
17738 
17739   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17740   // We expect declarations and assignments to align, as long as it doesn't
17741   // exceed the column limit, starting a new alignment sequence whenever it
17742   // happens.
17743   Alignment.AlignConsecutiveAssignments.Enabled = true;
17744   Alignment.ColumnLimit = 30;
17745   verifyFormat("float    ii              = 1;\n"
17746                "unsigned j               = 2;\n"
17747                "int someVerylongVariable = 1;\n"
17748                "AnotherLongType  ll = 123456;\n"
17749                "VeryVeryLongType k  = 2;\n"
17750                "int              myvar = 1;",
17751                Alignment);
17752   Alignment.ColumnLimit = 80;
17753   Alignment.AlignConsecutiveAssignments.Enabled = false;
17754 
17755   verifyFormat(
17756       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17757       "          typename LongType, typename B>\n"
17758       "auto foo() {}\n",
17759       Alignment);
17760   verifyFormat("float a, b = 1;\n"
17761                "int   c = 2;\n"
17762                "int   dd = 3;\n",
17763                Alignment);
17764   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17765                "float b[1][] = {{3.f}};\n",
17766                Alignment);
17767   Alignment.AlignConsecutiveAssignments.Enabled = true;
17768   verifyFormat("float a, b = 1;\n"
17769                "int   c  = 2;\n"
17770                "int   dd = 3;\n",
17771                Alignment);
17772   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17773                "float b[1][] = {{3.f}};\n",
17774                Alignment);
17775   Alignment.AlignConsecutiveAssignments.Enabled = false;
17776 
17777   Alignment.ColumnLimit = 30;
17778   Alignment.BinPackParameters = false;
17779   verifyFormat("void foo(float     a,\n"
17780                "         float     b,\n"
17781                "         int       c,\n"
17782                "         uint32_t *d) {\n"
17783                "  int   *e = 0;\n"
17784                "  float  f = 0;\n"
17785                "  double g = 0;\n"
17786                "}\n"
17787                "void bar(ino_t     a,\n"
17788                "         int       b,\n"
17789                "         uint32_t *c,\n"
17790                "         bool      d) {}\n",
17791                Alignment);
17792   Alignment.BinPackParameters = true;
17793   Alignment.ColumnLimit = 80;
17794 
17795   // Bug 33507
17796   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17797   verifyFormat(
17798       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
17799       "  static const Version verVs2017;\n"
17800       "  return true;\n"
17801       "});\n",
17802       Alignment);
17803   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17804 
17805   // See llvm.org/PR35641
17806   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17807   verifyFormat("int func() { //\n"
17808                "  int      b;\n"
17809                "  unsigned c;\n"
17810                "}",
17811                Alignment);
17812 
17813   // See PR37175
17814   FormatStyle Style = getMozillaStyle();
17815   Style.AlignConsecutiveDeclarations.Enabled = true;
17816   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17817             "foo(int a);",
17818             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17819 
17820   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17821   verifyFormat("unsigned int*       a;\n"
17822                "int*                b;\n"
17823                "unsigned int Const* c;\n"
17824                "unsigned int const* d;\n"
17825                "unsigned int Const& e;\n"
17826                "unsigned int const& f;",
17827                Alignment);
17828   verifyFormat("Const unsigned int* c;\n"
17829                "const unsigned int* d;\n"
17830                "Const unsigned int& e;\n"
17831                "const unsigned int& f;\n"
17832                "const unsigned      g;\n"
17833                "Const unsigned      h;",
17834                Alignment);
17835 
17836   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17837   verifyFormat("unsigned int *       a;\n"
17838                "int *                b;\n"
17839                "unsigned int Const * c;\n"
17840                "unsigned int const * d;\n"
17841                "unsigned int Const & e;\n"
17842                "unsigned int const & f;",
17843                Alignment);
17844   verifyFormat("Const unsigned int * c;\n"
17845                "const unsigned int * d;\n"
17846                "Const unsigned int & e;\n"
17847                "const unsigned int & f;\n"
17848                "const unsigned       g;\n"
17849                "Const unsigned       h;",
17850                Alignment);
17851 
17852   // See PR46529
17853   FormatStyle BracedAlign = getLLVMStyle();
17854   BracedAlign.AlignConsecutiveDeclarations.Enabled = true;
17855   verifyFormat("const auto result{[]() {\n"
17856                "  const auto something = 1;\n"
17857                "  return 2;\n"
17858                "}};",
17859                BracedAlign);
17860   verifyFormat("int foo{[]() {\n"
17861                "  int bar{0};\n"
17862                "  return 0;\n"
17863                "}()};",
17864                BracedAlign);
17865   BracedAlign.Cpp11BracedListStyle = false;
17866   verifyFormat("const auto result{ []() {\n"
17867                "  const auto something = 1;\n"
17868                "  return 2;\n"
17869                "} };",
17870                BracedAlign);
17871   verifyFormat("int foo{ []() {\n"
17872                "  int bar{ 0 };\n"
17873                "  return 0;\n"
17874                "}() };",
17875                BracedAlign);
17876 }
17877 
17878 TEST_F(FormatTest, AlignWithLineBreaks) {
17879   auto Style = getLLVMStyleWithColumns(120);
17880 
17881   EXPECT_EQ(Style.AlignConsecutiveAssignments,
17882             FormatStyle::AlignConsecutiveStyle(
17883                 {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
17884                  /*AcrossComments=*/false, /*AlignCompound=*/false,
17885                  /*PadOperators=*/true}));
17886   EXPECT_EQ(Style.AlignConsecutiveDeclarations,
17887             FormatStyle::AlignConsecutiveStyle({}));
17888   verifyFormat("void foo() {\n"
17889                "  int myVar = 5;\n"
17890                "  double x = 3.14;\n"
17891                "  auto str = \"Hello \"\n"
17892                "             \"World\";\n"
17893                "  auto s = \"Hello \"\n"
17894                "           \"Again\";\n"
17895                "}",
17896                Style);
17897 
17898   // clang-format off
17899   verifyFormat("void foo() {\n"
17900                "  const int capacityBefore = Entries.capacity();\n"
17901                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17902                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17903                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17904                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17905                "}",
17906                Style);
17907   // clang-format on
17908 
17909   Style.AlignConsecutiveAssignments.Enabled = true;
17910   verifyFormat("void foo() {\n"
17911                "  int myVar = 5;\n"
17912                "  double x  = 3.14;\n"
17913                "  auto str  = \"Hello \"\n"
17914                "              \"World\";\n"
17915                "  auto s    = \"Hello \"\n"
17916                "              \"Again\";\n"
17917                "}",
17918                Style);
17919 
17920   // clang-format off
17921   verifyFormat("void foo() {\n"
17922                "  const int capacityBefore = Entries.capacity();\n"
17923                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17924                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17925                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17926                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17927                "}",
17928                Style);
17929   // clang-format on
17930 
17931   Style.AlignConsecutiveAssignments.Enabled = false;
17932   Style.AlignConsecutiveDeclarations.Enabled = true;
17933   verifyFormat("void foo() {\n"
17934                "  int    myVar = 5;\n"
17935                "  double x = 3.14;\n"
17936                "  auto   str = \"Hello \"\n"
17937                "               \"World\";\n"
17938                "  auto   s = \"Hello \"\n"
17939                "             \"Again\";\n"
17940                "}",
17941                Style);
17942 
17943   // clang-format off
17944   verifyFormat("void foo() {\n"
17945                "  const int  capacityBefore = Entries.capacity();\n"
17946                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17947                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17948                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17949                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17950                "}",
17951                Style);
17952   // clang-format on
17953 
17954   Style.AlignConsecutiveAssignments.Enabled = true;
17955   Style.AlignConsecutiveDeclarations.Enabled = true;
17956 
17957   verifyFormat("void foo() {\n"
17958                "  int    myVar = 5;\n"
17959                "  double x     = 3.14;\n"
17960                "  auto   str   = \"Hello \"\n"
17961                "                 \"World\";\n"
17962                "  auto   s     = \"Hello \"\n"
17963                "                 \"Again\";\n"
17964                "}",
17965                Style);
17966 
17967   // clang-format off
17968   verifyFormat("void foo() {\n"
17969                "  const int  capacityBefore = Entries.capacity();\n"
17970                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17971                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17972                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17973                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17974                "}",
17975                Style);
17976   // clang-format on
17977 
17978   Style = getLLVMStyleWithColumns(120);
17979   Style.AlignConsecutiveAssignments.Enabled = true;
17980   Style.ContinuationIndentWidth = 4;
17981   Style.IndentWidth = 4;
17982 
17983   // clang-format off
17984   verifyFormat("void SomeFunc() {\n"
17985                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17986                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17987                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17988                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17989                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17990                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17991                "}",
17992                Style);
17993   // clang-format on
17994 
17995   Style.BinPackArguments = false;
17996 
17997   // clang-format off
17998   verifyFormat("void SomeFunc() {\n"
17999                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
18000                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18001                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
18002                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18003                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
18004                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18005                "}",
18006                Style);
18007   // clang-format on
18008 }
18009 
18010 TEST_F(FormatTest, AlignWithInitializerPeriods) {
18011   auto Style = getLLVMStyleWithColumns(60);
18012 
18013   verifyFormat("void foo1(void) {\n"
18014                "  BYTE p[1] = 1;\n"
18015                "  A B = {.one_foooooooooooooooo = 2,\n"
18016                "         .two_fooooooooooooo = 3,\n"
18017                "         .three_fooooooooooooo = 4};\n"
18018                "  BYTE payload = 2;\n"
18019                "}",
18020                Style);
18021 
18022   Style.AlignConsecutiveAssignments.Enabled = true;
18023   Style.AlignConsecutiveDeclarations.Enabled = false;
18024   verifyFormat("void foo2(void) {\n"
18025                "  BYTE p[1]    = 1;\n"
18026                "  A B          = {.one_foooooooooooooooo = 2,\n"
18027                "                  .two_fooooooooooooo    = 3,\n"
18028                "                  .three_fooooooooooooo  = 4};\n"
18029                "  BYTE payload = 2;\n"
18030                "}",
18031                Style);
18032 
18033   Style.AlignConsecutiveAssignments.Enabled = false;
18034   Style.AlignConsecutiveDeclarations.Enabled = true;
18035   verifyFormat("void foo3(void) {\n"
18036                "  BYTE p[1] = 1;\n"
18037                "  A    B = {.one_foooooooooooooooo = 2,\n"
18038                "            .two_fooooooooooooo = 3,\n"
18039                "            .three_fooooooooooooo = 4};\n"
18040                "  BYTE payload = 2;\n"
18041                "}",
18042                Style);
18043 
18044   Style.AlignConsecutiveAssignments.Enabled = true;
18045   Style.AlignConsecutiveDeclarations.Enabled = true;
18046   verifyFormat("void foo4(void) {\n"
18047                "  BYTE p[1]    = 1;\n"
18048                "  A    B       = {.one_foooooooooooooooo = 2,\n"
18049                "                  .two_fooooooooooooo    = 3,\n"
18050                "                  .three_fooooooooooooo  = 4};\n"
18051                "  BYTE payload = 2;\n"
18052                "}",
18053                Style);
18054 }
18055 
18056 TEST_F(FormatTest, LinuxBraceBreaking) {
18057   FormatStyle LinuxBraceStyle = getLLVMStyle();
18058   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
18059   verifyFormat("namespace a\n"
18060                "{\n"
18061                "class A\n"
18062                "{\n"
18063                "  void f()\n"
18064                "  {\n"
18065                "    if (true) {\n"
18066                "      a();\n"
18067                "      b();\n"
18068                "    } else {\n"
18069                "      a();\n"
18070                "    }\n"
18071                "  }\n"
18072                "  void g() { return; }\n"
18073                "};\n"
18074                "struct B {\n"
18075                "  int x;\n"
18076                "};\n"
18077                "} // namespace a\n",
18078                LinuxBraceStyle);
18079   verifyFormat("enum X {\n"
18080                "  Y = 0,\n"
18081                "}\n",
18082                LinuxBraceStyle);
18083   verifyFormat("struct S {\n"
18084                "  int Type;\n"
18085                "  union {\n"
18086                "    int x;\n"
18087                "    double y;\n"
18088                "  } Value;\n"
18089                "  class C\n"
18090                "  {\n"
18091                "    MyFavoriteType Value;\n"
18092                "  } Class;\n"
18093                "}\n",
18094                LinuxBraceStyle);
18095 }
18096 
18097 TEST_F(FormatTest, MozillaBraceBreaking) {
18098   FormatStyle MozillaBraceStyle = getLLVMStyle();
18099   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
18100   MozillaBraceStyle.FixNamespaceComments = false;
18101   verifyFormat("namespace a {\n"
18102                "class A\n"
18103                "{\n"
18104                "  void f()\n"
18105                "  {\n"
18106                "    if (true) {\n"
18107                "      a();\n"
18108                "      b();\n"
18109                "    }\n"
18110                "  }\n"
18111                "  void g() { return; }\n"
18112                "};\n"
18113                "enum E\n"
18114                "{\n"
18115                "  A,\n"
18116                "  // foo\n"
18117                "  B,\n"
18118                "  C\n"
18119                "};\n"
18120                "struct B\n"
18121                "{\n"
18122                "  int x;\n"
18123                "};\n"
18124                "}\n",
18125                MozillaBraceStyle);
18126   verifyFormat("struct S\n"
18127                "{\n"
18128                "  int Type;\n"
18129                "  union\n"
18130                "  {\n"
18131                "    int x;\n"
18132                "    double y;\n"
18133                "  } Value;\n"
18134                "  class C\n"
18135                "  {\n"
18136                "    MyFavoriteType Value;\n"
18137                "  } Class;\n"
18138                "}\n",
18139                MozillaBraceStyle);
18140 }
18141 
18142 TEST_F(FormatTest, StroustrupBraceBreaking) {
18143   FormatStyle StroustrupBraceStyle = getLLVMStyle();
18144   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18145   verifyFormat("namespace a {\n"
18146                "class A {\n"
18147                "  void f()\n"
18148                "  {\n"
18149                "    if (true) {\n"
18150                "      a();\n"
18151                "      b();\n"
18152                "    }\n"
18153                "  }\n"
18154                "  void g() { return; }\n"
18155                "};\n"
18156                "struct B {\n"
18157                "  int x;\n"
18158                "};\n"
18159                "} // namespace a\n",
18160                StroustrupBraceStyle);
18161 
18162   verifyFormat("void foo()\n"
18163                "{\n"
18164                "  if (a) {\n"
18165                "    a();\n"
18166                "  }\n"
18167                "  else {\n"
18168                "    b();\n"
18169                "  }\n"
18170                "}\n",
18171                StroustrupBraceStyle);
18172 
18173   verifyFormat("#ifdef _DEBUG\n"
18174                "int foo(int i = 0)\n"
18175                "#else\n"
18176                "int foo(int i = 5)\n"
18177                "#endif\n"
18178                "{\n"
18179                "  return i;\n"
18180                "}",
18181                StroustrupBraceStyle);
18182 
18183   verifyFormat("void foo() {}\n"
18184                "void bar()\n"
18185                "#ifdef _DEBUG\n"
18186                "{\n"
18187                "  foo();\n"
18188                "}\n"
18189                "#else\n"
18190                "{\n"
18191                "}\n"
18192                "#endif",
18193                StroustrupBraceStyle);
18194 
18195   verifyFormat("void foobar() { int i = 5; }\n"
18196                "#ifdef _DEBUG\n"
18197                "void bar() {}\n"
18198                "#else\n"
18199                "void bar() { foobar(); }\n"
18200                "#endif",
18201                StroustrupBraceStyle);
18202 }
18203 
18204 TEST_F(FormatTest, AllmanBraceBreaking) {
18205   FormatStyle AllmanBraceStyle = getLLVMStyle();
18206   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
18207 
18208   EXPECT_EQ("namespace a\n"
18209             "{\n"
18210             "void f();\n"
18211             "void g();\n"
18212             "} // namespace a\n",
18213             format("namespace a\n"
18214                    "{\n"
18215                    "void f();\n"
18216                    "void g();\n"
18217                    "}\n",
18218                    AllmanBraceStyle));
18219 
18220   verifyFormat("namespace a\n"
18221                "{\n"
18222                "class A\n"
18223                "{\n"
18224                "  void f()\n"
18225                "  {\n"
18226                "    if (true)\n"
18227                "    {\n"
18228                "      a();\n"
18229                "      b();\n"
18230                "    }\n"
18231                "  }\n"
18232                "  void g() { return; }\n"
18233                "};\n"
18234                "struct B\n"
18235                "{\n"
18236                "  int x;\n"
18237                "};\n"
18238                "union C\n"
18239                "{\n"
18240                "};\n"
18241                "} // namespace a",
18242                AllmanBraceStyle);
18243 
18244   verifyFormat("void f()\n"
18245                "{\n"
18246                "  if (true)\n"
18247                "  {\n"
18248                "    a();\n"
18249                "  }\n"
18250                "  else if (false)\n"
18251                "  {\n"
18252                "    b();\n"
18253                "  }\n"
18254                "  else\n"
18255                "  {\n"
18256                "    c();\n"
18257                "  }\n"
18258                "}\n",
18259                AllmanBraceStyle);
18260 
18261   verifyFormat("void f()\n"
18262                "{\n"
18263                "  for (int i = 0; i < 10; ++i)\n"
18264                "  {\n"
18265                "    a();\n"
18266                "  }\n"
18267                "  while (false)\n"
18268                "  {\n"
18269                "    b();\n"
18270                "  }\n"
18271                "  do\n"
18272                "  {\n"
18273                "    c();\n"
18274                "  } while (false)\n"
18275                "}\n",
18276                AllmanBraceStyle);
18277 
18278   verifyFormat("void f(int a)\n"
18279                "{\n"
18280                "  switch (a)\n"
18281                "  {\n"
18282                "  case 0:\n"
18283                "    break;\n"
18284                "  case 1:\n"
18285                "  {\n"
18286                "    break;\n"
18287                "  }\n"
18288                "  case 2:\n"
18289                "  {\n"
18290                "  }\n"
18291                "  break;\n"
18292                "  default:\n"
18293                "    break;\n"
18294                "  }\n"
18295                "}\n",
18296                AllmanBraceStyle);
18297 
18298   verifyFormat("enum X\n"
18299                "{\n"
18300                "  Y = 0,\n"
18301                "}\n",
18302                AllmanBraceStyle);
18303   verifyFormat("enum X\n"
18304                "{\n"
18305                "  Y = 0\n"
18306                "}\n",
18307                AllmanBraceStyle);
18308 
18309   verifyFormat("@interface BSApplicationController ()\n"
18310                "{\n"
18311                "@private\n"
18312                "  id _extraIvar;\n"
18313                "}\n"
18314                "@end\n",
18315                AllmanBraceStyle);
18316 
18317   verifyFormat("#ifdef _DEBUG\n"
18318                "int foo(int i = 0)\n"
18319                "#else\n"
18320                "int foo(int i = 5)\n"
18321                "#endif\n"
18322                "{\n"
18323                "  return i;\n"
18324                "}",
18325                AllmanBraceStyle);
18326 
18327   verifyFormat("void foo() {}\n"
18328                "void bar()\n"
18329                "#ifdef _DEBUG\n"
18330                "{\n"
18331                "  foo();\n"
18332                "}\n"
18333                "#else\n"
18334                "{\n"
18335                "}\n"
18336                "#endif",
18337                AllmanBraceStyle);
18338 
18339   verifyFormat("void foobar() { int i = 5; }\n"
18340                "#ifdef _DEBUG\n"
18341                "void bar() {}\n"
18342                "#else\n"
18343                "void bar() { foobar(); }\n"
18344                "#endif",
18345                AllmanBraceStyle);
18346 
18347   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18348             FormatStyle::SLS_All);
18349 
18350   verifyFormat("[](int i) { return i + 2; };\n"
18351                "[](int i, int j)\n"
18352                "{\n"
18353                "  auto x = i + j;\n"
18354                "  auto y = i * j;\n"
18355                "  return x ^ y;\n"
18356                "};\n"
18357                "void foo()\n"
18358                "{\n"
18359                "  auto shortLambda = [](int i) { return i + 2; };\n"
18360                "  auto longLambda = [](int i, int j)\n"
18361                "  {\n"
18362                "    auto x = i + j;\n"
18363                "    auto y = i * j;\n"
18364                "    return x ^ y;\n"
18365                "  };\n"
18366                "}",
18367                AllmanBraceStyle);
18368 
18369   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18370 
18371   verifyFormat("[](int i)\n"
18372                "{\n"
18373                "  return i + 2;\n"
18374                "};\n"
18375                "[](int i, int j)\n"
18376                "{\n"
18377                "  auto x = i + j;\n"
18378                "  auto y = i * j;\n"
18379                "  return x ^ y;\n"
18380                "};\n"
18381                "void foo()\n"
18382                "{\n"
18383                "  auto shortLambda = [](int i)\n"
18384                "  {\n"
18385                "    return i + 2;\n"
18386                "  };\n"
18387                "  auto longLambda = [](int i, int j)\n"
18388                "  {\n"
18389                "    auto x = i + j;\n"
18390                "    auto y = i * j;\n"
18391                "    return x ^ y;\n"
18392                "  };\n"
18393                "}",
18394                AllmanBraceStyle);
18395 
18396   // Reset
18397   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18398 
18399   // This shouldn't affect ObjC blocks..
18400   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18401                "  // ...\n"
18402                "  int i;\n"
18403                "}];",
18404                AllmanBraceStyle);
18405   verifyFormat("void (^block)(void) = ^{\n"
18406                "  // ...\n"
18407                "  int i;\n"
18408                "};",
18409                AllmanBraceStyle);
18410   // .. or dict literals.
18411   verifyFormat("void f()\n"
18412                "{\n"
18413                "  // ...\n"
18414                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18415                "}",
18416                AllmanBraceStyle);
18417   verifyFormat("void f()\n"
18418                "{\n"
18419                "  // ...\n"
18420                "  [object someMethod:@{a : @\"b\"}];\n"
18421                "}",
18422                AllmanBraceStyle);
18423   verifyFormat("int f()\n"
18424                "{ // comment\n"
18425                "  return 42;\n"
18426                "}",
18427                AllmanBraceStyle);
18428 
18429   AllmanBraceStyle.ColumnLimit = 19;
18430   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18431   AllmanBraceStyle.ColumnLimit = 18;
18432   verifyFormat("void f()\n"
18433                "{\n"
18434                "  int i;\n"
18435                "}",
18436                AllmanBraceStyle);
18437   AllmanBraceStyle.ColumnLimit = 80;
18438 
18439   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18440   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18441       FormatStyle::SIS_WithoutElse;
18442   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18443   verifyFormat("void f(bool b)\n"
18444                "{\n"
18445                "  if (b)\n"
18446                "  {\n"
18447                "    return;\n"
18448                "  }\n"
18449                "}\n",
18450                BreakBeforeBraceShortIfs);
18451   verifyFormat("void f(bool b)\n"
18452                "{\n"
18453                "  if constexpr (b)\n"
18454                "  {\n"
18455                "    return;\n"
18456                "  }\n"
18457                "}\n",
18458                BreakBeforeBraceShortIfs);
18459   verifyFormat("void f(bool b)\n"
18460                "{\n"
18461                "  if CONSTEXPR (b)\n"
18462                "  {\n"
18463                "    return;\n"
18464                "  }\n"
18465                "}\n",
18466                BreakBeforeBraceShortIfs);
18467   verifyFormat("void f(bool b)\n"
18468                "{\n"
18469                "  if (b) return;\n"
18470                "}\n",
18471                BreakBeforeBraceShortIfs);
18472   verifyFormat("void f(bool b)\n"
18473                "{\n"
18474                "  if constexpr (b) return;\n"
18475                "}\n",
18476                BreakBeforeBraceShortIfs);
18477   verifyFormat("void f(bool b)\n"
18478                "{\n"
18479                "  if CONSTEXPR (b) return;\n"
18480                "}\n",
18481                BreakBeforeBraceShortIfs);
18482   verifyFormat("void f(bool b)\n"
18483                "{\n"
18484                "  while (b)\n"
18485                "  {\n"
18486                "    return;\n"
18487                "  }\n"
18488                "}\n",
18489                BreakBeforeBraceShortIfs);
18490 }
18491 
18492 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18493   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18494   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18495 
18496   // Make a few changes to the style for testing purposes
18497   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18498       FormatStyle::SFS_Empty;
18499   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18500 
18501   // FIXME: this test case can't decide whether there should be a blank line
18502   // after the ~D() line or not. It adds one if one doesn't exist in the test
18503   // and it removes the line if one exists.
18504   /*
18505   verifyFormat("class A;\n"
18506                "namespace B\n"
18507                "  {\n"
18508                "class C;\n"
18509                "// Comment\n"
18510                "class D\n"
18511                "  {\n"
18512                "public:\n"
18513                "  D();\n"
18514                "  ~D() {}\n"
18515                "private:\n"
18516                "  enum E\n"
18517                "    {\n"
18518                "    F\n"
18519                "    }\n"
18520                "  };\n"
18521                "  } // namespace B\n",
18522                WhitesmithsBraceStyle);
18523   */
18524 
18525   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18526   verifyFormat("namespace a\n"
18527                "  {\n"
18528                "class A\n"
18529                "  {\n"
18530                "  void f()\n"
18531                "    {\n"
18532                "    if (true)\n"
18533                "      {\n"
18534                "      a();\n"
18535                "      b();\n"
18536                "      }\n"
18537                "    }\n"
18538                "  void g()\n"
18539                "    {\n"
18540                "    return;\n"
18541                "    }\n"
18542                "  };\n"
18543                "struct B\n"
18544                "  {\n"
18545                "  int x;\n"
18546                "  };\n"
18547                "  } // namespace a",
18548                WhitesmithsBraceStyle);
18549 
18550   verifyFormat("namespace a\n"
18551                "  {\n"
18552                "namespace b\n"
18553                "  {\n"
18554                "class A\n"
18555                "  {\n"
18556                "  void f()\n"
18557                "    {\n"
18558                "    if (true)\n"
18559                "      {\n"
18560                "      a();\n"
18561                "      b();\n"
18562                "      }\n"
18563                "    }\n"
18564                "  void g()\n"
18565                "    {\n"
18566                "    return;\n"
18567                "    }\n"
18568                "  };\n"
18569                "struct B\n"
18570                "  {\n"
18571                "  int x;\n"
18572                "  };\n"
18573                "  } // namespace b\n"
18574                "  } // namespace a",
18575                WhitesmithsBraceStyle);
18576 
18577   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18578   verifyFormat("namespace a\n"
18579                "  {\n"
18580                "namespace b\n"
18581                "  {\n"
18582                "  class A\n"
18583                "    {\n"
18584                "    void f()\n"
18585                "      {\n"
18586                "      if (true)\n"
18587                "        {\n"
18588                "        a();\n"
18589                "        b();\n"
18590                "        }\n"
18591                "      }\n"
18592                "    void g()\n"
18593                "      {\n"
18594                "      return;\n"
18595                "      }\n"
18596                "    };\n"
18597                "  struct B\n"
18598                "    {\n"
18599                "    int x;\n"
18600                "    };\n"
18601                "  } // namespace b\n"
18602                "  } // namespace a",
18603                WhitesmithsBraceStyle);
18604 
18605   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18606   verifyFormat("namespace a\n"
18607                "  {\n"
18608                "  namespace b\n"
18609                "    {\n"
18610                "    class A\n"
18611                "      {\n"
18612                "      void f()\n"
18613                "        {\n"
18614                "        if (true)\n"
18615                "          {\n"
18616                "          a();\n"
18617                "          b();\n"
18618                "          }\n"
18619                "        }\n"
18620                "      void g()\n"
18621                "        {\n"
18622                "        return;\n"
18623                "        }\n"
18624                "      };\n"
18625                "    struct B\n"
18626                "      {\n"
18627                "      int x;\n"
18628                "      };\n"
18629                "    } // namespace b\n"
18630                "  }   // namespace a",
18631                WhitesmithsBraceStyle);
18632 
18633   verifyFormat("void f()\n"
18634                "  {\n"
18635                "  if (true)\n"
18636                "    {\n"
18637                "    a();\n"
18638                "    }\n"
18639                "  else if (false)\n"
18640                "    {\n"
18641                "    b();\n"
18642                "    }\n"
18643                "  else\n"
18644                "    {\n"
18645                "    c();\n"
18646                "    }\n"
18647                "  }\n",
18648                WhitesmithsBraceStyle);
18649 
18650   verifyFormat("void f()\n"
18651                "  {\n"
18652                "  for (int i = 0; i < 10; ++i)\n"
18653                "    {\n"
18654                "    a();\n"
18655                "    }\n"
18656                "  while (false)\n"
18657                "    {\n"
18658                "    b();\n"
18659                "    }\n"
18660                "  do\n"
18661                "    {\n"
18662                "    c();\n"
18663                "    } while (false)\n"
18664                "  }\n",
18665                WhitesmithsBraceStyle);
18666 
18667   WhitesmithsBraceStyle.IndentCaseLabels = true;
18668   verifyFormat("void switchTest1(int a)\n"
18669                "  {\n"
18670                "  switch (a)\n"
18671                "    {\n"
18672                "    case 2:\n"
18673                "      {\n"
18674                "      }\n"
18675                "      break;\n"
18676                "    }\n"
18677                "  }\n",
18678                WhitesmithsBraceStyle);
18679 
18680   verifyFormat("void switchTest2(int a)\n"
18681                "  {\n"
18682                "  switch (a)\n"
18683                "    {\n"
18684                "    case 0:\n"
18685                "      break;\n"
18686                "    case 1:\n"
18687                "      {\n"
18688                "      break;\n"
18689                "      }\n"
18690                "    case 2:\n"
18691                "      {\n"
18692                "      }\n"
18693                "      break;\n"
18694                "    default:\n"
18695                "      break;\n"
18696                "    }\n"
18697                "  }\n",
18698                WhitesmithsBraceStyle);
18699 
18700   verifyFormat("void switchTest3(int a)\n"
18701                "  {\n"
18702                "  switch (a)\n"
18703                "    {\n"
18704                "    case 0:\n"
18705                "      {\n"
18706                "      foo(x);\n"
18707                "      }\n"
18708                "      break;\n"
18709                "    default:\n"
18710                "      {\n"
18711                "      foo(1);\n"
18712                "      }\n"
18713                "      break;\n"
18714                "    }\n"
18715                "  }\n",
18716                WhitesmithsBraceStyle);
18717 
18718   WhitesmithsBraceStyle.IndentCaseLabels = false;
18719 
18720   verifyFormat("void switchTest4(int a)\n"
18721                "  {\n"
18722                "  switch (a)\n"
18723                "    {\n"
18724                "  case 2:\n"
18725                "    {\n"
18726                "    }\n"
18727                "    break;\n"
18728                "    }\n"
18729                "  }\n",
18730                WhitesmithsBraceStyle);
18731 
18732   verifyFormat("void switchTest5(int a)\n"
18733                "  {\n"
18734                "  switch (a)\n"
18735                "    {\n"
18736                "  case 0:\n"
18737                "    break;\n"
18738                "  case 1:\n"
18739                "    {\n"
18740                "    foo();\n"
18741                "    break;\n"
18742                "    }\n"
18743                "  case 2:\n"
18744                "    {\n"
18745                "    }\n"
18746                "    break;\n"
18747                "  default:\n"
18748                "    break;\n"
18749                "    }\n"
18750                "  }\n",
18751                WhitesmithsBraceStyle);
18752 
18753   verifyFormat("void switchTest6(int a)\n"
18754                "  {\n"
18755                "  switch (a)\n"
18756                "    {\n"
18757                "  case 0:\n"
18758                "    {\n"
18759                "    foo(x);\n"
18760                "    }\n"
18761                "    break;\n"
18762                "  default:\n"
18763                "    {\n"
18764                "    foo(1);\n"
18765                "    }\n"
18766                "    break;\n"
18767                "    }\n"
18768                "  }\n",
18769                WhitesmithsBraceStyle);
18770 
18771   verifyFormat("enum X\n"
18772                "  {\n"
18773                "  Y = 0, // testing\n"
18774                "  }\n",
18775                WhitesmithsBraceStyle);
18776 
18777   verifyFormat("enum X\n"
18778                "  {\n"
18779                "  Y = 0\n"
18780                "  }\n",
18781                WhitesmithsBraceStyle);
18782   verifyFormat("enum X\n"
18783                "  {\n"
18784                "  Y = 0,\n"
18785                "  Z = 1\n"
18786                "  };\n",
18787                WhitesmithsBraceStyle);
18788 
18789   verifyFormat("@interface BSApplicationController ()\n"
18790                "  {\n"
18791                "@private\n"
18792                "  id _extraIvar;\n"
18793                "  }\n"
18794                "@end\n",
18795                WhitesmithsBraceStyle);
18796 
18797   verifyFormat("#ifdef _DEBUG\n"
18798                "int foo(int i = 0)\n"
18799                "#else\n"
18800                "int foo(int i = 5)\n"
18801                "#endif\n"
18802                "  {\n"
18803                "  return i;\n"
18804                "  }",
18805                WhitesmithsBraceStyle);
18806 
18807   verifyFormat("void foo() {}\n"
18808                "void bar()\n"
18809                "#ifdef _DEBUG\n"
18810                "  {\n"
18811                "  foo();\n"
18812                "  }\n"
18813                "#else\n"
18814                "  {\n"
18815                "  }\n"
18816                "#endif",
18817                WhitesmithsBraceStyle);
18818 
18819   verifyFormat("void foobar()\n"
18820                "  {\n"
18821                "  int i = 5;\n"
18822                "  }\n"
18823                "#ifdef _DEBUG\n"
18824                "void bar()\n"
18825                "  {\n"
18826                "  }\n"
18827                "#else\n"
18828                "void bar()\n"
18829                "  {\n"
18830                "  foobar();\n"
18831                "  }\n"
18832                "#endif",
18833                WhitesmithsBraceStyle);
18834 
18835   // This shouldn't affect ObjC blocks..
18836   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18837                "  // ...\n"
18838                "  int i;\n"
18839                "}];",
18840                WhitesmithsBraceStyle);
18841   verifyFormat("void (^block)(void) = ^{\n"
18842                "  // ...\n"
18843                "  int i;\n"
18844                "};",
18845                WhitesmithsBraceStyle);
18846   // .. or dict literals.
18847   verifyFormat("void f()\n"
18848                "  {\n"
18849                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18850                "  }",
18851                WhitesmithsBraceStyle);
18852 
18853   verifyFormat("int f()\n"
18854                "  { // comment\n"
18855                "  return 42;\n"
18856                "  }",
18857                WhitesmithsBraceStyle);
18858 
18859   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18860   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18861       FormatStyle::SIS_OnlyFirstIf;
18862   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18863   verifyFormat("void f(bool b)\n"
18864                "  {\n"
18865                "  if (b)\n"
18866                "    {\n"
18867                "    return;\n"
18868                "    }\n"
18869                "  }\n",
18870                BreakBeforeBraceShortIfs);
18871   verifyFormat("void f(bool b)\n"
18872                "  {\n"
18873                "  if (b) return;\n"
18874                "  }\n",
18875                BreakBeforeBraceShortIfs);
18876   verifyFormat("void f(bool b)\n"
18877                "  {\n"
18878                "  while (b)\n"
18879                "    {\n"
18880                "    return;\n"
18881                "    }\n"
18882                "  }\n",
18883                BreakBeforeBraceShortIfs);
18884 }
18885 
18886 TEST_F(FormatTest, GNUBraceBreaking) {
18887   FormatStyle GNUBraceStyle = getLLVMStyle();
18888   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
18889   verifyFormat("namespace a\n"
18890                "{\n"
18891                "class A\n"
18892                "{\n"
18893                "  void f()\n"
18894                "  {\n"
18895                "    int a;\n"
18896                "    {\n"
18897                "      int b;\n"
18898                "    }\n"
18899                "    if (true)\n"
18900                "      {\n"
18901                "        a();\n"
18902                "        b();\n"
18903                "      }\n"
18904                "  }\n"
18905                "  void g() { return; }\n"
18906                "}\n"
18907                "} // namespace a",
18908                GNUBraceStyle);
18909 
18910   verifyFormat("void f()\n"
18911                "{\n"
18912                "  if (true)\n"
18913                "    {\n"
18914                "      a();\n"
18915                "    }\n"
18916                "  else if (false)\n"
18917                "    {\n"
18918                "      b();\n"
18919                "    }\n"
18920                "  else\n"
18921                "    {\n"
18922                "      c();\n"
18923                "    }\n"
18924                "}\n",
18925                GNUBraceStyle);
18926 
18927   verifyFormat("void f()\n"
18928                "{\n"
18929                "  for (int i = 0; i < 10; ++i)\n"
18930                "    {\n"
18931                "      a();\n"
18932                "    }\n"
18933                "  while (false)\n"
18934                "    {\n"
18935                "      b();\n"
18936                "    }\n"
18937                "  do\n"
18938                "    {\n"
18939                "      c();\n"
18940                "    }\n"
18941                "  while (false);\n"
18942                "}\n",
18943                GNUBraceStyle);
18944 
18945   verifyFormat("void f(int a)\n"
18946                "{\n"
18947                "  switch (a)\n"
18948                "    {\n"
18949                "    case 0:\n"
18950                "      break;\n"
18951                "    case 1:\n"
18952                "      {\n"
18953                "        break;\n"
18954                "      }\n"
18955                "    case 2:\n"
18956                "      {\n"
18957                "      }\n"
18958                "      break;\n"
18959                "    default:\n"
18960                "      break;\n"
18961                "    }\n"
18962                "}\n",
18963                GNUBraceStyle);
18964 
18965   verifyFormat("enum X\n"
18966                "{\n"
18967                "  Y = 0,\n"
18968                "}\n",
18969                GNUBraceStyle);
18970 
18971   verifyFormat("@interface BSApplicationController ()\n"
18972                "{\n"
18973                "@private\n"
18974                "  id _extraIvar;\n"
18975                "}\n"
18976                "@end\n",
18977                GNUBraceStyle);
18978 
18979   verifyFormat("#ifdef _DEBUG\n"
18980                "int foo(int i = 0)\n"
18981                "#else\n"
18982                "int foo(int i = 5)\n"
18983                "#endif\n"
18984                "{\n"
18985                "  return i;\n"
18986                "}",
18987                GNUBraceStyle);
18988 
18989   verifyFormat("void foo() {}\n"
18990                "void bar()\n"
18991                "#ifdef _DEBUG\n"
18992                "{\n"
18993                "  foo();\n"
18994                "}\n"
18995                "#else\n"
18996                "{\n"
18997                "}\n"
18998                "#endif",
18999                GNUBraceStyle);
19000 
19001   verifyFormat("void foobar() { int i = 5; }\n"
19002                "#ifdef _DEBUG\n"
19003                "void bar() {}\n"
19004                "#else\n"
19005                "void bar() { foobar(); }\n"
19006                "#endif",
19007                GNUBraceStyle);
19008 }
19009 
19010 TEST_F(FormatTest, WebKitBraceBreaking) {
19011   FormatStyle WebKitBraceStyle = getLLVMStyle();
19012   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
19013   WebKitBraceStyle.FixNamespaceComments = false;
19014   verifyFormat("namespace a {\n"
19015                "class A {\n"
19016                "  void f()\n"
19017                "  {\n"
19018                "    if (true) {\n"
19019                "      a();\n"
19020                "      b();\n"
19021                "    }\n"
19022                "  }\n"
19023                "  void g() { return; }\n"
19024                "};\n"
19025                "enum E {\n"
19026                "  A,\n"
19027                "  // foo\n"
19028                "  B,\n"
19029                "  C\n"
19030                "};\n"
19031                "struct B {\n"
19032                "  int x;\n"
19033                "};\n"
19034                "}\n",
19035                WebKitBraceStyle);
19036   verifyFormat("struct S {\n"
19037                "  int Type;\n"
19038                "  union {\n"
19039                "    int x;\n"
19040                "    double y;\n"
19041                "  } Value;\n"
19042                "  class C {\n"
19043                "    MyFavoriteType Value;\n"
19044                "  } Class;\n"
19045                "};\n",
19046                WebKitBraceStyle);
19047 }
19048 
19049 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
19050   verifyFormat("void f() {\n"
19051                "  try {\n"
19052                "  } catch (const Exception &e) {\n"
19053                "  }\n"
19054                "}\n",
19055                getLLVMStyle());
19056 }
19057 
19058 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
19059   auto Style = getLLVMStyle();
19060   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19061   Style.AlignConsecutiveAssignments.Enabled = true;
19062   Style.AlignConsecutiveDeclarations.Enabled = true;
19063   verifyFormat("struct test demo[] = {\n"
19064                "    {56,    23, \"hello\"},\n"
19065                "    {-1, 93463, \"world\"},\n"
19066                "    { 7,     5,    \"!!\"}\n"
19067                "};\n",
19068                Style);
19069 
19070   verifyFormat("struct test demo[] = {\n"
19071                "    {56,    23, \"hello\"}, // first line\n"
19072                "    {-1, 93463, \"world\"}, // second line\n"
19073                "    { 7,     5,    \"!!\"}  // third line\n"
19074                "};\n",
19075                Style);
19076 
19077   verifyFormat("struct test demo[4] = {\n"
19078                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19079                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19080                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19081                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19082                "};\n",
19083                Style);
19084 
19085   verifyFormat("struct test demo[3] = {\n"
19086                "    {56,    23, \"hello\"},\n"
19087                "    {-1, 93463, \"world\"},\n"
19088                "    { 7,     5,    \"!!\"}\n"
19089                "};\n",
19090                Style);
19091 
19092   verifyFormat("struct test demo[3] = {\n"
19093                "    {int{56},    23, \"hello\"},\n"
19094                "    {int{-1}, 93463, \"world\"},\n"
19095                "    { int{7},     5,    \"!!\"}\n"
19096                "};\n",
19097                Style);
19098 
19099   verifyFormat("struct test demo[] = {\n"
19100                "    {56,    23, \"hello\"},\n"
19101                "    {-1, 93463, \"world\"},\n"
19102                "    { 7,     5,    \"!!\"},\n"
19103                "};\n",
19104                Style);
19105 
19106   verifyFormat("test demo[] = {\n"
19107                "    {56,    23, \"hello\"},\n"
19108                "    {-1, 93463, \"world\"},\n"
19109                "    { 7,     5,    \"!!\"},\n"
19110                "};\n",
19111                Style);
19112 
19113   verifyFormat("demo = std::array<struct test, 3>{\n"
19114                "    test{56,    23, \"hello\"},\n"
19115                "    test{-1, 93463, \"world\"},\n"
19116                "    test{ 7,     5,    \"!!\"},\n"
19117                "};\n",
19118                Style);
19119 
19120   verifyFormat("test demo[] = {\n"
19121                "    {56,    23, \"hello\"},\n"
19122                "#if X\n"
19123                "    {-1, 93463, \"world\"},\n"
19124                "#endif\n"
19125                "    { 7,     5,    \"!!\"}\n"
19126                "};\n",
19127                Style);
19128 
19129   verifyFormat(
19130       "test demo[] = {\n"
19131       "    { 7,    23,\n"
19132       "     \"hello world i am a very long line that really, in any\"\n"
19133       "     \"just world, ought to be split over multiple lines\"},\n"
19134       "    {-1, 93463,                                  \"world\"},\n"
19135       "    {56,     5,                                     \"!!\"}\n"
19136       "};\n",
19137       Style);
19138 
19139   verifyFormat("return GradForUnaryCwise(g, {\n"
19140                "                                {{\"sign\"}, \"Sign\",  "
19141                "  {\"x\", \"dy\"}},\n"
19142                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
19143                ", \"sign\"}},\n"
19144                "});\n",
19145                Style);
19146 
19147   Style.ColumnLimit = 0;
19148   EXPECT_EQ(
19149       "test demo[] = {\n"
19150       "    {56,    23, \"hello world i am a very long line that really, "
19151       "in any just world, ought to be split over multiple lines\"},\n"
19152       "    {-1, 93463,                                                  "
19153       "                                                 \"world\"},\n"
19154       "    { 7,     5,                                                  "
19155       "                                                    \"!!\"},\n"
19156       "};",
19157       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19158              "that really, in any just world, ought to be split over multiple "
19159              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19160              Style));
19161 
19162   Style.ColumnLimit = 80;
19163   verifyFormat("test demo[] = {\n"
19164                "    {56,    23, /* a comment */ \"hello\"},\n"
19165                "    {-1, 93463,                 \"world\"},\n"
19166                "    { 7,     5,                    \"!!\"}\n"
19167                "};\n",
19168                Style);
19169 
19170   verifyFormat("test demo[] = {\n"
19171                "    {56,    23,                    \"hello\"},\n"
19172                "    {-1, 93463, \"world\" /* comment here */},\n"
19173                "    { 7,     5,                       \"!!\"}\n"
19174                "};\n",
19175                Style);
19176 
19177   verifyFormat("test demo[] = {\n"
19178                "    {56, /* a comment */ 23, \"hello\"},\n"
19179                "    {-1,              93463, \"world\"},\n"
19180                "    { 7,                  5,    \"!!\"}\n"
19181                "};\n",
19182                Style);
19183 
19184   Style.ColumnLimit = 20;
19185   EXPECT_EQ(
19186       "demo = std::array<\n"
19187       "    struct test, 3>{\n"
19188       "    test{\n"
19189       "         56,    23,\n"
19190       "         \"hello \"\n"
19191       "         \"world i \"\n"
19192       "         \"am a very \"\n"
19193       "         \"long line \"\n"
19194       "         \"that \"\n"
19195       "         \"really, \"\n"
19196       "         \"in any \"\n"
19197       "         \"just \"\n"
19198       "         \"world, \"\n"
19199       "         \"ought to \"\n"
19200       "         \"be split \"\n"
19201       "         \"over \"\n"
19202       "         \"multiple \"\n"
19203       "         \"lines\"},\n"
19204       "    test{-1, 93463,\n"
19205       "         \"world\"},\n"
19206       "    test{ 7,     5,\n"
19207       "         \"!!\"   },\n"
19208       "};",
19209       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19210              "i am a very long line that really, in any just world, ought "
19211              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19212              "test{7, 5, \"!!\"},};",
19213              Style));
19214   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19215   Style = getLLVMStyleWithColumns(50);
19216   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19217   verifyFormat("static A x = {\n"
19218                "    {{init1, init2, init3, init4},\n"
19219                "     {init1, init2, init3, init4}}\n"
19220                "};",
19221                Style);
19222   // TODO: Fix the indentations below when this option is fully functional.
19223   verifyFormat("int a[][] = {\n"
19224                "    {\n"
19225                "     {0, 2}, //\n"
19226                " {1, 2}  //\n"
19227                "    }\n"
19228                "};",
19229                Style);
19230   Style.ColumnLimit = 100;
19231   EXPECT_EQ(
19232       "test demo[] = {\n"
19233       "    {56,    23,\n"
19234       "     \"hello world i am a very long line that really, in any just world"
19235       ", ought to be split over \"\n"
19236       "     \"multiple lines\"  },\n"
19237       "    {-1, 93463, \"world\"},\n"
19238       "    { 7,     5,    \"!!\"},\n"
19239       "};",
19240       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19241              "that really, in any just world, ought to be split over multiple "
19242              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19243              Style));
19244 
19245   Style = getLLVMStyleWithColumns(50);
19246   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19247   verifyFormat("struct test demo[] = {\n"
19248                "    {56,    23, \"hello\"},\n"
19249                "    {-1, 93463, \"world\"},\n"
19250                "    { 7,     5,    \"!!\"}\n"
19251                "};\n"
19252                "static A x = {\n"
19253                "    {{init1, init2, init3, init4},\n"
19254                "     {init1, init2, init3, init4}}\n"
19255                "};",
19256                Style);
19257   Style.ColumnLimit = 100;
19258   Style.AlignConsecutiveAssignments.AcrossComments = true;
19259   Style.AlignConsecutiveDeclarations.AcrossComments = true;
19260   verifyFormat("struct test demo[] = {\n"
19261                "    {56,    23, \"hello\"},\n"
19262                "    {-1, 93463, \"world\"},\n"
19263                "    { 7,     5,    \"!!\"}\n"
19264                "};\n"
19265                "struct test demo[4] = {\n"
19266                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19267                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19268                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19269                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19270                "};\n",
19271                Style);
19272   EXPECT_EQ(
19273       "test demo[] = {\n"
19274       "    {56,\n"
19275       "     \"hello world i am a very long line that really, in any just world"
19276       ", ought to be split over \"\n"
19277       "     \"multiple lines\",    23},\n"
19278       "    {-1,      \"world\", 93463},\n"
19279       "    { 7,         \"!!\",     5},\n"
19280       "};",
19281       format("test demo[] = {{56, \"hello world i am a very long line "
19282              "that really, in any just world, ought to be split over multiple "
19283              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
19284              Style));
19285 }
19286 
19287 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
19288   auto Style = getLLVMStyle();
19289   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19290   /* FIXME: This case gets misformatted.
19291   verifyFormat("auto foo = Items{\n"
19292                "    Section{0, bar(), },\n"
19293                "    Section{1, boo()  }\n"
19294                "};\n",
19295                Style);
19296   */
19297   verifyFormat("auto foo = Items{\n"
19298                "    Section{\n"
19299                "            0, bar(),\n"
19300                "            }\n"
19301                "};\n",
19302                Style);
19303   verifyFormat("struct test demo[] = {\n"
19304                "    {56, 23,    \"hello\"},\n"
19305                "    {-1, 93463, \"world\"},\n"
19306                "    {7,  5,     \"!!\"   }\n"
19307                "};\n",
19308                Style);
19309   verifyFormat("struct test demo[] = {\n"
19310                "    {56, 23,    \"hello\"}, // first line\n"
19311                "    {-1, 93463, \"world\"}, // second line\n"
19312                "    {7,  5,     \"!!\"   }  // third line\n"
19313                "};\n",
19314                Style);
19315   verifyFormat("struct test demo[4] = {\n"
19316                "    {56,  23,    21, \"oh\"      }, // first line\n"
19317                "    {-1,  93463, 22, \"my\"      }, // second line\n"
19318                "    {7,   5,     1,  \"goodness\"}  // third line\n"
19319                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
19320                "};\n",
19321                Style);
19322   verifyFormat("struct test demo[3] = {\n"
19323                "    {56, 23,    \"hello\"},\n"
19324                "    {-1, 93463, \"world\"},\n"
19325                "    {7,  5,     \"!!\"   }\n"
19326                "};\n",
19327                Style);
19328 
19329   verifyFormat("struct test demo[3] = {\n"
19330                "    {int{56}, 23,    \"hello\"},\n"
19331                "    {int{-1}, 93463, \"world\"},\n"
19332                "    {int{7},  5,     \"!!\"   }\n"
19333                "};\n",
19334                Style);
19335   verifyFormat("struct test demo[] = {\n"
19336                "    {56, 23,    \"hello\"},\n"
19337                "    {-1, 93463, \"world\"},\n"
19338                "    {7,  5,     \"!!\"   },\n"
19339                "};\n",
19340                Style);
19341   verifyFormat("test demo[] = {\n"
19342                "    {56, 23,    \"hello\"},\n"
19343                "    {-1, 93463, \"world\"},\n"
19344                "    {7,  5,     \"!!\"   },\n"
19345                "};\n",
19346                Style);
19347   verifyFormat("demo = std::array<struct test, 3>{\n"
19348                "    test{56, 23,    \"hello\"},\n"
19349                "    test{-1, 93463, \"world\"},\n"
19350                "    test{7,  5,     \"!!\"   },\n"
19351                "};\n",
19352                Style);
19353   verifyFormat("test demo[] = {\n"
19354                "    {56, 23,    \"hello\"},\n"
19355                "#if X\n"
19356                "    {-1, 93463, \"world\"},\n"
19357                "#endif\n"
19358                "    {7,  5,     \"!!\"   }\n"
19359                "};\n",
19360                Style);
19361   verifyFormat(
19362       "test demo[] = {\n"
19363       "    {7,  23,\n"
19364       "     \"hello world i am a very long line that really, in any\"\n"
19365       "     \"just world, ought to be split over multiple lines\"},\n"
19366       "    {-1, 93463, \"world\"                                 },\n"
19367       "    {56, 5,     \"!!\"                                    }\n"
19368       "};\n",
19369       Style);
19370 
19371   verifyFormat("return GradForUnaryCwise(g, {\n"
19372                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19373                "\"dy\"}   },\n"
19374                "                                {{\"dx\"},   \"Mul\",  "
19375                "{\"dy\", \"sign\"}},\n"
19376                "});\n",
19377                Style);
19378 
19379   Style.ColumnLimit = 0;
19380   EXPECT_EQ(
19381       "test demo[] = {\n"
19382       "    {56, 23,    \"hello world i am a very long line that really, in any "
19383       "just world, ought to be split over multiple lines\"},\n"
19384       "    {-1, 93463, \"world\"                                               "
19385       "                                                   },\n"
19386       "    {7,  5,     \"!!\"                                                  "
19387       "                                                   },\n"
19388       "};",
19389       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19390              "that really, in any just world, ought to be split over multiple "
19391              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19392              Style));
19393 
19394   Style.ColumnLimit = 80;
19395   verifyFormat("test demo[] = {\n"
19396                "    {56, 23,    /* a comment */ \"hello\"},\n"
19397                "    {-1, 93463, \"world\"                },\n"
19398                "    {7,  5,     \"!!\"                   }\n"
19399                "};\n",
19400                Style);
19401 
19402   verifyFormat("test demo[] = {\n"
19403                "    {56, 23,    \"hello\"                   },\n"
19404                "    {-1, 93463, \"world\" /* comment here */},\n"
19405                "    {7,  5,     \"!!\"                      }\n"
19406                "};\n",
19407                Style);
19408 
19409   verifyFormat("test demo[] = {\n"
19410                "    {56, /* a comment */ 23, \"hello\"},\n"
19411                "    {-1, 93463,              \"world\"},\n"
19412                "    {7,  5,                  \"!!\"   }\n"
19413                "};\n",
19414                Style);
19415 
19416   Style.ColumnLimit = 20;
19417   EXPECT_EQ(
19418       "demo = std::array<\n"
19419       "    struct test, 3>{\n"
19420       "    test{\n"
19421       "         56, 23,\n"
19422       "         \"hello \"\n"
19423       "         \"world i \"\n"
19424       "         \"am a very \"\n"
19425       "         \"long line \"\n"
19426       "         \"that \"\n"
19427       "         \"really, \"\n"
19428       "         \"in any \"\n"
19429       "         \"just \"\n"
19430       "         \"world, \"\n"
19431       "         \"ought to \"\n"
19432       "         \"be split \"\n"
19433       "         \"over \"\n"
19434       "         \"multiple \"\n"
19435       "         \"lines\"},\n"
19436       "    test{-1, 93463,\n"
19437       "         \"world\"},\n"
19438       "    test{7,  5,\n"
19439       "         \"!!\"   },\n"
19440       "};",
19441       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19442              "i am a very long line that really, in any just world, ought "
19443              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19444              "test{7, 5, \"!!\"},};",
19445              Style));
19446 
19447   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19448   Style = getLLVMStyleWithColumns(50);
19449   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19450   verifyFormat("static A x = {\n"
19451                "    {{init1, init2, init3, init4},\n"
19452                "     {init1, init2, init3, init4}}\n"
19453                "};",
19454                Style);
19455   Style.ColumnLimit = 100;
19456   EXPECT_EQ(
19457       "test demo[] = {\n"
19458       "    {56, 23,\n"
19459       "     \"hello world i am a very long line that really, in any just world"
19460       ", ought to be split over \"\n"
19461       "     \"multiple lines\"  },\n"
19462       "    {-1, 93463, \"world\"},\n"
19463       "    {7,  5,     \"!!\"   },\n"
19464       "};",
19465       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19466              "that really, in any just world, ought to be split over multiple "
19467              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19468              Style));
19469 }
19470 
19471 TEST_F(FormatTest, UnderstandsPragmas) {
19472   verifyFormat("#pragma omp reduction(| : var)");
19473   verifyFormat("#pragma omp reduction(+ : var)");
19474 
19475   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19476             "(including parentheses).",
19477             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19478                    "(including parentheses)."));
19479 }
19480 
19481 TEST_F(FormatTest, UnderstandPragmaOption) {
19482   verifyFormat("#pragma option -C -A");
19483 
19484   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19485 }
19486 
19487 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19488   FormatStyle Style = getLLVMStyleWithColumns(20);
19489 
19490   // See PR41213
19491   EXPECT_EQ("/*\n"
19492             " *\t9012345\n"
19493             " * /8901\n"
19494             " */",
19495             format("/*\n"
19496                    " *\t9012345 /8901\n"
19497                    " */",
19498                    Style));
19499   EXPECT_EQ("/*\n"
19500             " *345678\n"
19501             " *\t/8901\n"
19502             " */",
19503             format("/*\n"
19504                    " *345678\t/8901\n"
19505                    " */",
19506                    Style));
19507 
19508   verifyFormat("int a; // the\n"
19509                "       // comment",
19510                Style);
19511   EXPECT_EQ("int a; /* first line\n"
19512             "        * second\n"
19513             "        * line third\n"
19514             "        * line\n"
19515             "        */",
19516             format("int a; /* first line\n"
19517                    "        * second\n"
19518                    "        * line third\n"
19519                    "        * line\n"
19520                    "        */",
19521                    Style));
19522   EXPECT_EQ("int a; // first line\n"
19523             "       // second\n"
19524             "       // line third\n"
19525             "       // line",
19526             format("int a; // first line\n"
19527                    "       // second line\n"
19528                    "       // third line",
19529                    Style));
19530 
19531   Style.PenaltyExcessCharacter = 90;
19532   verifyFormat("int a; // the comment", Style);
19533   EXPECT_EQ("int a; // the comment\n"
19534             "       // aaa",
19535             format("int a; // the comment aaa", Style));
19536   EXPECT_EQ("int a; /* first line\n"
19537             "        * second line\n"
19538             "        * third line\n"
19539             "        */",
19540             format("int a; /* first line\n"
19541                    "        * second line\n"
19542                    "        * third line\n"
19543                    "        */",
19544                    Style));
19545   EXPECT_EQ("int a; // first line\n"
19546             "       // second line\n"
19547             "       // third line",
19548             format("int a; // first line\n"
19549                    "       // second line\n"
19550                    "       // third line",
19551                    Style));
19552   // FIXME: Investigate why this is not getting the same layout as the test
19553   // above.
19554   EXPECT_EQ("int a; /* first line\n"
19555             "        * second line\n"
19556             "        * third line\n"
19557             "        */",
19558             format("int a; /* first line second line third line"
19559                    "\n*/",
19560                    Style));
19561 
19562   EXPECT_EQ("// foo bar baz bazfoo\n"
19563             "// foo bar foo bar\n",
19564             format("// foo bar baz bazfoo\n"
19565                    "// foo bar foo           bar\n",
19566                    Style));
19567   EXPECT_EQ("// foo bar baz bazfoo\n"
19568             "// foo bar foo bar\n",
19569             format("// foo bar baz      bazfoo\n"
19570                    "// foo            bar foo bar\n",
19571                    Style));
19572 
19573   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19574   // next one.
19575   EXPECT_EQ("// foo bar baz bazfoo\n"
19576             "// bar foo bar\n",
19577             format("// foo bar baz      bazfoo bar\n"
19578                    "// foo            bar\n",
19579                    Style));
19580 
19581   EXPECT_EQ("// foo bar baz bazfoo\n"
19582             "// foo bar baz bazfoo\n"
19583             "// bar foo bar\n",
19584             format("// foo bar baz      bazfoo\n"
19585                    "// foo bar baz      bazfoo bar\n"
19586                    "// foo bar\n",
19587                    Style));
19588 
19589   EXPECT_EQ("// foo bar baz bazfoo\n"
19590             "// foo bar baz bazfoo\n"
19591             "// bar foo bar\n",
19592             format("// foo bar baz      bazfoo\n"
19593                    "// foo bar baz      bazfoo bar\n"
19594                    "// foo           bar\n",
19595                    Style));
19596 
19597   // Make sure we do not keep protruding characters if strict mode reflow is
19598   // cheaper than keeping protruding characters.
19599   Style.ColumnLimit = 21;
19600   EXPECT_EQ(
19601       "// foo foo foo foo\n"
19602       "// foo foo foo foo\n"
19603       "// foo foo foo foo\n",
19604       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19605 
19606   EXPECT_EQ("int a = /* long block\n"
19607             "           comment */\n"
19608             "    42;",
19609             format("int a = /* long block comment */ 42;", Style));
19610 }
19611 
19612 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19613   FormatStyle Style = getLLVMStyle();
19614   Style.ColumnLimit = 8;
19615   Style.PenaltyExcessCharacter = 15;
19616   verifyFormat("int foo(\n"
19617                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19618                Style);
19619   Style.PenaltyBreakOpenParenthesis = 200;
19620   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19621             format("int foo(\n"
19622                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19623                    Style));
19624 }
19625 
19626 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19627   FormatStyle Style = getLLVMStyle();
19628   Style.ColumnLimit = 5;
19629   Style.PenaltyExcessCharacter = 150;
19630   verifyFormat("foo((\n"
19631                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19632 
19633                Style);
19634   Style.PenaltyBreakOpenParenthesis = 100000;
19635   EXPECT_EQ("foo((int)\n"
19636             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19637             format("foo((\n"
19638                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19639                    Style));
19640 }
19641 
19642 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19643   FormatStyle Style = getLLVMStyle();
19644   Style.ColumnLimit = 4;
19645   Style.PenaltyExcessCharacter = 100;
19646   verifyFormat("for (\n"
19647                "    int iiiiiiiiiiiiiiiii =\n"
19648                "        0;\n"
19649                "    iiiiiiiiiiiiiiiii <\n"
19650                "    2;\n"
19651                "    iiiiiiiiiiiiiiiii++) {\n"
19652                "}",
19653 
19654                Style);
19655   Style.PenaltyBreakOpenParenthesis = 1250;
19656   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19657             "         0;\n"
19658             "     iiiiiiiiiiiiiiiii <\n"
19659             "     2;\n"
19660             "     iiiiiiiiiiiiiiiii++) {\n"
19661             "}",
19662             format("for (\n"
19663                    "    int iiiiiiiiiiiiiiiii =\n"
19664                    "        0;\n"
19665                    "    iiiiiiiiiiiiiiiii <\n"
19666                    "    2;\n"
19667                    "    iiiiiiiiiiiiiiiii++) {\n"
19668                    "}",
19669                    Style));
19670 }
19671 
19672 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19673   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19674   EXPECT_EQ(Styles[0], Styles[i])                                              \
19675       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19676 
19677 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19678   SmallVector<FormatStyle, 3> Styles;
19679   Styles.resize(3);
19680 
19681   Styles[0] = getLLVMStyle();
19682   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19683   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19684   EXPECT_ALL_STYLES_EQUAL(Styles);
19685 
19686   Styles[0] = getGoogleStyle();
19687   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19688   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19689   EXPECT_ALL_STYLES_EQUAL(Styles);
19690 
19691   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19692   EXPECT_TRUE(
19693       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19694   EXPECT_TRUE(
19695       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19696   EXPECT_ALL_STYLES_EQUAL(Styles);
19697 
19698   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19699   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19700   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19701   EXPECT_ALL_STYLES_EQUAL(Styles);
19702 
19703   Styles[0] = getMozillaStyle();
19704   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19705   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19706   EXPECT_ALL_STYLES_EQUAL(Styles);
19707 
19708   Styles[0] = getWebKitStyle();
19709   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19710   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19711   EXPECT_ALL_STYLES_EQUAL(Styles);
19712 
19713   Styles[0] = getGNUStyle();
19714   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19715   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19716   EXPECT_ALL_STYLES_EQUAL(Styles);
19717 
19718   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19719 }
19720 
19721 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19722   SmallVector<FormatStyle, 8> Styles;
19723   Styles.resize(2);
19724 
19725   Styles[0] = getGoogleStyle();
19726   Styles[1] = getLLVMStyle();
19727   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19728   EXPECT_ALL_STYLES_EQUAL(Styles);
19729 
19730   Styles.resize(5);
19731   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19732   Styles[1] = getLLVMStyle();
19733   Styles[1].Language = FormatStyle::LK_JavaScript;
19734   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19735 
19736   Styles[2] = getLLVMStyle();
19737   Styles[2].Language = FormatStyle::LK_JavaScript;
19738   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19739                                   "BasedOnStyle: Google",
19740                                   &Styles[2])
19741                    .value());
19742 
19743   Styles[3] = getLLVMStyle();
19744   Styles[3].Language = FormatStyle::LK_JavaScript;
19745   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19746                                   "Language: JavaScript",
19747                                   &Styles[3])
19748                    .value());
19749 
19750   Styles[4] = getLLVMStyle();
19751   Styles[4].Language = FormatStyle::LK_JavaScript;
19752   EXPECT_EQ(0, parseConfiguration("---\n"
19753                                   "BasedOnStyle: LLVM\n"
19754                                   "IndentWidth: 123\n"
19755                                   "---\n"
19756                                   "BasedOnStyle: Google\n"
19757                                   "Language: JavaScript",
19758                                   &Styles[4])
19759                    .value());
19760   EXPECT_ALL_STYLES_EQUAL(Styles);
19761 }
19762 
19763 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
19764   Style.FIELD = false;                                                         \
19765   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
19766   EXPECT_TRUE(Style.FIELD);                                                    \
19767   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
19768   EXPECT_FALSE(Style.FIELD);
19769 
19770 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
19771 
19772 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
19773   Style.STRUCT.FIELD = false;                                                  \
19774   EXPECT_EQ(0,                                                                 \
19775             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
19776                 .value());                                                     \
19777   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
19778   EXPECT_EQ(0,                                                                 \
19779             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
19780                 .value());                                                     \
19781   EXPECT_FALSE(Style.STRUCT.FIELD);
19782 
19783 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
19784   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
19785 
19786 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
19787   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
19788   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
19789   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
19790 
19791 TEST_F(FormatTest, ParsesConfigurationBools) {
19792   FormatStyle Style = {};
19793   Style.Language = FormatStyle::LK_Cpp;
19794   CHECK_PARSE_BOOL(AlignTrailingComments);
19795   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
19796   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
19797   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
19798   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
19799   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
19800   CHECK_PARSE_BOOL(BinPackArguments);
19801   CHECK_PARSE_BOOL(BinPackParameters);
19802   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
19803   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
19804   CHECK_PARSE_BOOL(BreakStringLiterals);
19805   CHECK_PARSE_BOOL(CompactNamespaces);
19806   CHECK_PARSE_BOOL(DeriveLineEnding);
19807   CHECK_PARSE_BOOL(DerivePointerAlignment);
19808   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
19809   CHECK_PARSE_BOOL(DisableFormat);
19810   CHECK_PARSE_BOOL(IndentAccessModifiers);
19811   CHECK_PARSE_BOOL(IndentCaseLabels);
19812   CHECK_PARSE_BOOL(IndentCaseBlocks);
19813   CHECK_PARSE_BOOL(IndentGotoLabels);
19814   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
19815   CHECK_PARSE_BOOL(IndentRequiresClause);
19816   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
19817   CHECK_PARSE_BOOL(InsertBraces);
19818   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
19819   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
19820   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
19821   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
19822   CHECK_PARSE_BOOL(ReflowComments);
19823   CHECK_PARSE_BOOL(RemoveBracesLLVM);
19824   CHECK_PARSE_BOOL(SortUsingDeclarations);
19825   CHECK_PARSE_BOOL(SpacesInParentheses);
19826   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
19827   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
19828   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
19829   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
19830   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
19831   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19832   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19833   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19834   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19835   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19836   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19837   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19838   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19839   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19840   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19841   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19842   CHECK_PARSE_BOOL(UseCRLF);
19843 
19844   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19845   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19846   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19847   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19848   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19849   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19850   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19851   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19852   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19853   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19854   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19855   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19856   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19857   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19858   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19859   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19860   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19861   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19862   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19863   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19864                           AfterFunctionDeclarationName);
19865   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19866                           AfterFunctionDefinitionName);
19867   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19868   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19869   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19870 }
19871 
19872 #undef CHECK_PARSE_BOOL
19873 
19874 TEST_F(FormatTest, ParsesConfiguration) {
19875   FormatStyle Style = {};
19876   Style.Language = FormatStyle::LK_Cpp;
19877   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19878   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19879               ConstructorInitializerIndentWidth, 1234u);
19880   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19881   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19882   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19883   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19884   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19885               PenaltyBreakBeforeFirstCallParameter, 1234u);
19886   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
19887               PenaltyBreakTemplateDeclaration, 1234u);
19888   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
19889               1234u);
19890   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
19891   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
19892               PenaltyReturnTypeOnItsOwnLine, 1234u);
19893   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
19894               SpacesBeforeTrailingComments, 1234u);
19895   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
19896   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
19897   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
19898 
19899   Style.QualifierAlignment = FormatStyle::QAS_Right;
19900   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
19901               FormatStyle::QAS_Leave);
19902   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
19903               FormatStyle::QAS_Right);
19904   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
19905               FormatStyle::QAS_Left);
19906   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
19907               FormatStyle::QAS_Custom);
19908 
19909   Style.QualifierOrder.clear();
19910   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
19911               std::vector<std::string>({"const", "volatile", "type"}));
19912   Style.QualifierOrder.clear();
19913   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
19914               std::vector<std::string>({"const", "type"}));
19915   Style.QualifierOrder.clear();
19916   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
19917               std::vector<std::string>({"volatile", "type"}));
19918 
19919 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
19920   do {                                                                         \
19921     Style.FIELD.Enabled = true;                                                \
19922     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
19923                 FormatStyle::AlignConsecutiveStyle(                            \
19924                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19925                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19926                      /*PadOperators=*/true}));                                 \
19927     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
19928                 FormatStyle::AlignConsecutiveStyle(                            \
19929                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19930                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19931                      /*PadOperators=*/true}));                                 \
19932     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
19933                 FormatStyle::AlignConsecutiveStyle(                            \
19934                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19935                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19936                      /*PadOperators=*/true}));                                 \
19937     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
19938                 FormatStyle::AlignConsecutiveStyle(                            \
19939                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19940                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
19941                      /*PadOperators=*/true}));                                 \
19942     /* For backwards compability, false / true should still parse */           \
19943     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
19944                 FormatStyle::AlignConsecutiveStyle(                            \
19945                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19946                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19947                      /*PadOperators=*/true}));                                 \
19948     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
19949                 FormatStyle::AlignConsecutiveStyle(                            \
19950                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19951                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19952                      /*PadOperators=*/true}));                                 \
19953                                                                                \
19954     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
19955     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
19956     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
19957     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
19958     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
19959   } while (false)
19960 
19961   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
19962   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
19963   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
19964   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
19965 
19966 #undef CHECK_ALIGN_CONSECUTIVE
19967 
19968   Style.PointerAlignment = FormatStyle::PAS_Middle;
19969   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
19970               FormatStyle::PAS_Left);
19971   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
19972               FormatStyle::PAS_Right);
19973   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
19974               FormatStyle::PAS_Middle);
19975   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
19976   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
19977               FormatStyle::RAS_Pointer);
19978   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
19979               FormatStyle::RAS_Left);
19980   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
19981               FormatStyle::RAS_Right);
19982   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
19983               FormatStyle::RAS_Middle);
19984   // For backward compatibility:
19985   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
19986               FormatStyle::PAS_Left);
19987   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
19988               FormatStyle::PAS_Right);
19989   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
19990               FormatStyle::PAS_Middle);
19991 
19992   Style.Standard = FormatStyle::LS_Auto;
19993   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
19994   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
19995   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
19996   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
19997   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
19998   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
19999   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
20000   // Legacy aliases:
20001   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
20002   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
20003   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
20004   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
20005 
20006   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
20007   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
20008               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
20009   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
20010               FormatStyle::BOS_None);
20011   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
20012               FormatStyle::BOS_All);
20013   // For backward compatibility:
20014   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
20015               FormatStyle::BOS_None);
20016   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
20017               FormatStyle::BOS_All);
20018 
20019   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20020   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
20021               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20022   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
20023               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
20024   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
20025               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
20026   // For backward compatibility:
20027   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
20028               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20029 
20030   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
20031   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
20032               FormatStyle::BILS_AfterComma);
20033   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
20034               FormatStyle::BILS_BeforeComma);
20035   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
20036               FormatStyle::BILS_AfterColon);
20037   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
20038               FormatStyle::BILS_BeforeColon);
20039   // For backward compatibility:
20040   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
20041               FormatStyle::BILS_BeforeComma);
20042 
20043   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20044   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
20045               FormatStyle::PCIS_Never);
20046   CHECK_PARSE("PackConstructorInitializers: BinPack",
20047               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20048   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
20049               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20050   CHECK_PARSE("PackConstructorInitializers: NextLine",
20051               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20052   // For backward compatibility:
20053   CHECK_PARSE("BasedOnStyle: Google\n"
20054               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20055               "AllowAllConstructorInitializersOnNextLine: false",
20056               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20057   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20058   CHECK_PARSE("BasedOnStyle: Google\n"
20059               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
20060               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20061   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20062               "AllowAllConstructorInitializersOnNextLine: true",
20063               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20064   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20065   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20066               "AllowAllConstructorInitializersOnNextLine: false",
20067               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20068 
20069   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
20070   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
20071               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
20072   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
20073               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
20074   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
20075               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
20076   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
20077               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
20078 
20079   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20080   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
20081               FormatStyle::BAS_Align);
20082   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
20083               FormatStyle::BAS_DontAlign);
20084   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
20085               FormatStyle::BAS_AlwaysBreak);
20086   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
20087               FormatStyle::BAS_BlockIndent);
20088   // For backward compatibility:
20089   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
20090               FormatStyle::BAS_DontAlign);
20091   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
20092               FormatStyle::BAS_Align);
20093 
20094   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
20095   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
20096               FormatStyle::ENAS_DontAlign);
20097   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
20098               FormatStyle::ENAS_Left);
20099   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
20100               FormatStyle::ENAS_Right);
20101   // For backward compatibility:
20102   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
20103               FormatStyle::ENAS_Left);
20104   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
20105               FormatStyle::ENAS_Right);
20106 
20107   Style.AlignOperands = FormatStyle::OAS_Align;
20108   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
20109               FormatStyle::OAS_DontAlign);
20110   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
20111   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
20112               FormatStyle::OAS_AlignAfterOperator);
20113   // For backward compatibility:
20114   CHECK_PARSE("AlignOperands: false", AlignOperands,
20115               FormatStyle::OAS_DontAlign);
20116   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
20117 
20118   Style.UseTab = FormatStyle::UT_ForIndentation;
20119   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
20120   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
20121   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
20122   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
20123               FormatStyle::UT_ForContinuationAndIndentation);
20124   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
20125               FormatStyle::UT_AlignWithSpaces);
20126   // For backward compatibility:
20127   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
20128   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
20129 
20130   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
20131   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
20132               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20133   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
20134               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
20135   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
20136               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20137   // For backward compatibility:
20138   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
20139               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20140   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
20141               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20142 
20143   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
20144   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
20145               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20146   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
20147               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
20148   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
20149               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
20150   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
20151               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20152   // For backward compatibility:
20153   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
20154               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20155   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
20156               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20157 
20158   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
20159   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
20160               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
20161   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
20162               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
20163   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
20164               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
20165   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
20166               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
20167 
20168   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20169   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
20170               FormatStyle::SBPO_Never);
20171   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
20172               FormatStyle::SBPO_Always);
20173   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
20174               FormatStyle::SBPO_ControlStatements);
20175   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
20176               SpaceBeforeParens,
20177               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20178   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
20179               FormatStyle::SBPO_NonEmptyParentheses);
20180   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
20181               FormatStyle::SBPO_Custom);
20182   // For backward compatibility:
20183   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
20184               FormatStyle::SBPO_Never);
20185   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
20186               FormatStyle::SBPO_ControlStatements);
20187   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
20188               SpaceBeforeParens,
20189               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20190 
20191   Style.ColumnLimit = 123;
20192   FormatStyle BaseStyle = getLLVMStyle();
20193   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
20194   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
20195 
20196   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
20197   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
20198               FormatStyle::BS_Attach);
20199   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
20200               FormatStyle::BS_Linux);
20201   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
20202               FormatStyle::BS_Mozilla);
20203   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
20204               FormatStyle::BS_Stroustrup);
20205   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
20206               FormatStyle::BS_Allman);
20207   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
20208               FormatStyle::BS_Whitesmiths);
20209   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
20210   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
20211               FormatStyle::BS_WebKit);
20212   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
20213               FormatStyle::BS_Custom);
20214 
20215   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
20216   CHECK_PARSE("BraceWrapping:\n"
20217               "  AfterControlStatement: MultiLine",
20218               BraceWrapping.AfterControlStatement,
20219               FormatStyle::BWACS_MultiLine);
20220   CHECK_PARSE("BraceWrapping:\n"
20221               "  AfterControlStatement: Always",
20222               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20223   CHECK_PARSE("BraceWrapping:\n"
20224               "  AfterControlStatement: Never",
20225               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20226   // For backward compatibility:
20227   CHECK_PARSE("BraceWrapping:\n"
20228               "  AfterControlStatement: true",
20229               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20230   CHECK_PARSE("BraceWrapping:\n"
20231               "  AfterControlStatement: false",
20232               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20233 
20234   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
20235   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
20236               FormatStyle::RTBS_None);
20237   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
20238               FormatStyle::RTBS_All);
20239   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
20240               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
20241   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
20242               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
20243   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
20244               AlwaysBreakAfterReturnType,
20245               FormatStyle::RTBS_TopLevelDefinitions);
20246 
20247   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20248   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
20249               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
20250   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
20251               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20252   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
20253               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20254   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
20255               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20256   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
20257               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20258 
20259   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
20260   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
20261               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
20262   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
20263               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
20264   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
20265               AlwaysBreakAfterDefinitionReturnType,
20266               FormatStyle::DRTBS_TopLevel);
20267 
20268   Style.NamespaceIndentation = FormatStyle::NI_All;
20269   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
20270               FormatStyle::NI_None);
20271   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
20272               FormatStyle::NI_Inner);
20273   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
20274               FormatStyle::NI_All);
20275 
20276   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
20277   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
20278               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20279   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
20280               AllowShortIfStatementsOnASingleLine,
20281               FormatStyle::SIS_WithoutElse);
20282   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
20283               AllowShortIfStatementsOnASingleLine,
20284               FormatStyle::SIS_OnlyFirstIf);
20285   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
20286               AllowShortIfStatementsOnASingleLine,
20287               FormatStyle::SIS_AllIfsAndElse);
20288   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
20289               AllowShortIfStatementsOnASingleLine,
20290               FormatStyle::SIS_OnlyFirstIf);
20291   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
20292               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20293   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
20294               AllowShortIfStatementsOnASingleLine,
20295               FormatStyle::SIS_WithoutElse);
20296 
20297   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
20298   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
20299               FormatStyle::IEBS_AfterExternBlock);
20300   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
20301               FormatStyle::IEBS_Indent);
20302   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
20303               FormatStyle::IEBS_NoIndent);
20304   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
20305               FormatStyle::IEBS_Indent);
20306   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20307               FormatStyle::IEBS_NoIndent);
20308 
20309   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20310   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20311               FormatStyle::BFCS_Both);
20312   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20313               FormatStyle::BFCS_None);
20314   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20315               FormatStyle::BFCS_Before);
20316   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20317               FormatStyle::BFCS_After);
20318 
20319   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20320   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20321               FormatStyle::SJSIO_After);
20322   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20323               FormatStyle::SJSIO_Before);
20324 
20325   // FIXME: This is required because parsing a configuration simply overwrites
20326   // the first N elements of the list instead of resetting it.
20327   Style.ForEachMacros.clear();
20328   std::vector<std::string> BoostForeach;
20329   BoostForeach.push_back("BOOST_FOREACH");
20330   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20331   std::vector<std::string> BoostAndQForeach;
20332   BoostAndQForeach.push_back("BOOST_FOREACH");
20333   BoostAndQForeach.push_back("Q_FOREACH");
20334   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20335               BoostAndQForeach);
20336 
20337   Style.IfMacros.clear();
20338   std::vector<std::string> CustomIfs;
20339   CustomIfs.push_back("MYIF");
20340   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20341 
20342   Style.AttributeMacros.clear();
20343   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20344               std::vector<std::string>{"__capability"});
20345   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20346               std::vector<std::string>({"attr1", "attr2"}));
20347 
20348   Style.StatementAttributeLikeMacros.clear();
20349   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20350               StatementAttributeLikeMacros,
20351               std::vector<std::string>({"emit", "Q_EMIT"}));
20352 
20353   Style.StatementMacros.clear();
20354   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20355               std::vector<std::string>{"QUNUSED"});
20356   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20357               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20358 
20359   Style.NamespaceMacros.clear();
20360   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20361               std::vector<std::string>{"TESTSUITE"});
20362   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20363               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20364 
20365   Style.WhitespaceSensitiveMacros.clear();
20366   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20367               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20368   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20369               WhitespaceSensitiveMacros,
20370               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
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 
20378   Style.IncludeStyle.IncludeCategories.clear();
20379   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20380       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20381   CHECK_PARSE("IncludeCategories:\n"
20382               "  - Regex: abc/.*\n"
20383               "    Priority: 2\n"
20384               "  - Regex: .*\n"
20385               "    Priority: 1\n"
20386               "    CaseSensitive: true\n",
20387               IncludeStyle.IncludeCategories, ExpectedCategories);
20388   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20389               "abc$");
20390   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20391               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20392 
20393   Style.SortIncludes = FormatStyle::SI_Never;
20394   CHECK_PARSE("SortIncludes: true", SortIncludes,
20395               FormatStyle::SI_CaseSensitive);
20396   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20397   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20398               FormatStyle::SI_CaseInsensitive);
20399   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20400               FormatStyle::SI_CaseSensitive);
20401   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20402 
20403   Style.RawStringFormats.clear();
20404   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20405       {
20406           FormatStyle::LK_TextProto,
20407           {"pb", "proto"},
20408           {"PARSE_TEXT_PROTO"},
20409           /*CanonicalDelimiter=*/"",
20410           "llvm",
20411       },
20412       {
20413           FormatStyle::LK_Cpp,
20414           {"cc", "cpp"},
20415           {"C_CODEBLOCK", "CPPEVAL"},
20416           /*CanonicalDelimiter=*/"cc",
20417           /*BasedOnStyle=*/"",
20418       },
20419   };
20420 
20421   CHECK_PARSE("RawStringFormats:\n"
20422               "  - Language: TextProto\n"
20423               "    Delimiters:\n"
20424               "      - 'pb'\n"
20425               "      - 'proto'\n"
20426               "    EnclosingFunctions:\n"
20427               "      - 'PARSE_TEXT_PROTO'\n"
20428               "    BasedOnStyle: llvm\n"
20429               "  - Language: Cpp\n"
20430               "    Delimiters:\n"
20431               "      - 'cc'\n"
20432               "      - 'cpp'\n"
20433               "    EnclosingFunctions:\n"
20434               "      - 'C_CODEBLOCK'\n"
20435               "      - 'CPPEVAL'\n"
20436               "    CanonicalDelimiter: 'cc'",
20437               RawStringFormats, ExpectedRawStringFormats);
20438 
20439   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20440               "  Minimum: 0\n"
20441               "  Maximum: 0",
20442               SpacesInLineCommentPrefix.Minimum, 0u);
20443   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20444   Style.SpacesInLineCommentPrefix.Minimum = 1;
20445   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20446               "  Minimum: 2",
20447               SpacesInLineCommentPrefix.Minimum, 0u);
20448   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20449               "  Maximum: -1",
20450               SpacesInLineCommentPrefix.Maximum, -1u);
20451   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20452               "  Minimum: 2",
20453               SpacesInLineCommentPrefix.Minimum, 2u);
20454   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20455               "  Maximum: 1",
20456               SpacesInLineCommentPrefix.Maximum, 1u);
20457   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20458 
20459   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20460   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20461   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20462               FormatStyle::SIAS_Always);
20463   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20464   // For backward compatibility:
20465   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20466   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20467 
20468   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20469               FormatStyle::RCPS_WithPreceding);
20470   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20471               FormatStyle::RCPS_WithFollowing);
20472   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20473               FormatStyle::RCPS_SingleLine);
20474   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20475               FormatStyle::RCPS_OwnLine);
20476 
20477   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20478               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20479   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20480               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20481   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20482               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20483   // For backward compatibility:
20484   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20485               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20486   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20487               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20488 }
20489 
20490 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20491   FormatStyle Style = {};
20492   Style.Language = FormatStyle::LK_Cpp;
20493   CHECK_PARSE("Language: Cpp\n"
20494               "IndentWidth: 12",
20495               IndentWidth, 12u);
20496   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20497                                "IndentWidth: 34",
20498                                &Style),
20499             ParseError::Unsuitable);
20500   FormatStyle BinPackedTCS = {};
20501   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20502   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20503                                "InsertTrailingCommas: Wrapped",
20504                                &BinPackedTCS),
20505             ParseError::BinPackTrailingCommaConflict);
20506   EXPECT_EQ(12u, Style.IndentWidth);
20507   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20508   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20509 
20510   Style.Language = FormatStyle::LK_JavaScript;
20511   CHECK_PARSE("Language: JavaScript\n"
20512               "IndentWidth: 12",
20513               IndentWidth, 12u);
20514   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20515   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20516                                "IndentWidth: 34",
20517                                &Style),
20518             ParseError::Unsuitable);
20519   EXPECT_EQ(23u, Style.IndentWidth);
20520   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20521   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20522 
20523   CHECK_PARSE("BasedOnStyle: LLVM\n"
20524               "IndentWidth: 67",
20525               IndentWidth, 67u);
20526 
20527   CHECK_PARSE("---\n"
20528               "Language: JavaScript\n"
20529               "IndentWidth: 12\n"
20530               "---\n"
20531               "Language: Cpp\n"
20532               "IndentWidth: 34\n"
20533               "...\n",
20534               IndentWidth, 12u);
20535 
20536   Style.Language = FormatStyle::LK_Cpp;
20537   CHECK_PARSE("---\n"
20538               "Language: JavaScript\n"
20539               "IndentWidth: 12\n"
20540               "---\n"
20541               "Language: Cpp\n"
20542               "IndentWidth: 34\n"
20543               "...\n",
20544               IndentWidth, 34u);
20545   CHECK_PARSE("---\n"
20546               "IndentWidth: 78\n"
20547               "---\n"
20548               "Language: JavaScript\n"
20549               "IndentWidth: 56\n"
20550               "...\n",
20551               IndentWidth, 78u);
20552 
20553   Style.ColumnLimit = 123;
20554   Style.IndentWidth = 234;
20555   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20556   Style.TabWidth = 345;
20557   EXPECT_FALSE(parseConfiguration("---\n"
20558                                   "IndentWidth: 456\n"
20559                                   "BreakBeforeBraces: Allman\n"
20560                                   "---\n"
20561                                   "Language: JavaScript\n"
20562                                   "IndentWidth: 111\n"
20563                                   "TabWidth: 111\n"
20564                                   "---\n"
20565                                   "Language: Cpp\n"
20566                                   "BreakBeforeBraces: Stroustrup\n"
20567                                   "TabWidth: 789\n"
20568                                   "...\n",
20569                                   &Style));
20570   EXPECT_EQ(123u, Style.ColumnLimit);
20571   EXPECT_EQ(456u, Style.IndentWidth);
20572   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20573   EXPECT_EQ(789u, Style.TabWidth);
20574 
20575   EXPECT_EQ(parseConfiguration("---\n"
20576                                "Language: JavaScript\n"
20577                                "IndentWidth: 56\n"
20578                                "---\n"
20579                                "IndentWidth: 78\n"
20580                                "...\n",
20581                                &Style),
20582             ParseError::Error);
20583   EXPECT_EQ(parseConfiguration("---\n"
20584                                "Language: JavaScript\n"
20585                                "IndentWidth: 56\n"
20586                                "---\n"
20587                                "Language: JavaScript\n"
20588                                "IndentWidth: 78\n"
20589                                "...\n",
20590                                &Style),
20591             ParseError::Error);
20592 
20593   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20594 }
20595 
20596 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20597   FormatStyle Style = {};
20598   Style.Language = FormatStyle::LK_JavaScript;
20599   Style.BreakBeforeTernaryOperators = true;
20600   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20601   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20602 
20603   Style.BreakBeforeTernaryOperators = true;
20604   EXPECT_EQ(0, parseConfiguration("---\n"
20605                                   "BasedOnStyle: Google\n"
20606                                   "---\n"
20607                                   "Language: JavaScript\n"
20608                                   "IndentWidth: 76\n"
20609                                   "...\n",
20610                                   &Style)
20611                    .value());
20612   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20613   EXPECT_EQ(76u, Style.IndentWidth);
20614   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20615 }
20616 
20617 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20618   FormatStyle Style = getLLVMStyle();
20619   std::string YAML = configurationAsText(Style);
20620   FormatStyle ParsedStyle = {};
20621   ParsedStyle.Language = FormatStyle::LK_Cpp;
20622   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20623   EXPECT_EQ(Style, ParsedStyle);
20624 }
20625 
20626 TEST_F(FormatTest, WorksFor8bitEncodings) {
20627   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20628             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20629             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20630             "\"\xef\xee\xf0\xf3...\"",
20631             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20632                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20633                    "\xef\xee\xf0\xf3...\"",
20634                    getLLVMStyleWithColumns(12)));
20635 }
20636 
20637 TEST_F(FormatTest, HandlesUTF8BOM) {
20638   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20639   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20640             format("\xef\xbb\xbf#include <iostream>"));
20641   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20642             format("\xef\xbb\xbf\n#include <iostream>"));
20643 }
20644 
20645 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20646 #if !defined(_MSC_VER)
20647 
20648 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20649   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20650                getLLVMStyleWithColumns(35));
20651   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20652                getLLVMStyleWithColumns(31));
20653   verifyFormat("// Однажды в студёную зимнюю пору...",
20654                getLLVMStyleWithColumns(36));
20655   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20656   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20657                getLLVMStyleWithColumns(39));
20658   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20659                getLLVMStyleWithColumns(35));
20660 }
20661 
20662 TEST_F(FormatTest, SplitsUTF8Strings) {
20663   // Non-printable characters' width is currently considered to be the length in
20664   // bytes in UTF8. The characters can be displayed in very different manner
20665   // (zero-width, single width with a substitution glyph, expanded to their code
20666   // (e.g. "<8d>"), so there's no single correct way to handle them.
20667   EXPECT_EQ("\"aaaaÄ\"\n"
20668             "\"\xc2\x8d\";",
20669             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20670   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20671             "\"\xc2\x8d\";",
20672             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20673   EXPECT_EQ("\"Однажды, в \"\n"
20674             "\"студёную \"\n"
20675             "\"зимнюю \"\n"
20676             "\"пору,\"",
20677             format("\"Однажды, в студёную зимнюю пору,\"",
20678                    getLLVMStyleWithColumns(13)));
20679   EXPECT_EQ(
20680       "\"一 二 三 \"\n"
20681       "\"四 五六 \"\n"
20682       "\"七 八 九 \"\n"
20683       "\"十\"",
20684       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20685   EXPECT_EQ("\"一\t\"\n"
20686             "\"二 \t\"\n"
20687             "\"三 四 \"\n"
20688             "\"五\t\"\n"
20689             "\"六 \t\"\n"
20690             "\"七 \"\n"
20691             "\"八九十\tqq\"",
20692             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20693                    getLLVMStyleWithColumns(11)));
20694 
20695   // UTF8 character in an escape sequence.
20696   EXPECT_EQ("\"aaaaaa\"\n"
20697             "\"\\\xC2\x8D\"",
20698             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20699 }
20700 
20701 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20702   EXPECT_EQ("const char *sssss =\n"
20703             "    \"一二三四五六七八\\\n"
20704             " 九 十\";",
20705             format("const char *sssss = \"一二三四五六七八\\\n"
20706                    " 九 十\";",
20707                    getLLVMStyleWithColumns(30)));
20708 }
20709 
20710 TEST_F(FormatTest, SplitsUTF8LineComments) {
20711   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20712             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20713   EXPECT_EQ("// Я из лесу\n"
20714             "// вышел; был\n"
20715             "// сильный\n"
20716             "// мороз.",
20717             format("// Я из лесу вышел; был сильный мороз.",
20718                    getLLVMStyleWithColumns(13)));
20719   EXPECT_EQ("// 一二三\n"
20720             "// 四五六七\n"
20721             "// 八  九\n"
20722             "// 十",
20723             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20724 }
20725 
20726 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20727   EXPECT_EQ("/* Гляжу,\n"
20728             " * поднимается\n"
20729             " * медленно в\n"
20730             " * гору\n"
20731             " * Лошадка,\n"
20732             " * везущая\n"
20733             " * хворосту\n"
20734             " * воз. */",
20735             format("/* Гляжу, поднимается медленно в гору\n"
20736                    " * Лошадка, везущая хворосту воз. */",
20737                    getLLVMStyleWithColumns(13)));
20738   EXPECT_EQ(
20739       "/* 一二三\n"
20740       " * 四五六七\n"
20741       " * 八  九\n"
20742       " * 十  */",
20743       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20744   EXPECT_EQ("/* �������� ��������\n"
20745             " * ��������\n"
20746             " * ������-�� */",
20747             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20748 }
20749 
20750 #endif // _MSC_VER
20751 
20752 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
20753   FormatStyle Style = getLLVMStyle();
20754 
20755   Style.ConstructorInitializerIndentWidth = 4;
20756   verifyFormat(
20757       "SomeClass::Constructor()\n"
20758       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20759       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20760       Style);
20761 
20762   Style.ConstructorInitializerIndentWidth = 2;
20763   verifyFormat(
20764       "SomeClass::Constructor()\n"
20765       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20766       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20767       Style);
20768 
20769   Style.ConstructorInitializerIndentWidth = 0;
20770   verifyFormat(
20771       "SomeClass::Constructor()\n"
20772       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20773       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20774       Style);
20775   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20776   verifyFormat(
20777       "SomeLongTemplateVariableName<\n"
20778       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
20779       Style);
20780   verifyFormat("bool smaller = 1 < "
20781                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
20782                "                       "
20783                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
20784                Style);
20785 
20786   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
20787   verifyFormat("SomeClass::Constructor() :\n"
20788                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
20789                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
20790                Style);
20791 }
20792 
20793 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
20794   FormatStyle Style = getLLVMStyle();
20795   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20796   Style.ConstructorInitializerIndentWidth = 4;
20797   verifyFormat("SomeClass::Constructor()\n"
20798                "    : a(a)\n"
20799                "    , b(b)\n"
20800                "    , c(c) {}",
20801                Style);
20802   verifyFormat("SomeClass::Constructor()\n"
20803                "    : a(a) {}",
20804                Style);
20805 
20806   Style.ColumnLimit = 0;
20807   verifyFormat("SomeClass::Constructor()\n"
20808                "    : a(a) {}",
20809                Style);
20810   verifyFormat("SomeClass::Constructor() noexcept\n"
20811                "    : a(a) {}",
20812                Style);
20813   verifyFormat("SomeClass::Constructor()\n"
20814                "    : a(a)\n"
20815                "    , b(b)\n"
20816                "    , c(c) {}",
20817                Style);
20818   verifyFormat("SomeClass::Constructor()\n"
20819                "    : a(a) {\n"
20820                "  foo();\n"
20821                "  bar();\n"
20822                "}",
20823                Style);
20824 
20825   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20826   verifyFormat("SomeClass::Constructor()\n"
20827                "    : a(a)\n"
20828                "    , b(b)\n"
20829                "    , c(c) {\n}",
20830                Style);
20831   verifyFormat("SomeClass::Constructor()\n"
20832                "    : a(a) {\n}",
20833                Style);
20834 
20835   Style.ColumnLimit = 80;
20836   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
20837   Style.ConstructorInitializerIndentWidth = 2;
20838   verifyFormat("SomeClass::Constructor()\n"
20839                "  : a(a)\n"
20840                "  , b(b)\n"
20841                "  , c(c) {}",
20842                Style);
20843 
20844   Style.ConstructorInitializerIndentWidth = 0;
20845   verifyFormat("SomeClass::Constructor()\n"
20846                ": a(a)\n"
20847                ", b(b)\n"
20848                ", c(c) {}",
20849                Style);
20850 
20851   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20852   Style.ConstructorInitializerIndentWidth = 4;
20853   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20854   verifyFormat(
20855       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20856       Style);
20857   verifyFormat(
20858       "SomeClass::Constructor()\n"
20859       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20860       Style);
20861   Style.ConstructorInitializerIndentWidth = 4;
20862   Style.ColumnLimit = 60;
20863   verifyFormat("SomeClass::Constructor()\n"
20864                "    : aaaaaaaa(aaaaaaaa)\n"
20865                "    , aaaaaaaa(aaaaaaaa)\n"
20866                "    , aaaaaaaa(aaaaaaaa) {}",
20867                Style);
20868 }
20869 
20870 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20871   FormatStyle Style = getLLVMStyle();
20872   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20873   Style.ConstructorInitializerIndentWidth = 4;
20874   verifyFormat("SomeClass::Constructor()\n"
20875                "    : a{a}\n"
20876                "    , b{b} {}",
20877                Style);
20878   verifyFormat("SomeClass::Constructor()\n"
20879                "    : a{a}\n"
20880                "#if CONDITION\n"
20881                "    , b{b}\n"
20882                "#endif\n"
20883                "{\n}",
20884                Style);
20885   Style.ConstructorInitializerIndentWidth = 2;
20886   verifyFormat("SomeClass::Constructor()\n"
20887                "#if CONDITION\n"
20888                "  : a{a}\n"
20889                "#endif\n"
20890                "  , b{b}\n"
20891                "  , c{c} {\n}",
20892                Style);
20893   Style.ConstructorInitializerIndentWidth = 0;
20894   verifyFormat("SomeClass::Constructor()\n"
20895                ": a{a}\n"
20896                "#ifdef CONDITION\n"
20897                ", b{b}\n"
20898                "#else\n"
20899                ", c{c}\n"
20900                "#endif\n"
20901                ", d{d} {\n}",
20902                Style);
20903   Style.ConstructorInitializerIndentWidth = 4;
20904   verifyFormat("SomeClass::Constructor()\n"
20905                "    : a{a}\n"
20906                "#if WINDOWS\n"
20907                "#if DEBUG\n"
20908                "    , b{0}\n"
20909                "#else\n"
20910                "    , b{1}\n"
20911                "#endif\n"
20912                "#else\n"
20913                "#if DEBUG\n"
20914                "    , b{2}\n"
20915                "#else\n"
20916                "    , b{3}\n"
20917                "#endif\n"
20918                "#endif\n"
20919                "{\n}",
20920                Style);
20921   verifyFormat("SomeClass::Constructor()\n"
20922                "    : a{a}\n"
20923                "#if WINDOWS\n"
20924                "    , b{0}\n"
20925                "#if DEBUG\n"
20926                "    , c{0}\n"
20927                "#else\n"
20928                "    , c{1}\n"
20929                "#endif\n"
20930                "#else\n"
20931                "#if DEBUG\n"
20932                "    , c{2}\n"
20933                "#else\n"
20934                "    , c{3}\n"
20935                "#endif\n"
20936                "    , b{1}\n"
20937                "#endif\n"
20938                "{\n}",
20939                Style);
20940 }
20941 
20942 TEST_F(FormatTest, Destructors) {
20943   verifyFormat("void F(int &i) { i.~int(); }");
20944   verifyFormat("void F(int &i) { i->~int(); }");
20945 }
20946 
20947 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20948   FormatStyle Style = getWebKitStyle();
20949 
20950   // Don't indent in outer namespaces.
20951   verifyFormat("namespace outer {\n"
20952                "int i;\n"
20953                "namespace inner {\n"
20954                "    int i;\n"
20955                "} // namespace inner\n"
20956                "} // namespace outer\n"
20957                "namespace other_outer {\n"
20958                "int i;\n"
20959                "}",
20960                Style);
20961 
20962   // Don't indent case labels.
20963   verifyFormat("switch (variable) {\n"
20964                "case 1:\n"
20965                "case 2:\n"
20966                "    doSomething();\n"
20967                "    break;\n"
20968                "default:\n"
20969                "    ++variable;\n"
20970                "}",
20971                Style);
20972 
20973   // Wrap before binary operators.
20974   EXPECT_EQ("void f()\n"
20975             "{\n"
20976             "    if (aaaaaaaaaaaaaaaa\n"
20977             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
20978             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20979             "        return;\n"
20980             "}",
20981             format("void f() {\n"
20982                    "if (aaaaaaaaaaaaaaaa\n"
20983                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
20984                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20985                    "return;\n"
20986                    "}",
20987                    Style));
20988 
20989   // Allow functions on a single line.
20990   verifyFormat("void f() { return; }", Style);
20991 
20992   // Allow empty blocks on a single line and insert a space in empty blocks.
20993   EXPECT_EQ("void f() { }", format("void f() {}", Style));
20994   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
20995   // However, don't merge non-empty short loops.
20996   EXPECT_EQ("while (true) {\n"
20997             "    continue;\n"
20998             "}",
20999             format("while (true) { continue; }", Style));
21000 
21001   // Constructor initializers are formatted one per line with the "," on the
21002   // new line.
21003   verifyFormat("Constructor()\n"
21004                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
21005                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
21006                "          aaaaaaaaaaaaaa)\n"
21007                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
21008                "{\n"
21009                "}",
21010                Style);
21011   verifyFormat("SomeClass::Constructor()\n"
21012                "    : a(a)\n"
21013                "{\n"
21014                "}",
21015                Style);
21016   EXPECT_EQ("SomeClass::Constructor()\n"
21017             "    : a(a)\n"
21018             "{\n"
21019             "}",
21020             format("SomeClass::Constructor():a(a){}", Style));
21021   verifyFormat("SomeClass::Constructor()\n"
21022                "    : a(a)\n"
21023                "    , b(b)\n"
21024                "    , c(c)\n"
21025                "{\n"
21026                "}",
21027                Style);
21028   verifyFormat("SomeClass::Constructor()\n"
21029                "    : a(a)\n"
21030                "{\n"
21031                "    foo();\n"
21032                "    bar();\n"
21033                "}",
21034                Style);
21035 
21036   // Access specifiers should be aligned left.
21037   verifyFormat("class C {\n"
21038                "public:\n"
21039                "    int i;\n"
21040                "};",
21041                Style);
21042 
21043   // Do not align comments.
21044   verifyFormat("int a; // Do not\n"
21045                "double b; // align comments.",
21046                Style);
21047 
21048   // Do not align operands.
21049   EXPECT_EQ("ASSERT(aaaa\n"
21050             "    || bbbb);",
21051             format("ASSERT ( aaaa\n||bbbb);", Style));
21052 
21053   // Accept input's line breaks.
21054   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
21055             "    || bbbbbbbbbbbbbbb) {\n"
21056             "    i++;\n"
21057             "}",
21058             format("if (aaaaaaaaaaaaaaa\n"
21059                    "|| bbbbbbbbbbbbbbb) { i++; }",
21060                    Style));
21061   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
21062             "    i++;\n"
21063             "}",
21064             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
21065 
21066   // Don't automatically break all macro definitions (llvm.org/PR17842).
21067   verifyFormat("#define aNumber 10", Style);
21068   // However, generally keep the line breaks that the user authored.
21069   EXPECT_EQ("#define aNumber \\\n"
21070             "    10",
21071             format("#define aNumber \\\n"
21072                    " 10",
21073                    Style));
21074 
21075   // Keep empty and one-element array literals on a single line.
21076   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
21077             "                                  copyItems:YES];",
21078             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
21079                    "copyItems:YES];",
21080                    Style));
21081   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
21082             "                                  copyItems:YES];",
21083             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
21084                    "             copyItems:YES];",
21085                    Style));
21086   // FIXME: This does not seem right, there should be more indentation before
21087   // the array literal's entries. Nested blocks have the same problem.
21088   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21089             "    @\"a\",\n"
21090             "    @\"a\"\n"
21091             "]\n"
21092             "                                  copyItems:YES];",
21093             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21094                    "     @\"a\",\n"
21095                    "     @\"a\"\n"
21096                    "     ]\n"
21097                    "       copyItems:YES];",
21098                    Style));
21099   EXPECT_EQ(
21100       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21101       "                                  copyItems:YES];",
21102       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21103              "   copyItems:YES];",
21104              Style));
21105 
21106   verifyFormat("[self.a b:c c:d];", Style);
21107   EXPECT_EQ("[self.a b:c\n"
21108             "        c:d];",
21109             format("[self.a b:c\n"
21110                    "c:d];",
21111                    Style));
21112 }
21113 
21114 TEST_F(FormatTest, FormatsLambdas) {
21115   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
21116   verifyFormat(
21117       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
21118   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
21119   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
21120   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
21121   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
21122   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
21123   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
21124   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
21125   verifyFormat("int x = f(*+[] {});");
21126   verifyFormat("void f() {\n"
21127                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
21128                "}\n");
21129   verifyFormat("void f() {\n"
21130                "  other(x.begin(), //\n"
21131                "        x.end(),   //\n"
21132                "        [&](int, int) { return 1; });\n"
21133                "}\n");
21134   verifyFormat("void f() {\n"
21135                "  other.other.other.other.other(\n"
21136                "      x.begin(), x.end(),\n"
21137                "      [something, rather](int, int, int, int, int, int, int) { "
21138                "return 1; });\n"
21139                "}\n");
21140   verifyFormat(
21141       "void f() {\n"
21142       "  other.other.other.other.other(\n"
21143       "      x.begin(), x.end(),\n"
21144       "      [something, rather](int, int, int, int, int, int, int) {\n"
21145       "        //\n"
21146       "      });\n"
21147       "}\n");
21148   verifyFormat("SomeFunction([]() { // A cool function...\n"
21149                "  return 43;\n"
21150                "});");
21151   EXPECT_EQ("SomeFunction([]() {\n"
21152             "#define A a\n"
21153             "  return 43;\n"
21154             "});",
21155             format("SomeFunction([](){\n"
21156                    "#define A a\n"
21157                    "return 43;\n"
21158                    "});"));
21159   verifyFormat("void f() {\n"
21160                "  SomeFunction([](decltype(x), A *a) {});\n"
21161                "  SomeFunction([](typeof(x), A *a) {});\n"
21162                "  SomeFunction([](_Atomic(x), A *a) {});\n"
21163                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
21164                "}");
21165   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21166                "    [](const aaaaaaaaaa &a) { return a; });");
21167   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
21168                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
21169                "});");
21170   verifyFormat("Constructor()\n"
21171                "    : Field([] { // comment\n"
21172                "        int i;\n"
21173                "      }) {}");
21174   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
21175                "  return some_parameter.size();\n"
21176                "};");
21177   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
21178                "    [](const string &s) { return s; };");
21179   verifyFormat("int i = aaaaaa ? 1 //\n"
21180                "               : [] {\n"
21181                "                   return 2; //\n"
21182                "                 }();");
21183   verifyFormat("llvm::errs() << \"number of twos is \"\n"
21184                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
21185                "                  return x == 2; // force break\n"
21186                "                });");
21187   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21188                "    [=](int iiiiiiiiiiii) {\n"
21189                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
21190                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
21191                "    });",
21192                getLLVMStyleWithColumns(60));
21193 
21194   verifyFormat("SomeFunction({[&] {\n"
21195                "                // comment\n"
21196                "              },\n"
21197                "              [&] {\n"
21198                "                // comment\n"
21199                "              }});");
21200   verifyFormat("SomeFunction({[&] {\n"
21201                "  // comment\n"
21202                "}});");
21203   verifyFormat(
21204       "virtual aaaaaaaaaaaaaaaa(\n"
21205       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
21206       "    aaaaa aaaaaaaaa);");
21207 
21208   // Lambdas with return types.
21209   verifyFormat("int c = []() -> int { return 2; }();\n");
21210   verifyFormat("int c = []() -> int * { return 2; }();\n");
21211   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
21212   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
21213   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
21214   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
21215   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
21216   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
21217   verifyFormat("[a, a]() -> a<1> {};");
21218   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
21219   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
21220   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
21221   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
21222   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
21223   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
21224   verifyFormat("[]() -> foo<!5> { return {}; };");
21225   verifyFormat("[]() -> foo<~5> { 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 == 2> { return {}; };");
21231   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
21232   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
21233   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
21234   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
21235   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
21236   verifyFormat("namespace bar {\n"
21237                "// broken:\n"
21238                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
21239                "} // namespace bar");
21240   verifyFormat("namespace bar {\n"
21241                "// broken:\n"
21242                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
21243                "} // namespace bar");
21244   verifyFormat("namespace bar {\n"
21245                "// broken:\n"
21246                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
21247                "} // namespace bar");
21248   verifyFormat("namespace bar {\n"
21249                "// broken:\n"
21250                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
21251                "} // namespace bar");
21252   verifyFormat("namespace bar {\n"
21253                "// broken:\n"
21254                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
21255                "} // namespace bar");
21256   verifyFormat("namespace bar {\n"
21257                "// broken:\n"
21258                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
21259                "} // namespace bar");
21260   verifyFormat("namespace bar {\n"
21261                "// broken:\n"
21262                "auto foo{[]() -> foo<!5> { return {}; }};\n"
21263                "} // namespace bar");
21264   verifyFormat("namespace bar {\n"
21265                "// broken:\n"
21266                "auto foo{[]() -> foo<~5> { return {}; }};\n"
21267                "} // namespace bar");
21268   verifyFormat("namespace bar {\n"
21269                "// broken:\n"
21270                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
21271                "} // namespace bar");
21272   verifyFormat("namespace bar {\n"
21273                "// broken:\n"
21274                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
21275                "} // namespace bar");
21276   verifyFormat("namespace bar {\n"
21277                "// broken:\n"
21278                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
21279                "} // namespace bar");
21280   verifyFormat("namespace bar {\n"
21281                "// broken:\n"
21282                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
21283                "} // namespace bar");
21284   verifyFormat("namespace bar {\n"
21285                "// broken:\n"
21286                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
21287                "} // namespace bar");
21288   verifyFormat("namespace bar {\n"
21289                "// broken:\n"
21290                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
21291                "} // namespace bar");
21292   verifyFormat("namespace bar {\n"
21293                "// broken:\n"
21294                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
21295                "} // namespace bar");
21296   verifyFormat("namespace bar {\n"
21297                "// broken:\n"
21298                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
21299                "} // namespace bar");
21300   verifyFormat("namespace bar {\n"
21301                "// broken:\n"
21302                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
21303                "} // namespace bar");
21304   verifyFormat("namespace bar {\n"
21305                "// broken:\n"
21306                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21307                "} // namespace bar");
21308   verifyFormat("[]() -> a<1> {};");
21309   verifyFormat("[]() -> a<1> { ; };");
21310   verifyFormat("[]() -> a<1> { ; }();");
21311   verifyFormat("[a, a]() -> a<true> {};");
21312   verifyFormat("[]() -> a<true> {};");
21313   verifyFormat("[]() -> a<true> { ; };");
21314   verifyFormat("[]() -> a<true> { ; }();");
21315   verifyFormat("[a, a]() -> a<false> {};");
21316   verifyFormat("[]() -> a<false> {};");
21317   verifyFormat("[]() -> a<false> { ; };");
21318   verifyFormat("[]() -> a<false> { ; }();");
21319   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21320   verifyFormat("namespace bar {\n"
21321                "auto foo{[]() -> foo<false> { ; }};\n"
21322                "} // namespace bar");
21323   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21324                "                   int j) -> int {\n"
21325                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21326                "};");
21327   verifyFormat(
21328       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21329       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21330       "      return aaaaaaaaaaaaaaaaa;\n"
21331       "    });",
21332       getLLVMStyleWithColumns(70));
21333   verifyFormat("[]() //\n"
21334                "    -> int {\n"
21335                "  return 1; //\n"
21336                "};");
21337   verifyFormat("[]() -> Void<T...> {};");
21338   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21339   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21340   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21341   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21342   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21343   verifyFormat("return int{[x = x]() { return x; }()};");
21344 
21345   // Lambdas with explicit template argument lists.
21346   verifyFormat(
21347       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21348   verifyFormat("auto L = []<class T>(T) {\n"
21349                "  {\n"
21350                "    f();\n"
21351                "    g();\n"
21352                "  }\n"
21353                "};\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 = []<typename... T>(T...) {\n"
21361                "  {\n"
21362                "    f();\n"
21363                "    g();\n"
21364                "  }\n"
21365                "};\n");
21366   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21367                "  {\n"
21368                "    f();\n"
21369                "    g();\n"
21370                "  }\n"
21371                "};\n");
21372   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21373                "  {\n"
21374                "    f();\n"
21375                "    g();\n"
21376                "  }\n"
21377                "};\n");
21378 
21379   // Multiple lambdas in the same parentheses change indentation rules. These
21380   // lambdas are forced to start on new lines.
21381   verifyFormat("SomeFunction(\n"
21382                "    []() {\n"
21383                "      //\n"
21384                "    },\n"
21385                "    []() {\n"
21386                "      //\n"
21387                "    });");
21388 
21389   // A lambda passed as arg0 is always pushed to the next line.
21390   verifyFormat("SomeFunction(\n"
21391                "    [this] {\n"
21392                "      //\n"
21393                "    },\n"
21394                "    1);\n");
21395 
21396   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21397   // the arg0 case above.
21398   auto Style = getGoogleStyle();
21399   Style.BinPackArguments = false;
21400   verifyFormat("SomeFunction(\n"
21401                "    a,\n"
21402                "    [this] {\n"
21403                "      //\n"
21404                "    },\n"
21405                "    b);\n",
21406                Style);
21407   verifyFormat("SomeFunction(\n"
21408                "    a,\n"
21409                "    [this] {\n"
21410                "      //\n"
21411                "    },\n"
21412                "    b);\n");
21413 
21414   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21415   // the BinPackArguments value (as long as the code is wide enough).
21416   verifyFormat(
21417       "something->SomeFunction(\n"
21418       "    a,\n"
21419       "    [this] {\n"
21420       "      "
21421       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21422       "    },\n"
21423       "    b);\n");
21424 
21425   // A multi-line lambda is pulled up as long as the introducer fits on the
21426   // previous line and there are no further args.
21427   verifyFormat("function(1, [this, that] {\n"
21428                "  //\n"
21429                "});\n");
21430   verifyFormat("function([this, that] {\n"
21431                "  //\n"
21432                "});\n");
21433   // FIXME: this format is not ideal and we should consider forcing the first
21434   // arg onto its own line.
21435   verifyFormat("function(a, b, c, //\n"
21436                "         d, [this, that] {\n"
21437                "           //\n"
21438                "         });\n");
21439 
21440   // Multiple lambdas are treated correctly even when there is a short arg0.
21441   verifyFormat("SomeFunction(\n"
21442                "    1,\n"
21443                "    [this] {\n"
21444                "      //\n"
21445                "    },\n"
21446                "    [this] {\n"
21447                "      //\n"
21448                "    },\n"
21449                "    1);\n");
21450 
21451   // More complex introducers.
21452   verifyFormat("return [i, args...] {};");
21453 
21454   // Not lambdas.
21455   verifyFormat("constexpr char hello[]{\"hello\"};");
21456   verifyFormat("double &operator[](int i) { return 0; }\n"
21457                "int i;");
21458   verifyFormat("std::unique_ptr<int[]> foo() {}");
21459   verifyFormat("int i = a[a][a]->f();");
21460   verifyFormat("int i = (*b)[a]->f();");
21461 
21462   // Other corner cases.
21463   verifyFormat("void f() {\n"
21464                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21465                "  );\n"
21466                "}");
21467 
21468   // Lambdas created through weird macros.
21469   verifyFormat("void f() {\n"
21470                "  MACRO((const AA &a) { return 1; });\n"
21471                "  MACRO((AA &a) { return 1; });\n"
21472                "}");
21473 
21474   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21475                "      doo_dah();\n"
21476                "      doo_dah();\n"
21477                "    })) {\n"
21478                "}");
21479   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21480                "                doo_dah();\n"
21481                "                doo_dah();\n"
21482                "              })) {\n"
21483                "}");
21484   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21485                "                doo_dah();\n"
21486                "                doo_dah();\n"
21487                "              })) {\n"
21488                "}");
21489   verifyFormat("auto lambda = []() {\n"
21490                "  int a = 2\n"
21491                "#if A\n"
21492                "          + 2\n"
21493                "#endif\n"
21494                "      ;\n"
21495                "};");
21496 
21497   // Lambdas with complex multiline introducers.
21498   verifyFormat(
21499       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21500       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21501       "        -> ::std::unordered_set<\n"
21502       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21503       "      //\n"
21504       "    });");
21505 
21506   FormatStyle DoNotMerge = getLLVMStyle();
21507   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21508   verifyFormat("auto c = []() {\n"
21509                "  return b;\n"
21510                "};",
21511                "auto c = []() { return b; };", DoNotMerge);
21512   verifyFormat("auto c = []() {\n"
21513                "};",
21514                " auto c = []() {};", DoNotMerge);
21515 
21516   FormatStyle MergeEmptyOnly = getLLVMStyle();
21517   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21518   verifyFormat("auto c = []() {\n"
21519                "  return b;\n"
21520                "};",
21521                "auto c = []() {\n"
21522                "  return b;\n"
21523                " };",
21524                MergeEmptyOnly);
21525   verifyFormat("auto c = []() {};",
21526                "auto c = []() {\n"
21527                "};",
21528                MergeEmptyOnly);
21529 
21530   FormatStyle MergeInline = getLLVMStyle();
21531   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21532   verifyFormat("auto c = []() {\n"
21533                "  return b;\n"
21534                "};",
21535                "auto c = []() { return b; };", MergeInline);
21536   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21537                MergeInline);
21538   verifyFormat("function([]() { return b; }, a)",
21539                "function([]() { return b; }, a)", MergeInline);
21540   verifyFormat("function(a, []() { return b; })",
21541                "function(a, []() { return b; })", MergeInline);
21542 
21543   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21544   // AllowShortLambdasOnASingleLine
21545   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21546   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21547   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21548   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21549       FormatStyle::ShortLambdaStyle::SLS_None;
21550   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21551                "    []()\n"
21552                "    {\n"
21553                "      return 17;\n"
21554                "    });",
21555                LLVMWithBeforeLambdaBody);
21556   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21557                "    []()\n"
21558                "    {\n"
21559                "    });",
21560                LLVMWithBeforeLambdaBody);
21561   verifyFormat("auto fct_SLS_None = []()\n"
21562                "{\n"
21563                "  return 17;\n"
21564                "};",
21565                LLVMWithBeforeLambdaBody);
21566   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21567                "    []()\n"
21568                "    {\n"
21569                "      return Call(\n"
21570                "          []()\n"
21571                "          {\n"
21572                "            return 17;\n"
21573                "          });\n"
21574                "    });",
21575                LLVMWithBeforeLambdaBody);
21576   verifyFormat("void Fct() {\n"
21577                "  return {[]()\n"
21578                "          {\n"
21579                "            return 17;\n"
21580                "          }};\n"
21581                "}",
21582                LLVMWithBeforeLambdaBody);
21583 
21584   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21585       FormatStyle::ShortLambdaStyle::SLS_Empty;
21586   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21587                "    []()\n"
21588                "    {\n"
21589                "      return 17;\n"
21590                "    });",
21591                LLVMWithBeforeLambdaBody);
21592   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21593                LLVMWithBeforeLambdaBody);
21594   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21595                "ongFunctionName_SLS_Empty(\n"
21596                "    []() {});",
21597                LLVMWithBeforeLambdaBody);
21598   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21599                "                                []()\n"
21600                "                                {\n"
21601                "                                  return 17;\n"
21602                "                                });",
21603                LLVMWithBeforeLambdaBody);
21604   verifyFormat("auto fct_SLS_Empty = []()\n"
21605                "{\n"
21606                "  return 17;\n"
21607                "};",
21608                LLVMWithBeforeLambdaBody);
21609   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21610                "    []()\n"
21611                "    {\n"
21612                "      return Call([]() {});\n"
21613                "    });",
21614                LLVMWithBeforeLambdaBody);
21615   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21616                "                           []()\n"
21617                "                           {\n"
21618                "                             return Call([]() {});\n"
21619                "                           });",
21620                LLVMWithBeforeLambdaBody);
21621   verifyFormat(
21622       "FctWithLongLineInLambda_SLS_Empty(\n"
21623       "    []()\n"
21624       "    {\n"
21625       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21626       "                               AndShouldNotBeConsiderAsInline,\n"
21627       "                               LambdaBodyMustBeBreak);\n"
21628       "    });",
21629       LLVMWithBeforeLambdaBody);
21630 
21631   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21632       FormatStyle::ShortLambdaStyle::SLS_Inline;
21633   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21634                LLVMWithBeforeLambdaBody);
21635   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21636                LLVMWithBeforeLambdaBody);
21637   verifyFormat("auto fct_SLS_Inline = []()\n"
21638                "{\n"
21639                "  return 17;\n"
21640                "};",
21641                LLVMWithBeforeLambdaBody);
21642   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21643                "17; }); });",
21644                LLVMWithBeforeLambdaBody);
21645   verifyFormat(
21646       "FctWithLongLineInLambda_SLS_Inline(\n"
21647       "    []()\n"
21648       "    {\n"
21649       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21650       "                               AndShouldNotBeConsiderAsInline,\n"
21651       "                               LambdaBodyMustBeBreak);\n"
21652       "    });",
21653       LLVMWithBeforeLambdaBody);
21654   verifyFormat("FctWithMultipleParams_SLS_Inline("
21655                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21656                "                                 []() { return 17; });",
21657                LLVMWithBeforeLambdaBody);
21658   verifyFormat(
21659       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21660       LLVMWithBeforeLambdaBody);
21661 
21662   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21663       FormatStyle::ShortLambdaStyle::SLS_All;
21664   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21665                LLVMWithBeforeLambdaBody);
21666   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21667                LLVMWithBeforeLambdaBody);
21668   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21669                LLVMWithBeforeLambdaBody);
21670   verifyFormat("FctWithOneParam_SLS_All(\n"
21671                "    []()\n"
21672                "    {\n"
21673                "      // A cool function...\n"
21674                "      return 43;\n"
21675                "    });",
21676                LLVMWithBeforeLambdaBody);
21677   verifyFormat("FctWithMultipleParams_SLS_All("
21678                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21679                "                              []() { return 17; });",
21680                LLVMWithBeforeLambdaBody);
21681   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21682                LLVMWithBeforeLambdaBody);
21683   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21684                LLVMWithBeforeLambdaBody);
21685   verifyFormat(
21686       "FctWithLongLineInLambda_SLS_All(\n"
21687       "    []()\n"
21688       "    {\n"
21689       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21690       "                               AndShouldNotBeConsiderAsInline,\n"
21691       "                               LambdaBodyMustBeBreak);\n"
21692       "    });",
21693       LLVMWithBeforeLambdaBody);
21694   verifyFormat(
21695       "auto fct_SLS_All = []()\n"
21696       "{\n"
21697       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21698       "                           AndShouldNotBeConsiderAsInline,\n"
21699       "                           LambdaBodyMustBeBreak);\n"
21700       "};",
21701       LLVMWithBeforeLambdaBody);
21702   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21703   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21704                LLVMWithBeforeLambdaBody);
21705   verifyFormat(
21706       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21707       "                                FirstParam,\n"
21708       "                                SecondParam,\n"
21709       "                                ThirdParam,\n"
21710       "                                FourthParam);",
21711       LLVMWithBeforeLambdaBody);
21712   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21713                "    []() { return "
21714                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21715                "    FirstParam,\n"
21716                "    SecondParam,\n"
21717                "    ThirdParam,\n"
21718                "    FourthParam);",
21719                LLVMWithBeforeLambdaBody);
21720   verifyFormat(
21721       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21722       "                                SecondParam,\n"
21723       "                                ThirdParam,\n"
21724       "                                FourthParam,\n"
21725       "                                []() { return SomeValueNotSoLong; });",
21726       LLVMWithBeforeLambdaBody);
21727   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21728                "    []()\n"
21729                "    {\n"
21730                "      return "
21731                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21732                "eConsiderAsInline;\n"
21733                "    });",
21734                LLVMWithBeforeLambdaBody);
21735   verifyFormat(
21736       "FctWithLongLineInLambda_SLS_All(\n"
21737       "    []()\n"
21738       "    {\n"
21739       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21740       "                               AndShouldNotBeConsiderAsInline,\n"
21741       "                               LambdaBodyMustBeBreak);\n"
21742       "    });",
21743       LLVMWithBeforeLambdaBody);
21744   verifyFormat("FctWithTwoParams_SLS_All(\n"
21745                "    []()\n"
21746                "    {\n"
21747                "      // A cool function...\n"
21748                "      return 43;\n"
21749                "    },\n"
21750                "    87);",
21751                LLVMWithBeforeLambdaBody);
21752   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
21753                LLVMWithBeforeLambdaBody);
21754   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
21755                LLVMWithBeforeLambdaBody);
21756   verifyFormat(
21757       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
21758       LLVMWithBeforeLambdaBody);
21759   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
21760                "}); }, x);",
21761                LLVMWithBeforeLambdaBody);
21762   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21763                "    []()\n"
21764                "    {\n"
21765                "      // A cool function...\n"
21766                "      return Call([]() { return 17; });\n"
21767                "    });",
21768                LLVMWithBeforeLambdaBody);
21769   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21770                "    []()\n"
21771                "    {\n"
21772                "      return Call(\n"
21773                "          []()\n"
21774                "          {\n"
21775                "            // A cool function...\n"
21776                "            return 17;\n"
21777                "          });\n"
21778                "    });",
21779                LLVMWithBeforeLambdaBody);
21780 
21781   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21782       FormatStyle::ShortLambdaStyle::SLS_None;
21783 
21784   verifyFormat("auto select = [this]() -> const Library::Object *\n"
21785                "{\n"
21786                "  return MyAssignment::SelectFromList(this);\n"
21787                "};\n",
21788                LLVMWithBeforeLambdaBody);
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]() -> std::unique_ptr<Object>\n"
21797                "{\n"
21798                "  return MyAssignment::SelectFromList(this);\n"
21799                "};\n",
21800                LLVMWithBeforeLambdaBody);
21801 
21802   verifyFormat("namespace test {\n"
21803                "class Test {\n"
21804                "public:\n"
21805                "  Test() = default;\n"
21806                "};\n"
21807                "} // namespace test",
21808                LLVMWithBeforeLambdaBody);
21809 
21810   // Lambdas with different indentation styles.
21811   Style = getLLVMStyleWithColumns(100);
21812   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21813             "  return promise.then(\n"
21814             "      [this, &someVariable, someObject = "
21815             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21816             "        return someObject.startAsyncAction().then(\n"
21817             "            [this, &someVariable](AsyncActionResult result) "
21818             "mutable { result.processMore(); });\n"
21819             "      });\n"
21820             "}\n",
21821             format("SomeResult doSomething(SomeObject promise) {\n"
21822                    "  return promise.then([this, &someVariable, someObject = "
21823                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21824                    "    return someObject.startAsyncAction().then([this, "
21825                    "&someVariable](AsyncActionResult result) mutable {\n"
21826                    "      result.processMore();\n"
21827                    "    });\n"
21828                    "  });\n"
21829                    "}\n",
21830                    Style));
21831   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21832   verifyFormat("test() {\n"
21833                "  ([]() -> {\n"
21834                "    int b = 32;\n"
21835                "    return 3;\n"
21836                "  }).foo();\n"
21837                "}",
21838                Style);
21839   verifyFormat("test() {\n"
21840                "  []() -> {\n"
21841                "    int b = 32;\n"
21842                "    return 3;\n"
21843                "  }\n"
21844                "}",
21845                Style);
21846   verifyFormat("std::sort(v.begin(), v.end(),\n"
21847                "          [](const auto &someLongArgumentName, const auto "
21848                "&someOtherLongArgumentName) {\n"
21849                "  return someLongArgumentName.someMemberVariable < "
21850                "someOtherLongArgumentName.someMemberVariable;\n"
21851                "});",
21852                Style);
21853   verifyFormat("test() {\n"
21854                "  (\n"
21855                "      []() -> {\n"
21856                "        int b = 32;\n"
21857                "        return 3;\n"
21858                "      },\n"
21859                "      foo, bar)\n"
21860                "      .foo();\n"
21861                "}",
21862                Style);
21863   verifyFormat("test() {\n"
21864                "  ([]() -> {\n"
21865                "    int b = 32;\n"
21866                "    return 3;\n"
21867                "  })\n"
21868                "      .foo()\n"
21869                "      .bar();\n"
21870                "}",
21871                Style);
21872   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21873             "  return promise.then(\n"
21874             "      [this, &someVariable, someObject = "
21875             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21876             "    return someObject.startAsyncAction().then(\n"
21877             "        [this, &someVariable](AsyncActionResult result) mutable { "
21878             "result.processMore(); });\n"
21879             "  });\n"
21880             "}\n",
21881             format("SomeResult doSomething(SomeObject promise) {\n"
21882                    "  return promise.then([this, &someVariable, someObject = "
21883                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21884                    "    return someObject.startAsyncAction().then([this, "
21885                    "&someVariable](AsyncActionResult result) mutable {\n"
21886                    "      result.processMore();\n"
21887                    "    });\n"
21888                    "  });\n"
21889                    "}\n",
21890                    Style));
21891   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21892             "  return promise.then([this, &someVariable] {\n"
21893             "    return someObject.startAsyncAction().then(\n"
21894             "        [this, &someVariable](AsyncActionResult result) mutable { "
21895             "result.processMore(); });\n"
21896             "  });\n"
21897             "}\n",
21898             format("SomeResult doSomething(SomeObject promise) {\n"
21899                    "  return promise.then([this, &someVariable] {\n"
21900                    "    return someObject.startAsyncAction().then([this, "
21901                    "&someVariable](AsyncActionResult result) mutable {\n"
21902                    "      result.processMore();\n"
21903                    "    });\n"
21904                    "  });\n"
21905                    "}\n",
21906                    Style));
21907   Style = getGoogleStyle();
21908   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21909   EXPECT_EQ("#define A                                       \\\n"
21910             "  [] {                                          \\\n"
21911             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
21912             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
21913             "      }",
21914             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
21915                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
21916                    Style));
21917   // TODO: The current formatting has a minor issue that's not worth fixing
21918   // right now whereby the closing brace is indented relative to the signature
21919   // instead of being aligned. This only happens with macros.
21920 }
21921 
21922 TEST_F(FormatTest, LambdaWithLineComments) {
21923   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21924   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21925   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21926   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21927       FormatStyle::ShortLambdaStyle::SLS_All;
21928 
21929   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
21930   verifyFormat("auto k = []() // comment\n"
21931                "{ return; }",
21932                LLVMWithBeforeLambdaBody);
21933   verifyFormat("auto k = []() /* comment */ { return; }",
21934                LLVMWithBeforeLambdaBody);
21935   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
21936                LLVMWithBeforeLambdaBody);
21937   verifyFormat("auto k = []() // X\n"
21938                "{ return; }",
21939                LLVMWithBeforeLambdaBody);
21940   verifyFormat(
21941       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
21942       "{ return; }",
21943       LLVMWithBeforeLambdaBody);
21944 
21945   LLVMWithBeforeLambdaBody.ColumnLimit = 0;
21946 
21947   verifyFormat("foo([]()\n"
21948                "    {\n"
21949                "      bar();    //\n"
21950                "      return 1; // comment\n"
21951                "    }());",
21952                "foo([]() {\n"
21953                "  bar(); //\n"
21954                "  return 1; // comment\n"
21955                "}());",
21956                LLVMWithBeforeLambdaBody);
21957   verifyFormat("foo(\n"
21958                "    1, MACRO {\n"
21959                "      baz();\n"
21960                "      bar(); // comment\n"
21961                "    },\n"
21962                "    []() {});",
21963                "foo(\n"
21964                "  1, MACRO { baz(); bar(); // comment\n"
21965                "  }, []() {}\n"
21966                ");",
21967                LLVMWithBeforeLambdaBody);
21968 }
21969 
21970 TEST_F(FormatTest, EmptyLinesInLambdas) {
21971   verifyFormat("auto lambda = []() {\n"
21972                "  x(); //\n"
21973                "};",
21974                "auto lambda = []() {\n"
21975                "\n"
21976                "  x(); //\n"
21977                "\n"
21978                "};");
21979 }
21980 
21981 TEST_F(FormatTest, FormatsBlocks) {
21982   FormatStyle ShortBlocks = getLLVMStyle();
21983   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21984   verifyFormat("int (^Block)(int, int);", ShortBlocks);
21985   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
21986   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
21987   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
21988   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
21989   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
21990 
21991   verifyFormat("foo(^{ bar(); });", ShortBlocks);
21992   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
21993   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
21994 
21995   verifyFormat("[operation setCompletionBlock:^{\n"
21996                "  [self onOperationDone];\n"
21997                "}];");
21998   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
21999                "  [self onOperationDone];\n"
22000                "}]};");
22001   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
22002                "  f();\n"
22003                "}];");
22004   verifyFormat("int a = [operation block:^int(int *i) {\n"
22005                "  return 1;\n"
22006                "}];");
22007   verifyFormat("[myObject doSomethingWith:arg1\n"
22008                "                      aaa:^int(int *a) {\n"
22009                "                        return 1;\n"
22010                "                      }\n"
22011                "                      bbb:f(a * bbbbbbbb)];");
22012 
22013   verifyFormat("[operation setCompletionBlock:^{\n"
22014                "  [self.delegate newDataAvailable];\n"
22015                "}];",
22016                getLLVMStyleWithColumns(60));
22017   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
22018                "  NSString *path = [self sessionFilePath];\n"
22019                "  if (path) {\n"
22020                "    // ...\n"
22021                "  }\n"
22022                "});");
22023   verifyFormat("[[SessionService sharedService]\n"
22024                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22025                "      if (window) {\n"
22026                "        [self windowDidLoad:window];\n"
22027                "      } else {\n"
22028                "        [self errorLoadingWindow];\n"
22029                "      }\n"
22030                "    }];");
22031   verifyFormat("void (^largeBlock)(void) = ^{\n"
22032                "  // ...\n"
22033                "};\n",
22034                getLLVMStyleWithColumns(40));
22035   verifyFormat("[[SessionService sharedService]\n"
22036                "    loadWindowWithCompletionBlock: //\n"
22037                "        ^(SessionWindow *window) {\n"
22038                "          if (window) {\n"
22039                "            [self windowDidLoad:window];\n"
22040                "          } else {\n"
22041                "            [self errorLoadingWindow];\n"
22042                "          }\n"
22043                "        }];",
22044                getLLVMStyleWithColumns(60));
22045   verifyFormat("[myObject doSomethingWith:arg1\n"
22046                "    firstBlock:^(Foo *a) {\n"
22047                "      // ...\n"
22048                "      int i;\n"
22049                "    }\n"
22050                "    secondBlock:^(Bar *b) {\n"
22051                "      // ...\n"
22052                "      int i;\n"
22053                "    }\n"
22054                "    thirdBlock:^Foo(Bar *b) {\n"
22055                "      // ...\n"
22056                "      int i;\n"
22057                "    }];");
22058   verifyFormat("[myObject doSomethingWith:arg1\n"
22059                "               firstBlock:-1\n"
22060                "              secondBlock:^(Bar *b) {\n"
22061                "                // ...\n"
22062                "                int i;\n"
22063                "              }];");
22064 
22065   verifyFormat("f(^{\n"
22066                "  @autoreleasepool {\n"
22067                "    if (a) {\n"
22068                "      g();\n"
22069                "    }\n"
22070                "  }\n"
22071                "});");
22072   verifyFormat("Block b = ^int *(A *a, B *b) {}");
22073   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
22074                "};");
22075 
22076   FormatStyle FourIndent = getLLVMStyle();
22077   FourIndent.ObjCBlockIndentWidth = 4;
22078   verifyFormat("[operation setCompletionBlock:^{\n"
22079                "    [self onOperationDone];\n"
22080                "}];",
22081                FourIndent);
22082 }
22083 
22084 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
22085   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
22086 
22087   verifyFormat("[[SessionService sharedService] "
22088                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22089                "  if (window) {\n"
22090                "    [self windowDidLoad:window];\n"
22091                "  } else {\n"
22092                "    [self errorLoadingWindow];\n"
22093                "  }\n"
22094                "}];",
22095                ZeroColumn);
22096   EXPECT_EQ("[[SessionService sharedService]\n"
22097             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22098             "      if (window) {\n"
22099             "        [self windowDidLoad:window];\n"
22100             "      } else {\n"
22101             "        [self errorLoadingWindow];\n"
22102             "      }\n"
22103             "    }];",
22104             format("[[SessionService sharedService]\n"
22105                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22106                    "                if (window) {\n"
22107                    "    [self windowDidLoad:window];\n"
22108                    "  } else {\n"
22109                    "    [self errorLoadingWindow];\n"
22110                    "  }\n"
22111                    "}];",
22112                    ZeroColumn));
22113   verifyFormat("[myObject doSomethingWith:arg1\n"
22114                "    firstBlock:^(Foo *a) {\n"
22115                "      // ...\n"
22116                "      int i;\n"
22117                "    }\n"
22118                "    secondBlock:^(Bar *b) {\n"
22119                "      // ...\n"
22120                "      int i;\n"
22121                "    }\n"
22122                "    thirdBlock:^Foo(Bar *b) {\n"
22123                "      // ...\n"
22124                "      int i;\n"
22125                "    }];",
22126                ZeroColumn);
22127   verifyFormat("f(^{\n"
22128                "  @autoreleasepool {\n"
22129                "    if (a) {\n"
22130                "      g();\n"
22131                "    }\n"
22132                "  }\n"
22133                "});",
22134                ZeroColumn);
22135   verifyFormat("void (^largeBlock)(void) = ^{\n"
22136                "  // ...\n"
22137                "};",
22138                ZeroColumn);
22139 
22140   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22141   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
22142             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22143   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22144   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
22145             "  int i;\n"
22146             "};",
22147             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22148 }
22149 
22150 TEST_F(FormatTest, SupportsCRLF) {
22151   EXPECT_EQ("int a;\r\n"
22152             "int b;\r\n"
22153             "int c;\r\n",
22154             format("int a;\r\n"
22155                    "  int b;\r\n"
22156                    "    int c;\r\n",
22157                    getLLVMStyle()));
22158   EXPECT_EQ("int a;\r\n"
22159             "int b;\r\n"
22160             "int c;\r\n",
22161             format("int a;\r\n"
22162                    "  int b;\n"
22163                    "    int c;\r\n",
22164                    getLLVMStyle()));
22165   EXPECT_EQ("int a;\n"
22166             "int b;\n"
22167             "int c;\n",
22168             format("int a;\r\n"
22169                    "  int b;\n"
22170                    "    int c;\n",
22171                    getLLVMStyle()));
22172   EXPECT_EQ("\"aaaaaaa \"\r\n"
22173             "\"bbbbbbb\";\r\n",
22174             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
22175   EXPECT_EQ("#define A \\\r\n"
22176             "  b;      \\\r\n"
22177             "  c;      \\\r\n"
22178             "  d;\r\n",
22179             format("#define A \\\r\n"
22180                    "  b; \\\r\n"
22181                    "  c; d; \r\n",
22182                    getGoogleStyle()));
22183 
22184   EXPECT_EQ("/*\r\n"
22185             "multi line block comments\r\n"
22186             "should not introduce\r\n"
22187             "an extra carriage return\r\n"
22188             "*/\r\n",
22189             format("/*\r\n"
22190                    "multi line block comments\r\n"
22191                    "should not introduce\r\n"
22192                    "an extra carriage return\r\n"
22193                    "*/\r\n"));
22194   EXPECT_EQ("/*\r\n"
22195             "\r\n"
22196             "*/",
22197             format("/*\r\n"
22198                    "    \r\r\r\n"
22199                    "*/"));
22200 
22201   FormatStyle style = getLLVMStyle();
22202 
22203   style.DeriveLineEnding = true;
22204   style.UseCRLF = false;
22205   EXPECT_EQ("union FooBarBazQux {\n"
22206             "  int foo;\n"
22207             "  int bar;\n"
22208             "  int baz;\n"
22209             "};",
22210             format("union FooBarBazQux {\r\n"
22211                    "  int foo;\n"
22212                    "  int bar;\r\n"
22213                    "  int baz;\n"
22214                    "};",
22215                    style));
22216   style.UseCRLF = true;
22217   EXPECT_EQ("union FooBarBazQux {\r\n"
22218             "  int foo;\r\n"
22219             "  int bar;\r\n"
22220             "  int baz;\r\n"
22221             "};",
22222             format("union FooBarBazQux {\r\n"
22223                    "  int foo;\n"
22224                    "  int bar;\r\n"
22225                    "  int baz;\n"
22226                    "};",
22227                    style));
22228 
22229   style.DeriveLineEnding = false;
22230   style.UseCRLF = false;
22231   EXPECT_EQ("union FooBarBazQux {\n"
22232             "  int foo;\n"
22233             "  int bar;\n"
22234             "  int baz;\n"
22235             "  int qux;\n"
22236             "};",
22237             format("union FooBarBazQux {\r\n"
22238                    "  int foo;\n"
22239                    "  int bar;\r\n"
22240                    "  int baz;\n"
22241                    "  int qux;\r\n"
22242                    "};",
22243                    style));
22244   style.UseCRLF = true;
22245   EXPECT_EQ("union FooBarBazQux {\r\n"
22246             "  int foo;\r\n"
22247             "  int bar;\r\n"
22248             "  int baz;\r\n"
22249             "  int qux;\r\n"
22250             "};",
22251             format("union FooBarBazQux {\r\n"
22252                    "  int foo;\n"
22253                    "  int bar;\r\n"
22254                    "  int baz;\n"
22255                    "  int qux;\n"
22256                    "};",
22257                    style));
22258 
22259   style.DeriveLineEnding = true;
22260   style.UseCRLF = false;
22261   EXPECT_EQ("union FooBarBazQux {\r\n"
22262             "  int foo;\r\n"
22263             "  int bar;\r\n"
22264             "  int baz;\r\n"
22265             "  int qux;\r\n"
22266             "};",
22267             format("union FooBarBazQux {\r\n"
22268                    "  int foo;\n"
22269                    "  int bar;\r\n"
22270                    "  int baz;\n"
22271                    "  int qux;\r\n"
22272                    "};",
22273                    style));
22274   style.UseCRLF = true;
22275   EXPECT_EQ("union FooBarBazQux {\n"
22276             "  int foo;\n"
22277             "  int bar;\n"
22278             "  int baz;\n"
22279             "  int qux;\n"
22280             "};",
22281             format("union FooBarBazQux {\r\n"
22282                    "  int foo;\n"
22283                    "  int bar;\r\n"
22284                    "  int baz;\n"
22285                    "  int qux;\n"
22286                    "};",
22287                    style));
22288 }
22289 
22290 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
22291   verifyFormat("MY_CLASS(C) {\n"
22292                "  int i;\n"
22293                "  int j;\n"
22294                "};");
22295 }
22296 
22297 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
22298   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
22299   TwoIndent.ContinuationIndentWidth = 2;
22300 
22301   EXPECT_EQ("int i =\n"
22302             "  longFunction(\n"
22303             "    arg);",
22304             format("int i = longFunction(arg);", TwoIndent));
22305 
22306   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
22307   SixIndent.ContinuationIndentWidth = 6;
22308 
22309   EXPECT_EQ("int i =\n"
22310             "      longFunction(\n"
22311             "            arg);",
22312             format("int i = longFunction(arg);", SixIndent));
22313 }
22314 
22315 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
22316   FormatStyle Style = getLLVMStyle();
22317   verifyFormat("int Foo::getter(\n"
22318                "    //\n"
22319                ") const {\n"
22320                "  return foo;\n"
22321                "}",
22322                Style);
22323   verifyFormat("void Foo::setter(\n"
22324                "    //\n"
22325                ") {\n"
22326                "  foo = 1;\n"
22327                "}",
22328                Style);
22329 }
22330 
22331 TEST_F(FormatTest, SpacesInAngles) {
22332   FormatStyle Spaces = getLLVMStyle();
22333   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22334 
22335   verifyFormat("vector< ::std::string > x1;", Spaces);
22336   verifyFormat("Foo< int, Bar > x2;", Spaces);
22337   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22338 
22339   verifyFormat("static_cast< int >(arg);", Spaces);
22340   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22341   verifyFormat("f< int, float >();", Spaces);
22342   verifyFormat("template <> g() {}", Spaces);
22343   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22344   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22345   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22346                Spaces);
22347 
22348   Spaces.Standard = FormatStyle::LS_Cpp03;
22349   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22350   verifyFormat("A< A< int > >();", Spaces);
22351 
22352   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22353   verifyFormat("A<A<int> >();", Spaces);
22354 
22355   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22356   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22357                Spaces);
22358   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22359                Spaces);
22360 
22361   verifyFormat("A<A<int> >();", Spaces);
22362   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22363   verifyFormat("A< A< int > >();", Spaces);
22364 
22365   Spaces.Standard = FormatStyle::LS_Cpp11;
22366   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22367   verifyFormat("A< A< int > >();", Spaces);
22368 
22369   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22370   verifyFormat("vector<::std::string> x4;", Spaces);
22371   verifyFormat("vector<int> x5;", Spaces);
22372   verifyFormat("Foo<int, Bar> x6;", Spaces);
22373   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22374 
22375   verifyFormat("A<A<int>>();", Spaces);
22376 
22377   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22378   verifyFormat("vector<::std::string> x4;", Spaces);
22379   verifyFormat("vector< ::std::string > x4;", Spaces);
22380   verifyFormat("vector<int> x5;", Spaces);
22381   verifyFormat("vector< int > x5;", Spaces);
22382   verifyFormat("Foo<int, Bar> x6;", Spaces);
22383   verifyFormat("Foo< int, Bar > x6;", Spaces);
22384   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22385   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22386 
22387   verifyFormat("A<A<int>>();", Spaces);
22388   verifyFormat("A< A< int > >();", Spaces);
22389   verifyFormat("A<A<int > >();", Spaces);
22390   verifyFormat("A< A< int>>();", Spaces);
22391 
22392   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22393   verifyFormat("// clang-format off\n"
22394                "foo<<<1, 1>>>();\n"
22395                "// clang-format on\n",
22396                Spaces);
22397   verifyFormat("// clang-format off\n"
22398                "foo< < <1, 1> > >();\n"
22399                "// clang-format on\n",
22400                Spaces);
22401 }
22402 
22403 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22404   FormatStyle Style = getLLVMStyle();
22405   Style.SpaceAfterTemplateKeyword = false;
22406   verifyFormat("template<int> void foo();", Style);
22407 }
22408 
22409 TEST_F(FormatTest, TripleAngleBrackets) {
22410   verifyFormat("f<<<1, 1>>>();");
22411   verifyFormat("f<<<1, 1, 1, s>>>();");
22412   verifyFormat("f<<<a, b, c, d>>>();");
22413   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22414   verifyFormat("f<param><<<1, 1>>>();");
22415   verifyFormat("f<1><<<1, 1>>>();");
22416   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22417   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22418                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22419   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22420                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22421 }
22422 
22423 TEST_F(FormatTest, MergeLessLessAtEnd) {
22424   verifyFormat("<<");
22425   EXPECT_EQ("< < <", format("\\\n<<<"));
22426   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22427                "aaallvm::outs() <<");
22428   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22429                "aaaallvm::outs()\n    <<");
22430 }
22431 
22432 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22433   std::string code = "#if A\n"
22434                      "#if B\n"
22435                      "a.\n"
22436                      "#endif\n"
22437                      "    a = 1;\n"
22438                      "#else\n"
22439                      "#endif\n"
22440                      "#if C\n"
22441                      "#else\n"
22442                      "#endif\n";
22443   EXPECT_EQ(code, format(code));
22444 }
22445 
22446 TEST_F(FormatTest, HandleConflictMarkers) {
22447   // Git/SVN conflict markers.
22448   EXPECT_EQ("int a;\n"
22449             "void f() {\n"
22450             "  callme(some(parameter1,\n"
22451             "<<<<<<< text by the vcs\n"
22452             "              parameter2),\n"
22453             "||||||| text by the vcs\n"
22454             "              parameter2),\n"
22455             "         parameter3,\n"
22456             "======= text by the vcs\n"
22457             "              parameter2, parameter3),\n"
22458             ">>>>>>> text by the vcs\n"
22459             "         otherparameter);\n",
22460             format("int a;\n"
22461                    "void f() {\n"
22462                    "  callme(some(parameter1,\n"
22463                    "<<<<<<< text by the vcs\n"
22464                    "  parameter2),\n"
22465                    "||||||| text by the vcs\n"
22466                    "  parameter2),\n"
22467                    "  parameter3,\n"
22468                    "======= text by the vcs\n"
22469                    "  parameter2,\n"
22470                    "  parameter3),\n"
22471                    ">>>>>>> text by the vcs\n"
22472                    "  otherparameter);\n"));
22473 
22474   // Perforce markers.
22475   EXPECT_EQ("void f() {\n"
22476             "  function(\n"
22477             ">>>> text by the vcs\n"
22478             "      parameter,\n"
22479             "==== text by the vcs\n"
22480             "      parameter,\n"
22481             "==== text by the vcs\n"
22482             "      parameter,\n"
22483             "<<<< text by the vcs\n"
22484             "      parameter);\n",
22485             format("void f() {\n"
22486                    "  function(\n"
22487                    ">>>> text by the vcs\n"
22488                    "  parameter,\n"
22489                    "==== text by the vcs\n"
22490                    "  parameter,\n"
22491                    "==== text by the vcs\n"
22492                    "  parameter,\n"
22493                    "<<<< text by the vcs\n"
22494                    "  parameter);\n"));
22495 
22496   EXPECT_EQ("<<<<<<<\n"
22497             "|||||||\n"
22498             "=======\n"
22499             ">>>>>>>",
22500             format("<<<<<<<\n"
22501                    "|||||||\n"
22502                    "=======\n"
22503                    ">>>>>>>"));
22504 
22505   EXPECT_EQ("<<<<<<<\n"
22506             "|||||||\n"
22507             "int i;\n"
22508             "=======\n"
22509             ">>>>>>>",
22510             format("<<<<<<<\n"
22511                    "|||||||\n"
22512                    "int i;\n"
22513                    "=======\n"
22514                    ">>>>>>>"));
22515 
22516   // FIXME: Handle parsing of macros around conflict markers correctly:
22517   EXPECT_EQ("#define Macro \\\n"
22518             "<<<<<<<\n"
22519             "Something \\\n"
22520             "|||||||\n"
22521             "Else \\\n"
22522             "=======\n"
22523             "Other \\\n"
22524             ">>>>>>>\n"
22525             "    End int i;\n",
22526             format("#define Macro \\\n"
22527                    "<<<<<<<\n"
22528                    "  Something \\\n"
22529                    "|||||||\n"
22530                    "  Else \\\n"
22531                    "=======\n"
22532                    "  Other \\\n"
22533                    ">>>>>>>\n"
22534                    "  End\n"
22535                    "int i;\n"));
22536 
22537   verifyFormat(R"(====
22538 #ifdef A
22539 a
22540 #else
22541 b
22542 #endif
22543 )");
22544 }
22545 
22546 TEST_F(FormatTest, DisableRegions) {
22547   EXPECT_EQ("int i;\n"
22548             "// clang-format off\n"
22549             "  int j;\n"
22550             "// clang-format on\n"
22551             "int k;",
22552             format(" int  i;\n"
22553                    "   // clang-format off\n"
22554                    "  int j;\n"
22555                    " // clang-format on\n"
22556                    "   int   k;"));
22557   EXPECT_EQ("int i;\n"
22558             "/* clang-format off */\n"
22559             "  int j;\n"
22560             "/* clang-format on */\n"
22561             "int k;",
22562             format(" int  i;\n"
22563                    "   /* clang-format off */\n"
22564                    "  int j;\n"
22565                    " /* clang-format on */\n"
22566                    "   int   k;"));
22567 
22568   // Don't reflow comments within disabled regions.
22569   EXPECT_EQ("// clang-format off\n"
22570             "// long long long long long long line\n"
22571             "/* clang-format on */\n"
22572             "/* long long long\n"
22573             " * long long long\n"
22574             " * line */\n"
22575             "int i;\n"
22576             "/* clang-format off */\n"
22577             "/* long long long long long long line */\n",
22578             format("// clang-format off\n"
22579                    "// long long long long long long line\n"
22580                    "/* clang-format on */\n"
22581                    "/* long long long long long long line */\n"
22582                    "int i;\n"
22583                    "/* clang-format off */\n"
22584                    "/* long long long long long long line */\n",
22585                    getLLVMStyleWithColumns(20)));
22586 }
22587 
22588 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22589   format("? ) =");
22590   verifyNoCrash("#define a\\\n /**/}");
22591 }
22592 
22593 TEST_F(FormatTest, FormatsTableGenCode) {
22594   FormatStyle Style = getLLVMStyle();
22595   Style.Language = FormatStyle::LK_TableGen;
22596   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22597 }
22598 
22599 TEST_F(FormatTest, ArrayOfTemplates) {
22600   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22601             format("auto a = new unique_ptr<int > [ 10];"));
22602 
22603   FormatStyle Spaces = getLLVMStyle();
22604   Spaces.SpacesInSquareBrackets = true;
22605   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22606             format("auto a = new unique_ptr<int > [10];", Spaces));
22607 }
22608 
22609 TEST_F(FormatTest, ArrayAsTemplateType) {
22610   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22611             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22612 
22613   FormatStyle Spaces = getLLVMStyle();
22614   Spaces.SpacesInSquareBrackets = true;
22615   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22616             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22617 }
22618 
22619 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22620 
22621 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22622   llvm::vfs::InMemoryFileSystem FS;
22623   auto Style1 = getStyle("file", "", "Google", "", &FS);
22624   ASSERT_TRUE((bool)Style1);
22625   ASSERT_EQ(*Style1, getGoogleStyle());
22626 }
22627 
22628 TEST(FormatStyle, GetStyleOfFile) {
22629   llvm::vfs::InMemoryFileSystem FS;
22630   // Test 1: format file in the same directory.
22631   ASSERT_TRUE(
22632       FS.addFile("/a/.clang-format", 0,
22633                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22634   ASSERT_TRUE(
22635       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22636   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22637   ASSERT_TRUE((bool)Style1);
22638   ASSERT_EQ(*Style1, getLLVMStyle());
22639 
22640   // Test 2.1: fallback to default.
22641   ASSERT_TRUE(
22642       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22643   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22644   ASSERT_TRUE((bool)Style2);
22645   ASSERT_EQ(*Style2, getMozillaStyle());
22646 
22647   // Test 2.2: no format on 'none' fallback style.
22648   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22649   ASSERT_TRUE((bool)Style2);
22650   ASSERT_EQ(*Style2, getNoStyle());
22651 
22652   // Test 2.3: format if config is found with no based style while fallback is
22653   // 'none'.
22654   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22655                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22656   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22657   ASSERT_TRUE((bool)Style2);
22658   ASSERT_EQ(*Style2, getLLVMStyle());
22659 
22660   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22661   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22662   ASSERT_TRUE((bool)Style2);
22663   ASSERT_EQ(*Style2, getLLVMStyle());
22664 
22665   // Test 3: format file in parent directory.
22666   ASSERT_TRUE(
22667       FS.addFile("/c/.clang-format", 0,
22668                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22669   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22670                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22671   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22672   ASSERT_TRUE((bool)Style3);
22673   ASSERT_EQ(*Style3, getGoogleStyle());
22674 
22675   // Test 4: error on invalid fallback style
22676   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22677   ASSERT_FALSE((bool)Style4);
22678   llvm::consumeError(Style4.takeError());
22679 
22680   // Test 5: error on invalid yaml on command line
22681   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22682   ASSERT_FALSE((bool)Style5);
22683   llvm::consumeError(Style5.takeError());
22684 
22685   // Test 6: error on invalid style
22686   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22687   ASSERT_FALSE((bool)Style6);
22688   llvm::consumeError(Style6.takeError());
22689 
22690   // Test 7: found config file, error on parsing it
22691   ASSERT_TRUE(
22692       FS.addFile("/d/.clang-format", 0,
22693                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22694                                                   "InvalidKey: InvalidValue")));
22695   ASSERT_TRUE(
22696       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22697   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22698   ASSERT_FALSE((bool)Style7a);
22699   llvm::consumeError(Style7a.takeError());
22700 
22701   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22702   ASSERT_TRUE((bool)Style7b);
22703 
22704   // Test 8: inferred per-language defaults apply.
22705   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22706   ASSERT_TRUE((bool)StyleTd);
22707   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22708 
22709   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22710   // fallback style.
22711   ASSERT_TRUE(FS.addFile(
22712       "/e/sub/.clang-format", 0,
22713       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22714                                        "ColumnLimit: 20")));
22715   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22716                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22717   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22718   ASSERT_TRUE(static_cast<bool>(Style9));
22719   ASSERT_EQ(*Style9, [] {
22720     auto Style = getNoStyle();
22721     Style.ColumnLimit = 20;
22722     return Style;
22723   }());
22724 
22725   // Test 9.1.2: propagate more than one level with no parent file.
22726   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22727                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22728   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22729                          llvm::MemoryBuffer::getMemBuffer(
22730                              "BasedOnStyle: InheritParentConfig\n"
22731                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22732   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22733 
22734   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22735   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22736   ASSERT_TRUE(static_cast<bool>(Style9));
22737   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22738     auto Style = getNoStyle();
22739     Style.ColumnLimit = 20;
22740     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22741     return Style;
22742   }());
22743 
22744   // Test 9.2: with LLVM fallback style
22745   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22746   ASSERT_TRUE(static_cast<bool>(Style9));
22747   ASSERT_EQ(*Style9, [] {
22748     auto Style = getLLVMStyle();
22749     Style.ColumnLimit = 20;
22750     return Style;
22751   }());
22752 
22753   // Test 9.3: with a parent file
22754   ASSERT_TRUE(
22755       FS.addFile("/e/.clang-format", 0,
22756                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
22757                                                   "UseTab: Always")));
22758   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22759   ASSERT_TRUE(static_cast<bool>(Style9));
22760   ASSERT_EQ(*Style9, [] {
22761     auto Style = getGoogleStyle();
22762     Style.ColumnLimit = 20;
22763     Style.UseTab = FormatStyle::UT_Always;
22764     return Style;
22765   }());
22766 
22767   // Test 9.4: propagate more than one level with a parent file.
22768   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
22769     auto Style = getGoogleStyle();
22770     Style.ColumnLimit = 20;
22771     Style.UseTab = FormatStyle::UT_Always;
22772     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22773     return Style;
22774   }();
22775 
22776   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22777   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22778   ASSERT_TRUE(static_cast<bool>(Style9));
22779   ASSERT_EQ(*Style9, SubSubStyle);
22780 
22781   // Test 9.5: use InheritParentConfig as style name
22782   Style9 =
22783       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
22784   ASSERT_TRUE(static_cast<bool>(Style9));
22785   ASSERT_EQ(*Style9, SubSubStyle);
22786 
22787   // Test 9.6: use command line style with inheritance
22788   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
22789                     "none", "", &FS);
22790   ASSERT_TRUE(static_cast<bool>(Style9));
22791   ASSERT_EQ(*Style9, SubSubStyle);
22792 
22793   // Test 9.7: use command line style with inheritance and own config
22794   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
22795                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
22796                     "/e/sub/code.cpp", "none", "", &FS);
22797   ASSERT_TRUE(static_cast<bool>(Style9));
22798   ASSERT_EQ(*Style9, SubSubStyle);
22799 
22800   // Test 9.8: use inheritance from a file without BasedOnStyle
22801   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
22802                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
22803   ASSERT_TRUE(
22804       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
22805                  llvm::MemoryBuffer::getMemBuffer(
22806                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
22807   // Make sure we do not use the fallback style
22808   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
22809   ASSERT_TRUE(static_cast<bool>(Style9));
22810   ASSERT_EQ(*Style9, [] {
22811     auto Style = getLLVMStyle();
22812     Style.ColumnLimit = 123;
22813     return Style;
22814   }());
22815 
22816   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
22817   ASSERT_TRUE(static_cast<bool>(Style9));
22818   ASSERT_EQ(*Style9, [] {
22819     auto Style = getLLVMStyle();
22820     Style.ColumnLimit = 123;
22821     Style.IndentWidth = 7;
22822     return Style;
22823   }());
22824 
22825   // Test 9.9: use inheritance from a specific config file.
22826   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
22827                     "none", "", &FS);
22828   ASSERT_TRUE(static_cast<bool>(Style9));
22829   ASSERT_EQ(*Style9, SubSubStyle);
22830 }
22831 
22832 TEST(FormatStyle, GetStyleOfSpecificFile) {
22833   llvm::vfs::InMemoryFileSystem FS;
22834   // Specify absolute path to a format file in a parent directory.
22835   ASSERT_TRUE(
22836       FS.addFile("/e/.clang-format", 0,
22837                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22838   ASSERT_TRUE(
22839       FS.addFile("/e/explicit.clang-format", 0,
22840                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22841   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
22842                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22843   auto Style = getStyle("file:/e/explicit.clang-format",
22844                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22845   ASSERT_TRUE(static_cast<bool>(Style));
22846   ASSERT_EQ(*Style, getGoogleStyle());
22847 
22848   // Specify relative path to a format file.
22849   ASSERT_TRUE(
22850       FS.addFile("../../e/explicit.clang-format", 0,
22851                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22852   Style = getStyle("file:../../e/explicit.clang-format",
22853                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22854   ASSERT_TRUE(static_cast<bool>(Style));
22855   ASSERT_EQ(*Style, getGoogleStyle());
22856 
22857   // Specify path to a format file that does not exist.
22858   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
22859                    "LLVM", "", &FS);
22860   ASSERT_FALSE(static_cast<bool>(Style));
22861   llvm::consumeError(Style.takeError());
22862 
22863   // Specify path to a file on the filesystem.
22864   SmallString<128> FormatFilePath;
22865   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
22866       "FormatFileTest", "tpl", FormatFilePath);
22867   EXPECT_FALSE((bool)ECF);
22868   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
22869   EXPECT_FALSE((bool)ECF);
22870   FormatFileTest << "BasedOnStyle: Google\n";
22871   FormatFileTest.close();
22872 
22873   SmallString<128> TestFilePath;
22874   std::error_code ECT =
22875       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
22876   EXPECT_FALSE((bool)ECT);
22877   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
22878   CodeFileTest << "int i;\n";
22879   CodeFileTest.close();
22880 
22881   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
22882   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
22883 
22884   llvm::sys::fs::remove(FormatFilePath.c_str());
22885   llvm::sys::fs::remove(TestFilePath.c_str());
22886   ASSERT_TRUE(static_cast<bool>(Style));
22887   ASSERT_EQ(*Style, getGoogleStyle());
22888 }
22889 
22890 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
22891   // Column limit is 20.
22892   std::string Code = "Type *a =\n"
22893                      "    new Type();\n"
22894                      "g(iiiii, 0, jjjjj,\n"
22895                      "  0, kkkkk, 0, mm);\n"
22896                      "int  bad     = format   ;";
22897   std::string Expected = "auto a = new Type();\n"
22898                          "g(iiiii, nullptr,\n"
22899                          "  jjjjj, nullptr,\n"
22900                          "  kkkkk, nullptr,\n"
22901                          "  mm);\n"
22902                          "int  bad     = format   ;";
22903   FileID ID = Context.createInMemoryFile("format.cpp", Code);
22904   tooling::Replacements Replaces = toReplacements(
22905       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
22906                             "auto "),
22907        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
22908                             "nullptr"),
22909        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
22910                             "nullptr"),
22911        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
22912                             "nullptr")});
22913 
22914   FormatStyle Style = getLLVMStyle();
22915   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
22916   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22917   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22918       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22919   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22920   EXPECT_TRUE(static_cast<bool>(Result));
22921   EXPECT_EQ(Expected, *Result);
22922 }
22923 
22924 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
22925   std::string Code = "#include \"a.h\"\n"
22926                      "#include \"c.h\"\n"
22927                      "\n"
22928                      "int main() {\n"
22929                      "  return 0;\n"
22930                      "}";
22931   std::string Expected = "#include \"a.h\"\n"
22932                          "#include \"b.h\"\n"
22933                          "#include \"c.h\"\n"
22934                          "\n"
22935                          "int main() {\n"
22936                          "  return 0;\n"
22937                          "}";
22938   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
22939   tooling::Replacements Replaces = toReplacements(
22940       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
22941                             "#include \"b.h\"\n")});
22942 
22943   FormatStyle Style = getLLVMStyle();
22944   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
22945   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22946   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22947       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22948   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22949   EXPECT_TRUE(static_cast<bool>(Result));
22950   EXPECT_EQ(Expected, *Result);
22951 }
22952 
22953 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
22954   EXPECT_EQ("using std::cin;\n"
22955             "using std::cout;",
22956             format("using std::cout;\n"
22957                    "using std::cin;",
22958                    getGoogleStyle()));
22959 }
22960 
22961 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
22962   FormatStyle Style = getLLVMStyle();
22963   Style.Standard = FormatStyle::LS_Cpp03;
22964   // cpp03 recognize this string as identifier u8 and literal character 'a'
22965   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
22966 }
22967 
22968 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
22969   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
22970   // all modes, including C++11, C++14 and C++17
22971   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
22972 }
22973 
22974 TEST_F(FormatTest, DoNotFormatLikelyXml) {
22975   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
22976   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
22977 }
22978 
22979 TEST_F(FormatTest, StructuredBindings) {
22980   // Structured bindings is a C++17 feature.
22981   // all modes, including C++11, C++14 and C++17
22982   verifyFormat("auto [a, b] = f();");
22983   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
22984   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
22985   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
22986   EXPECT_EQ("auto const volatile [a, b] = f();",
22987             format("auto  const   volatile[a, b] = f();"));
22988   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
22989   EXPECT_EQ("auto &[a, b, c] = f();",
22990             format("auto   &[  a  ,  b,c   ] = f();"));
22991   EXPECT_EQ("auto &&[a, b, c] = f();",
22992             format("auto   &&[  a  ,  b,c   ] = f();"));
22993   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
22994   EXPECT_EQ("auto const volatile &&[a, b] = f();",
22995             format("auto  const  volatile  &&[a, b] = f();"));
22996   EXPECT_EQ("auto const &&[a, b] = f();",
22997             format("auto  const   &&  [a, b] = f();"));
22998   EXPECT_EQ("const auto &[a, b] = f();",
22999             format("const  auto  &  [a, b] = f();"));
23000   EXPECT_EQ("const auto volatile &&[a, b] = f();",
23001             format("const  auto   volatile  &&[a, b] = f();"));
23002   EXPECT_EQ("volatile const auto &&[a, b] = f();",
23003             format("volatile  const  auto   &&[a, b] = f();"));
23004   EXPECT_EQ("const auto &&[a, b] = f();",
23005             format("const  auto  &&  [a, b] = f();"));
23006 
23007   // Make sure we don't mistake structured bindings for lambdas.
23008   FormatStyle PointerMiddle = getLLVMStyle();
23009   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
23010   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
23011   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
23012   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
23013   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
23014   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
23015   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
23016   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
23017   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
23018   verifyFormat("auto const & [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 
23023   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
23024             format("for (const auto   &&   [a, b] : some_range) {\n}"));
23025   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
23026             format("for (const auto   &   [a, b] : some_range) {\n}"));
23027   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
23028             format("for (const auto[a, b] : some_range) {\n}"));
23029   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
23030   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
23031   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
23032   EXPECT_EQ("auto const &[x, y](expr);",
23033             format("auto  const  &  [x,y]  (expr);"));
23034   EXPECT_EQ("auto const &&[x, y](expr);",
23035             format("auto  const  &&  [x,y]  (expr);"));
23036   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
23037   EXPECT_EQ("auto const &[x, y]{expr};",
23038             format("auto  const  &  [x,y]  {expr};"));
23039   EXPECT_EQ("auto const &&[x, y]{expr};",
23040             format("auto  const  &&  [x,y]  {expr};"));
23041 
23042   FormatStyle Spaces = getLLVMStyle();
23043   Spaces.SpacesInSquareBrackets = true;
23044   verifyFormat("auto [ a, b ] = f();", Spaces);
23045   verifyFormat("auto &&[ a, b ] = f();", Spaces);
23046   verifyFormat("auto &[ a, b ] = f();", Spaces);
23047   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
23048   verifyFormat("auto const &[ a, b ] = f();", Spaces);
23049 }
23050 
23051 TEST_F(FormatTest, FileAndCode) {
23052   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
23053   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
23054   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
23055   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
23056   EXPECT_EQ(FormatStyle::LK_ObjC,
23057             guessLanguage("foo.h", "@interface Foo\n@end\n"));
23058   EXPECT_EQ(
23059       FormatStyle::LK_ObjC,
23060       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
23061   EXPECT_EQ(FormatStyle::LK_ObjC,
23062             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
23063   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
23064   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
23065   EXPECT_EQ(FormatStyle::LK_ObjC,
23066             guessLanguage("foo", "@interface Foo\n@end\n"));
23067   EXPECT_EQ(FormatStyle::LK_ObjC,
23068             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
23069   EXPECT_EQ(
23070       FormatStyle::LK_ObjC,
23071       guessLanguage("foo.h",
23072                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
23073   EXPECT_EQ(
23074       FormatStyle::LK_Cpp,
23075       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
23076   // Only one of the two preprocessor regions has ObjC-like code.
23077   EXPECT_EQ(FormatStyle::LK_ObjC,
23078             guessLanguage("foo.h", "#if A\n"
23079                                    "#define B() C\n"
23080                                    "#else\n"
23081                                    "#define B() [NSString a:@\"\"]\n"
23082                                    "#endif\n"));
23083 }
23084 
23085 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
23086   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
23087   EXPECT_EQ(FormatStyle::LK_ObjC,
23088             guessLanguage("foo.h", "array[[calculator getIndex]];"));
23089   EXPECT_EQ(FormatStyle::LK_Cpp,
23090             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
23091   EXPECT_EQ(
23092       FormatStyle::LK_Cpp,
23093       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
23094   EXPECT_EQ(FormatStyle::LK_ObjC,
23095             guessLanguage("foo.h", "[[noreturn foo] bar];"));
23096   EXPECT_EQ(FormatStyle::LK_Cpp,
23097             guessLanguage("foo.h", "[[clang::fallthrough]];"));
23098   EXPECT_EQ(FormatStyle::LK_ObjC,
23099             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
23100   EXPECT_EQ(FormatStyle::LK_Cpp,
23101             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
23102   EXPECT_EQ(FormatStyle::LK_Cpp,
23103             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
23104   EXPECT_EQ(FormatStyle::LK_ObjC,
23105             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
23106   EXPECT_EQ(FormatStyle::LK_Cpp,
23107             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
23108   EXPECT_EQ(
23109       FormatStyle::LK_Cpp,
23110       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
23111   EXPECT_EQ(
23112       FormatStyle::LK_Cpp,
23113       guessLanguage("foo.h",
23114                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
23115   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
23116 }
23117 
23118 TEST_F(FormatTest, GuessLanguageWithCaret) {
23119   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
23120   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
23121   EXPECT_EQ(FormatStyle::LK_ObjC,
23122             guessLanguage("foo.h", "int(^)(char, float);"));
23123   EXPECT_EQ(FormatStyle::LK_ObjC,
23124             guessLanguage("foo.h", "int(^foo)(char, float);"));
23125   EXPECT_EQ(FormatStyle::LK_ObjC,
23126             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
23127   EXPECT_EQ(FormatStyle::LK_ObjC,
23128             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
23129   EXPECT_EQ(
23130       FormatStyle::LK_ObjC,
23131       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
23132 }
23133 
23134 TEST_F(FormatTest, GuessLanguageWithPragmas) {
23135   EXPECT_EQ(FormatStyle::LK_Cpp,
23136             guessLanguage("foo.h", "__pragma(warning(disable:))"));
23137   EXPECT_EQ(FormatStyle::LK_Cpp,
23138             guessLanguage("foo.h", "#pragma(warning(disable:))"));
23139   EXPECT_EQ(FormatStyle::LK_Cpp,
23140             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
23141 }
23142 
23143 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
23144   // ASM symbolic names are identifiers that must be surrounded by [] without
23145   // space in between:
23146   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
23147 
23148   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
23149   verifyFormat(R"(//
23150 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
23151 )");
23152 
23153   // A list of several ASM symbolic names.
23154   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
23155 
23156   // ASM symbolic names in inline ASM with inputs and outputs.
23157   verifyFormat(R"(//
23158 asm("cmoveq %1, %2, %[result]"
23159     : [result] "=r"(result)
23160     : "r"(test), "r"(new), "[result]"(old));
23161 )");
23162 
23163   // ASM symbolic names in inline ASM with no outputs.
23164   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
23165 }
23166 
23167 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
23168   EXPECT_EQ(FormatStyle::LK_Cpp,
23169             guessLanguage("foo.h", "void f() {\n"
23170                                    "  asm (\"mov %[e], %[d]\"\n"
23171                                    "     : [d] \"=rm\" (d)\n"
23172                                    "       [e] \"rm\" (*e));\n"
23173                                    "}"));
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 volatile (\"mov %[e], %[d]\"\n"
23201                                    "     : [d] \"=rm\" (d)\n"
23202                                    "       [e] \"rm\" (*e));\n"
23203                                    "}"));
23204 }
23205 
23206 TEST_F(FormatTest, GuessLanguageWithChildLines) {
23207   EXPECT_EQ(FormatStyle::LK_Cpp,
23208             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
23209   EXPECT_EQ(FormatStyle::LK_ObjC,
23210             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
23211   EXPECT_EQ(
23212       FormatStyle::LK_Cpp,
23213       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
23214   EXPECT_EQ(
23215       FormatStyle::LK_ObjC,
23216       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
23217 }
23218 
23219 TEST_F(FormatTest, TypenameMacros) {
23220   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
23221 
23222   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
23223   FormatStyle Google = getGoogleStyleWithColumns(0);
23224   Google.TypenameMacros = TypenameMacros;
23225   verifyFormat("struct foo {\n"
23226                "  int bar;\n"
23227                "  TAILQ_ENTRY(a) bleh;\n"
23228                "};",
23229                Google);
23230 
23231   FormatStyle Macros = getLLVMStyle();
23232   Macros.TypenameMacros = TypenameMacros;
23233 
23234   verifyFormat("STACK_OF(int) a;", Macros);
23235   verifyFormat("STACK_OF(int) *a;", Macros);
23236   verifyFormat("STACK_OF(int const *) *a;", Macros);
23237   verifyFormat("STACK_OF(int *const) *a;", Macros);
23238   verifyFormat("STACK_OF(int, string) a;", Macros);
23239   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
23240   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
23241   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
23242   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
23243   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
23244   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
23245 
23246   Macros.PointerAlignment = FormatStyle::PAS_Left;
23247   verifyFormat("STACK_OF(int)* a;", Macros);
23248   verifyFormat("STACK_OF(int*)* a;", Macros);
23249   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
23250   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
23251   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
23252 }
23253 
23254 TEST_F(FormatTest, AtomicQualifier) {
23255   // Check that we treate _Atomic as a type and not a function call
23256   FormatStyle Google = getGoogleStyleWithColumns(0);
23257   verifyFormat("struct foo {\n"
23258                "  int a1;\n"
23259                "  _Atomic(a) a2;\n"
23260                "  _Atomic(_Atomic(int) *const) a3;\n"
23261                "};",
23262                Google);
23263   verifyFormat("_Atomic(uint64_t) a;");
23264   verifyFormat("_Atomic(uint64_t) *a;");
23265   verifyFormat("_Atomic(uint64_t const *) *a;");
23266   verifyFormat("_Atomic(uint64_t *const) *a;");
23267   verifyFormat("_Atomic(const uint64_t *) *a;");
23268   verifyFormat("_Atomic(uint64_t) a;");
23269   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
23270   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
23271   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
23272   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
23273 
23274   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
23275   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
23276   FormatStyle Style = getLLVMStyle();
23277   Style.PointerAlignment = FormatStyle::PAS_Left;
23278   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
23279   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
23280   verifyFormat("_Atomic(int)* a;", Style);
23281   verifyFormat("_Atomic(int*)* a;", Style);
23282   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
23283 
23284   Style.SpacesInCStyleCastParentheses = true;
23285   Style.SpacesInParentheses = false;
23286   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
23287   Style.SpacesInCStyleCastParentheses = false;
23288   Style.SpacesInParentheses = true;
23289   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
23290   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
23291 }
23292 
23293 TEST_F(FormatTest, AmbersandInLamda) {
23294   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
23295   FormatStyle AlignStyle = getLLVMStyle();
23296   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
23297   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23298   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
23299   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23300 }
23301 
23302 TEST_F(FormatTest, SpacesInConditionalStatement) {
23303   FormatStyle Spaces = getLLVMStyle();
23304   Spaces.IfMacros.clear();
23305   Spaces.IfMacros.push_back("MYIF");
23306   Spaces.SpacesInConditionalStatement = true;
23307   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
23308   verifyFormat("if ( !a )\n  return;", Spaces);
23309   verifyFormat("if ( a )\n  return;", Spaces);
23310   verifyFormat("if constexpr ( a )\n  return;", Spaces);
23311   verifyFormat("MYIF ( a )\n  return;", Spaces);
23312   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
23313   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
23314   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
23315   verifyFormat("while ( a )\n  return;", Spaces);
23316   verifyFormat("while ( (a && b) )\n  return;", Spaces);
23317   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
23318   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
23319   // Check that space on the left of "::" is inserted as expected at beginning
23320   // of condition.
23321   verifyFormat("while ( ::func() )\n  return;", Spaces);
23322 
23323   // Check impact of ControlStatementsExceptControlMacros is honored.
23324   Spaces.SpaceBeforeParens =
23325       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
23326   verifyFormat("MYIF( a )\n  return;", Spaces);
23327   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
23328   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
23329 }
23330 
23331 TEST_F(FormatTest, AlternativeOperators) {
23332   // Test case for ensuring alternate operators are not
23333   // combined with their right most neighbour.
23334   verifyFormat("int a and b;");
23335   verifyFormat("int a and_eq b;");
23336   verifyFormat("int a bitand b;");
23337   verifyFormat("int a bitor b;");
23338   verifyFormat("int a compl b;");
23339   verifyFormat("int a not b;");
23340   verifyFormat("int a not_eq b;");
23341   verifyFormat("int a or b;");
23342   verifyFormat("int a xor b;");
23343   verifyFormat("int a xor_eq b;");
23344   verifyFormat("return this not_eq bitand other;");
23345   verifyFormat("bool operator not_eq(const X bitand other)");
23346 
23347   verifyFormat("int a and 5;");
23348   verifyFormat("int a and_eq 5;");
23349   verifyFormat("int a bitand 5;");
23350   verifyFormat("int a bitor 5;");
23351   verifyFormat("int a compl 5;");
23352   verifyFormat("int a not 5;");
23353   verifyFormat("int a not_eq 5;");
23354   verifyFormat("int a or 5;");
23355   verifyFormat("int a xor 5;");
23356   verifyFormat("int a xor_eq 5;");
23357 
23358   verifyFormat("int a compl(5);");
23359   verifyFormat("int a not(5);");
23360 
23361   /* FIXME handle alternate tokens
23362    * https://en.cppreference.com/w/cpp/language/operator_alternative
23363   // alternative tokens
23364   verifyFormat("compl foo();");     //  ~foo();
23365   verifyFormat("foo() <%%>;");      // foo();
23366   verifyFormat("void foo() <%%>;"); // void foo(){}
23367   verifyFormat("int a <:1:>;");     // int a[1];[
23368   verifyFormat("%:define ABC abc"); // #define ABC abc
23369   verifyFormat("%:%:");             // ##
23370   */
23371 }
23372 
23373 TEST_F(FormatTest, STLWhileNotDefineChed) {
23374   verifyFormat("#if defined(while)\n"
23375                "#define while EMIT WARNING C4005\n"
23376                "#endif // while");
23377 }
23378 
23379 TEST_F(FormatTest, OperatorSpacing) {
23380   FormatStyle Style = getLLVMStyle();
23381   Style.PointerAlignment = FormatStyle::PAS_Right;
23382   verifyFormat("Foo::operator*();", Style);
23383   verifyFormat("Foo::operator void *();", Style);
23384   verifyFormat("Foo::operator void **();", Style);
23385   verifyFormat("Foo::operator void *&();", Style);
23386   verifyFormat("Foo::operator void *&&();", Style);
23387   verifyFormat("Foo::operator void const *();", Style);
23388   verifyFormat("Foo::operator void const **();", Style);
23389   verifyFormat("Foo::operator void const *&();", Style);
23390   verifyFormat("Foo::operator void const *&&();", Style);
23391   verifyFormat("Foo::operator()(void *);", Style);
23392   verifyFormat("Foo::operator*(void *);", Style);
23393   verifyFormat("Foo::operator*();", Style);
23394   verifyFormat("Foo::operator**();", Style);
23395   verifyFormat("Foo::operator&();", Style);
23396   verifyFormat("Foo::operator<int> *();", Style);
23397   verifyFormat("Foo::operator<Foo> *();", Style);
23398   verifyFormat("Foo::operator<int> **();", Style);
23399   verifyFormat("Foo::operator<Foo> **();", Style);
23400   verifyFormat("Foo::operator<int> &();", Style);
23401   verifyFormat("Foo::operator<Foo> &();", 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("operator*(int (*)(), class Foo);", Style);
23409 
23410   verifyFormat("Foo::operator&();", Style);
23411   verifyFormat("Foo::operator void &();", Style);
23412   verifyFormat("Foo::operator void const &();", Style);
23413   verifyFormat("Foo::operator()(void &);", Style);
23414   verifyFormat("Foo::operator&(void &);", Style);
23415   verifyFormat("Foo::operator&();", Style);
23416   verifyFormat("operator&(int (&)(), class Foo);", Style);
23417   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23418 
23419   verifyFormat("Foo::operator&&();", Style);
23420   verifyFormat("Foo::operator**();", Style);
23421   verifyFormat("Foo::operator void &&();", Style);
23422   verifyFormat("Foo::operator void const &&();", Style);
23423   verifyFormat("Foo::operator()(void &&);", Style);
23424   verifyFormat("Foo::operator&&(void &&);", Style);
23425   verifyFormat("Foo::operator&&();", Style);
23426   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23427   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23428   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23429                Style);
23430   verifyFormat("operator void **()", Style);
23431   verifyFormat("operator const FooRight<Object> &()", Style);
23432   verifyFormat("operator const FooRight<Object> *()", Style);
23433   verifyFormat("operator const FooRight<Object> **()", Style);
23434   verifyFormat("operator const FooRight<Object> *&()", Style);
23435   verifyFormat("operator const FooRight<Object> *&&()", Style);
23436 
23437   Style.PointerAlignment = FormatStyle::PAS_Left;
23438   verifyFormat("Foo::operator*();", Style);
23439   verifyFormat("Foo::operator**();", Style);
23440   verifyFormat("Foo::operator void*();", Style);
23441   verifyFormat("Foo::operator void**();", Style);
23442   verifyFormat("Foo::operator void*&();", Style);
23443   verifyFormat("Foo::operator void*&&();", Style);
23444   verifyFormat("Foo::operator void const*();", Style);
23445   verifyFormat("Foo::operator void const**();", Style);
23446   verifyFormat("Foo::operator void const*&();", Style);
23447   verifyFormat("Foo::operator void const*&&();", Style);
23448   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23449   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23450   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23451   verifyFormat("Foo::operator()(void*);", Style);
23452   verifyFormat("Foo::operator*(void*);", Style);
23453   verifyFormat("Foo::operator*();", Style);
23454   verifyFormat("Foo::operator<int>*();", Style);
23455   verifyFormat("Foo::operator<Foo>*();", Style);
23456   verifyFormat("Foo::operator<int>**();", Style);
23457   verifyFormat("Foo::operator<Foo>**();", Style);
23458   verifyFormat("Foo::operator<Foo>*&();", Style);
23459   verifyFormat("Foo::operator<int>&();", Style);
23460   verifyFormat("Foo::operator<Foo>&();", Style);
23461   verifyFormat("Foo::operator<int>&&();", Style);
23462   verifyFormat("Foo::operator<Foo>&&();", Style);
23463   verifyFormat("Foo::operator<int>*&();", Style);
23464   verifyFormat("Foo::operator<Foo>*&();", Style);
23465   verifyFormat("operator*(int (*)(), class Foo);", Style);
23466 
23467   verifyFormat("Foo::operator&();", Style);
23468   verifyFormat("Foo::operator void&();", Style);
23469   verifyFormat("Foo::operator void const&();", Style);
23470   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23471   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23472   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23473   verifyFormat("Foo::operator()(void&);", Style);
23474   verifyFormat("Foo::operator&(void&);", Style);
23475   verifyFormat("Foo::operator&();", Style);
23476   verifyFormat("operator&(int (&)(), class Foo);", Style);
23477   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23478   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23479 
23480   verifyFormat("Foo::operator&&();", Style);
23481   verifyFormat("Foo::operator void&&();", Style);
23482   verifyFormat("Foo::operator void const&&();", Style);
23483   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23484   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23485   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23486   verifyFormat("Foo::operator()(void&&);", Style);
23487   verifyFormat("Foo::operator&&(void&&);", Style);
23488   verifyFormat("Foo::operator&&();", Style);
23489   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23490   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23491   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23492                Style);
23493   verifyFormat("operator void**()", Style);
23494   verifyFormat("operator const FooLeft<Object>&()", Style);
23495   verifyFormat("operator const FooLeft<Object>*()", Style);
23496   verifyFormat("operator const FooLeft<Object>**()", Style);
23497   verifyFormat("operator const FooLeft<Object>*&()", Style);
23498   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23499 
23500   // PR45107
23501   verifyFormat("operator Vector<String>&();", Style);
23502   verifyFormat("operator const Vector<String>&();", Style);
23503   verifyFormat("operator foo::Bar*();", Style);
23504   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23505   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23506                Style);
23507 
23508   Style.PointerAlignment = FormatStyle::PAS_Middle;
23509   verifyFormat("Foo::operator*();", Style);
23510   verifyFormat("Foo::operator void *();", Style);
23511   verifyFormat("Foo::operator()(void *);", Style);
23512   verifyFormat("Foo::operator*(void *);", Style);
23513   verifyFormat("Foo::operator*();", Style);
23514   verifyFormat("operator*(int (*)(), class Foo);", Style);
23515 
23516   verifyFormat("Foo::operator&();", Style);
23517   verifyFormat("Foo::operator void &();", Style);
23518   verifyFormat("Foo::operator void const &();", Style);
23519   verifyFormat("Foo::operator()(void &);", Style);
23520   verifyFormat("Foo::operator&(void &);", Style);
23521   verifyFormat("Foo::operator&();", Style);
23522   verifyFormat("operator&(int (&)(), class Foo);", Style);
23523 
23524   verifyFormat("Foo::operator&&();", Style);
23525   verifyFormat("Foo::operator void &&();", Style);
23526   verifyFormat("Foo::operator void const &&();", Style);
23527   verifyFormat("Foo::operator()(void &&);", Style);
23528   verifyFormat("Foo::operator&&(void &&);", Style);
23529   verifyFormat("Foo::operator&&();", Style);
23530   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23531 }
23532 
23533 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23534   FormatStyle Style = getLLVMStyle();
23535   // PR46157
23536   verifyFormat("foo(operator+, -42);", Style);
23537   verifyFormat("foo(operator++, -42);", Style);
23538   verifyFormat("foo(operator--, -42);", Style);
23539   verifyFormat("foo(-42, operator--);", Style);
23540   verifyFormat("foo(-42, operator, );", Style);
23541   verifyFormat("foo(operator, , -42);", Style);
23542 }
23543 
23544 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23545   FormatStyle Style = getLLVMStyle();
23546   Style.WhitespaceSensitiveMacros.push_back("FOO");
23547 
23548   // Don't use the helpers here, since 'mess up' will change the whitespace
23549   // and these are all whitespace sensitive by definition
23550   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23551             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23552   EXPECT_EQ(
23553       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23554       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23555   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23556             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23557   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23558             "       Still=Intentional);",
23559             format("FOO(String-ized&Messy+But,: :\n"
23560                    "       Still=Intentional);",
23561                    Style));
23562   Style.AlignConsecutiveAssignments.Enabled = true;
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 
23569   Style.ColumnLimit = 21;
23570   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23571             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23572 }
23573 
23574 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23575   // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
23576   // test its interaction with line wrapping
23577   FormatStyle Style = getLLVMStyleWithColumns(80);
23578   verifyFormat("namespace {\n"
23579                "int i;\n"
23580                "int j;\n"
23581                "} // namespace",
23582                Style);
23583 
23584   verifyFormat("namespace AAA {\n"
23585                "int i;\n"
23586                "int j;\n"
23587                "} // namespace AAA",
23588                Style);
23589 
23590   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23591             "int i;\n"
23592             "int j;\n"
23593             "} // namespace Averyveryveryverylongnamespace",
23594             format("namespace Averyveryveryverylongnamespace {\n"
23595                    "int i;\n"
23596                    "int j;\n"
23597                    "}",
23598                    Style));
23599 
23600   EXPECT_EQ(
23601       "namespace "
23602       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23603       "    went::mad::now {\n"
23604       "int i;\n"
23605       "int j;\n"
23606       "} // namespace\n"
23607       "  // "
23608       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23609       "went::mad::now",
23610       format("namespace "
23611              "would::it::save::you::a::lot::of::time::if_::i::"
23612              "just::gave::up::and_::went::mad::now {\n"
23613              "int i;\n"
23614              "int j;\n"
23615              "}",
23616              Style));
23617 
23618   // This used to duplicate the comment again and again on subsequent runs
23619   EXPECT_EQ(
23620       "namespace "
23621       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23622       "    went::mad::now {\n"
23623       "int i;\n"
23624       "int j;\n"
23625       "} // namespace\n"
23626       "  // "
23627       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23628       "went::mad::now",
23629       format("namespace "
23630              "would::it::save::you::a::lot::of::time::if_::i::"
23631              "just::gave::up::and_::went::mad::now {\n"
23632              "int i;\n"
23633              "int j;\n"
23634              "} // namespace\n"
23635              "  // "
23636              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23637              "and_::went::mad::now",
23638              Style));
23639 }
23640 
23641 TEST_F(FormatTest, LikelyUnlikely) {
23642   FormatStyle Style = getLLVMStyle();
23643 
23644   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23645                "  return 29;\n"
23646                "}",
23647                Style);
23648 
23649   verifyFormat("if (argc > 5) [[likely]] {\n"
23650                "  return 29;\n"
23651                "}",
23652                Style);
23653 
23654   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23655                "  return 29;\n"
23656                "} else [[likely]] {\n"
23657                "  return 42;\n"
23658                "}\n",
23659                Style);
23660 
23661   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23662                "  return 29;\n"
23663                "} else if (argc > 10) [[likely]] {\n"
23664                "  return 99;\n"
23665                "} else {\n"
23666                "  return 42;\n"
23667                "}\n",
23668                Style);
23669 
23670   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23671                "  return 29;\n"
23672                "}",
23673                Style);
23674 
23675   verifyFormat("if (argc > 5) [[unlikely]]\n"
23676                "  return 29;\n",
23677                Style);
23678   verifyFormat("if (argc > 5) [[likely]]\n"
23679                "  return 29;\n",
23680                Style);
23681 
23682   Style.AttributeMacros.push_back("UNLIKELY");
23683   Style.AttributeMacros.push_back("LIKELY");
23684   verifyFormat("if (argc > 5) UNLIKELY\n"
23685                "  return 29;\n",
23686                Style);
23687 
23688   verifyFormat("if (argc > 5) UNLIKELY {\n"
23689                "  return 29;\n"
23690                "}",
23691                Style);
23692   verifyFormat("if (argc > 5) UNLIKELY {\n"
23693                "  return 29;\n"
23694                "} else [[likely]] {\n"
23695                "  return 42;\n"
23696                "}\n",
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 }
23711 
23712 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23713   verifyFormat("Constructor()\n"
23714                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23715                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23716                "aaaaaaaaaaaaaaaaaat))");
23717   verifyFormat("Constructor()\n"
23718                "    : aaaaaaaaaaaaa(aaaaaa), "
23719                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
23720 
23721   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
23722   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
23723   verifyFormat("Constructor()\n"
23724                "    : aaaaaa(aaaaaa),\n"
23725                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23726                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
23727                StyleWithWhitespacePenalty);
23728   verifyFormat("Constructor()\n"
23729                "    : aaaaaaaaaaaaa(aaaaaa), "
23730                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
23731                StyleWithWhitespacePenalty);
23732 }
23733 
23734 TEST_F(FormatTest, LLVMDefaultStyle) {
23735   FormatStyle Style = getLLVMStyle();
23736   verifyFormat("extern \"C\" {\n"
23737                "int foo();\n"
23738                "}",
23739                Style);
23740 }
23741 TEST_F(FormatTest, GNUDefaultStyle) {
23742   FormatStyle Style = getGNUStyle();
23743   verifyFormat("extern \"C\"\n"
23744                "{\n"
23745                "  int foo ();\n"
23746                "}",
23747                Style);
23748 }
23749 TEST_F(FormatTest, MozillaDefaultStyle) {
23750   FormatStyle Style = getMozillaStyle();
23751   verifyFormat("extern \"C\"\n"
23752                "{\n"
23753                "  int foo();\n"
23754                "}",
23755                Style);
23756 }
23757 TEST_F(FormatTest, GoogleDefaultStyle) {
23758   FormatStyle Style = getGoogleStyle();
23759   verifyFormat("extern \"C\" {\n"
23760                "int foo();\n"
23761                "}",
23762                Style);
23763 }
23764 TEST_F(FormatTest, ChromiumDefaultStyle) {
23765   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
23766   verifyFormat("extern \"C\" {\n"
23767                "int foo();\n"
23768                "}",
23769                Style);
23770 }
23771 TEST_F(FormatTest, MicrosoftDefaultStyle) {
23772   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
23773   verifyFormat("extern \"C\"\n"
23774                "{\n"
23775                "    int foo();\n"
23776                "}",
23777                Style);
23778 }
23779 TEST_F(FormatTest, WebKitDefaultStyle) {
23780   FormatStyle Style = getWebKitStyle();
23781   verifyFormat("extern \"C\" {\n"
23782                "int foo();\n"
23783                "}",
23784                Style);
23785 }
23786 
23787 TEST_F(FormatTest, Concepts) {
23788   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
23789             FormatStyle::BBCDS_Always);
23790   verifyFormat("template <typename T>\n"
23791                "concept True = true;");
23792 
23793   verifyFormat("template <typename T>\n"
23794                "concept C = ((false || foo()) && C2<T>) ||\n"
23795                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
23796                getLLVMStyleWithColumns(60));
23797 
23798   verifyFormat("template <typename T>\n"
23799                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
23800                "sizeof(T) <= 8;");
23801 
23802   verifyFormat("template <typename T>\n"
23803                "concept DelayedCheck = true && requires(T t) {\n"
23804                "                                 t.bar();\n"
23805                "                                 t.baz();\n"
23806                "                               } && sizeof(T) <= 8;");
23807 
23808   verifyFormat("template <typename T>\n"
23809                "concept DelayedCheck = true && requires(T t) { // Comment\n"
23810                "                                 t.bar();\n"
23811                "                                 t.baz();\n"
23812                "                               } && sizeof(T) <= 8;");
23813 
23814   verifyFormat("template <typename T>\n"
23815                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
23816                "sizeof(T) <= 8;");
23817 
23818   verifyFormat("template <typename T>\n"
23819                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
23820                "&& sizeof(T) <= 8;");
23821 
23822   verifyFormat(
23823       "template <typename T>\n"
23824       "concept DelayedCheck = static_cast<bool>(0) ||\n"
23825       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23826 
23827   verifyFormat("template <typename T>\n"
23828                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
23829                "&& sizeof(T) <= 8;");
23830 
23831   verifyFormat(
23832       "template <typename T>\n"
23833       "concept DelayedCheck = (bool)(0) ||\n"
23834       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23835 
23836   verifyFormat("template <typename T>\n"
23837                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
23838                "&& sizeof(T) <= 8;");
23839 
23840   verifyFormat("template <typename T>\n"
23841                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
23842                "sizeof(T) <= 8;");
23843 
23844   verifyFormat("template <typename T>\n"
23845                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
23846                "               requires(T t) {\n"
23847                "                 t.bar();\n"
23848                "                 t.baz();\n"
23849                "               } && sizeof(T) <= 8 && !(4 < 3);",
23850                getLLVMStyleWithColumns(60));
23851 
23852   verifyFormat("template <typename T>\n"
23853                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
23854 
23855   verifyFormat("template <typename T>\n"
23856                "concept C = foo();");
23857 
23858   verifyFormat("template <typename T>\n"
23859                "concept C = foo(T());");
23860 
23861   verifyFormat("template <typename T>\n"
23862                "concept C = foo(T{});");
23863 
23864   verifyFormat("template <typename T>\n"
23865                "concept Size = V<sizeof(T)>::Value > 5;");
23866 
23867   verifyFormat("template <typename T>\n"
23868                "concept True = S<T>::Value;");
23869 
23870   verifyFormat(
23871       "template <typename T>\n"
23872       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
23873       "            sizeof(T) <= 8;");
23874 
23875   // FIXME: This is misformatted because the fake l paren starts at bool, not at
23876   // the lambda l square.
23877   verifyFormat("template <typename T>\n"
23878                "concept C = [] -> bool { return true; }() && requires(T t) { "
23879                "t.bar(); } &&\n"
23880                "                      sizeof(T) <= 8;");
23881 
23882   verifyFormat(
23883       "template <typename T>\n"
23884       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
23885       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23886 
23887   verifyFormat("template <typename T>\n"
23888                "concept C = decltype([]() { return std::true_type{}; "
23889                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
23890                getLLVMStyleWithColumns(120));
23891 
23892   verifyFormat("template <typename T>\n"
23893                "concept C = decltype([]() -> std::true_type { return {}; "
23894                "}())::value &&\n"
23895                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23896 
23897   verifyFormat("template <typename T>\n"
23898                "concept C = true;\n"
23899                "Foo Bar;");
23900 
23901   verifyFormat("template <typename T>\n"
23902                "concept Hashable = requires(T a) {\n"
23903                "                     { std::hash<T>{}(a) } -> "
23904                "std::convertible_to<std::size_t>;\n"
23905                "                   };");
23906 
23907   verifyFormat(
23908       "template <typename T>\n"
23909       "concept EqualityComparable = requires(T a, T b) {\n"
23910       "                               { a == b } -> std::same_as<bool>;\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       "                               { a != b } -> std::same_as<bool>;\n"
23918       "                             };");
23919 
23920   verifyFormat("template <typename T>\n"
23921                "concept WeakEqualityComparable = requires(T a, T b) {\n"
23922                "                                   { a == b };\n"
23923                "                                   { a != b };\n"
23924                "                                 };");
23925 
23926   verifyFormat("template <typename T>\n"
23927                "concept HasSizeT = requires { typename T::size_t; };");
23928 
23929   verifyFormat("template <typename T>\n"
23930                "concept Semiregular =\n"
23931                "    DefaultConstructible<T> && CopyConstructible<T> && "
23932                "CopyAssignable<T> &&\n"
23933                "    requires(T a, std::size_t n) {\n"
23934                "      requires Same<T *, decltype(&a)>;\n"
23935                "      { a.~T() } noexcept;\n"
23936                "      requires Same<T *, decltype(new T)>;\n"
23937                "      requires Same<T *, decltype(new T[n])>;\n"
23938                "      { delete new T; };\n"
23939                "      { delete new T[n]; };\n"
23940                "    };");
23941 
23942   verifyFormat("template <typename T>\n"
23943                "concept Semiregular =\n"
23944                "    requires(T a, std::size_t n) {\n"
23945                "      requires Same<T *, decltype(&a)>;\n"
23946                "      { a.~T() } noexcept;\n"
23947                "      requires Same<T *, decltype(new T)>;\n"
23948                "      requires Same<T *, decltype(new T[n])>;\n"
23949                "      { delete new T; };\n"
23950                "      { delete new T[n]; };\n"
23951                "      { new T } -> std::same_as<T *>;\n"
23952                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
23953                "CopyAssignable<T>;");
23954 
23955   verifyFormat(
23956       "template <typename T>\n"
23957       "concept Semiregular =\n"
23958       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
23959       "                                 requires Same<T *, decltype(&a)>;\n"
23960       "                                 { a.~T() } noexcept;\n"
23961       "                                 requires Same<T *, decltype(new T)>;\n"
23962       "                                 requires Same<T *, decltype(new "
23963       "T[n])>;\n"
23964       "                                 { delete new T; };\n"
23965       "                                 { delete new T[n]; };\n"
23966       "                               } && CopyConstructible<T> && "
23967       "CopyAssignable<T>;");
23968 
23969   verifyFormat("template <typename T>\n"
23970                "concept Two = requires(T t) {\n"
23971                "                { t.foo() } -> std::same_as<Bar>;\n"
23972                "              } && requires(T &&t) {\n"
23973                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
23974                "                   };");
23975 
23976   verifyFormat(
23977       "template <typename T>\n"
23978       "concept C = requires(T x) {\n"
23979       "              { *x } -> std::convertible_to<typename T::inner>;\n"
23980       "              { x + 1 } noexcept -> std::same_as<int>;\n"
23981       "              { x * 1 } -> std::convertible_to<T>;\n"
23982       "            };");
23983 
23984   verifyFormat(
23985       "template <typename T, typename U = T>\n"
23986       "concept Swappable = requires(T &&t, U &&u) {\n"
23987       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
23988       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
23989       "                    };");
23990 
23991   verifyFormat("template <typename T, typename U>\n"
23992                "concept Common = requires(T &&t, U &&u) {\n"
23993                "                   typename CommonType<T, U>;\n"
23994                "                   { CommonType<T, 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(
24004       "template <typename T>\n"
24005       "concept C = requires(T t) {\n"
24006       "              requires Bar<T> && Foo<T>;\n"
24007       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24008       "            };");
24009 
24010   verifyFormat("template <typename T>\n"
24011                "concept HasFoo = requires(T t) {\n"
24012                "                   { t.foo() };\n"
24013                "                   t.foo();\n"
24014                "                 };\n"
24015                "template <typename T>\n"
24016                "concept HasBar = requires(T t) {\n"
24017                "                   { t.bar() };\n"
24018                "                   t.bar();\n"
24019                "                 };");
24020 
24021   verifyFormat("template <typename T>\n"
24022                "concept Large = sizeof(T) > 10;");
24023 
24024   verifyFormat("template <typename T, typename U>\n"
24025                "concept FooableWith = requires(T t, U u) {\n"
24026                "                        typename T::foo_type;\n"
24027                "                        { t.foo(u) } -> typename T::foo_type;\n"
24028                "                        t++;\n"
24029                "                      };\n"
24030                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
24031 
24032   verifyFormat("template <typename T>\n"
24033                "concept Context = is_specialization_of_v<context, T>;");
24034 
24035   verifyFormat("template <typename T>\n"
24036                "concept Node = std::is_object_v<T>;");
24037 
24038   verifyFormat("template <class T>\n"
24039                "concept integral = __is_integral(T);");
24040 
24041   verifyFormat("template <class T>\n"
24042                "concept is2D = __array_extent(T, 1) == 2;");
24043 
24044   verifyFormat("template <class T>\n"
24045                "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
24046 
24047   verifyFormat("template <class T, class T2>\n"
24048                "concept Same = __is_same_as<T, T2>;");
24049 
24050   auto Style = getLLVMStyle();
24051   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
24052 
24053   verifyFormat(
24054       "template <typename T>\n"
24055       "concept C = requires(T t) {\n"
24056       "              requires Bar<T> && Foo<T>;\n"
24057       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24058       "            };",
24059       Style);
24060 
24061   verifyFormat("template <typename T>\n"
24062                "concept HasFoo = requires(T t) {\n"
24063                "                   { t.foo() };\n"
24064                "                   t.foo();\n"
24065                "                 };\n"
24066                "template <typename T>\n"
24067                "concept HasBar = requires(T t) {\n"
24068                "                   { t.bar() };\n"
24069                "                   t.bar();\n"
24070                "                 };",
24071                Style);
24072 
24073   verifyFormat("template <typename T> concept True = true;", Style);
24074 
24075   verifyFormat("template <typename T>\n"
24076                "concept C = decltype([]() -> std::true_type { return {}; "
24077                "}())::value &&\n"
24078                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24079                Style);
24080 
24081   verifyFormat("template <typename T>\n"
24082                "concept Semiregular =\n"
24083                "    DefaultConstructible<T> && CopyConstructible<T> && "
24084                "CopyAssignable<T> &&\n"
24085                "    requires(T a, std::size_t n) {\n"
24086                "      requires Same<T *, decltype(&a)>;\n"
24087                "      { a.~T() } noexcept;\n"
24088                "      requires Same<T *, decltype(new T)>;\n"
24089                "      requires Same<T *, decltype(new T[n])>;\n"
24090                "      { delete new T; };\n"
24091                "      { delete new T[n]; };\n"
24092                "    };",
24093                Style);
24094 
24095   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
24096 
24097   verifyFormat("template <typename T> concept C =\n"
24098                "    requires(T t) {\n"
24099                "      requires Bar<T> && Foo<T>;\n"
24100                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24101                "    };",
24102                Style);
24103 
24104   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
24105                "                                         { t.foo() };\n"
24106                "                                         t.foo();\n"
24107                "                                       };\n"
24108                "template <typename T> concept HasBar = requires(T t) {\n"
24109                "                                         { t.bar() };\n"
24110                "                                         t.bar();\n"
24111                "                                       };",
24112                Style);
24113 
24114   verifyFormat("template <typename T> concept True = true;", Style);
24115 
24116   verifyFormat(
24117       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
24118       "                                    return {};\n"
24119       "                                  }())::value &&\n"
24120       "                                  requires(T t) { t.bar(); } && "
24121       "sizeof(T) <= 8;",
24122       Style);
24123 
24124   verifyFormat("template <typename T> concept Semiregular =\n"
24125                "    DefaultConstructible<T> && CopyConstructible<T> && "
24126                "CopyAssignable<T> &&\n"
24127                "    requires(T a, std::size_t n) {\n"
24128                "      requires Same<T *, decltype(&a)>;\n"
24129                "      { a.~T() } noexcept;\n"
24130                "      requires Same<T *, decltype(new T)>;\n"
24131                "      requires Same<T *, decltype(new T[n])>;\n"
24132                "      { delete new T; };\n"
24133                "      { delete new T[n]; };\n"
24134                "    };",
24135                Style);
24136 
24137   // The following tests are invalid C++, we just want to make sure we don't
24138   // assert.
24139   verifyFormat("template <typename T>\n"
24140                "concept C = requires C2<T>;");
24141 
24142   verifyFormat("template <typename T>\n"
24143                "concept C = 5 + 4;");
24144 
24145   verifyFormat("template <typename T>\n"
24146                "concept C =\n"
24147                "class X;");
24148 
24149   verifyFormat("template <typename T>\n"
24150                "concept C = [] && true;");
24151 
24152   verifyFormat("template <typename T>\n"
24153                "concept C = [] && requires(T t) { typename T::size_type; };");
24154 }
24155 
24156 TEST_F(FormatTest, RequiresClausesPositions) {
24157   auto Style = getLLVMStyle();
24158   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
24159   EXPECT_EQ(Style.IndentRequiresClause, true);
24160 
24161   verifyFormat("template <typename T>\n"
24162                "  requires(Foo<T> && std::trait<T>)\n"
24163                "struct Bar;",
24164                Style);
24165 
24166   verifyFormat("template <typename T>\n"
24167                "  requires(Foo<T> && std::trait<T>)\n"
24168                "class Bar {\n"
24169                "public:\n"
24170                "  Bar(T t);\n"
24171                "  bool baz();\n"
24172                "};",
24173                Style);
24174 
24175   verifyFormat(
24176       "template <typename T>\n"
24177       "  requires requires(T &&t) {\n"
24178       "             typename T::I;\n"
24179       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
24180       "           }\n"
24181       "Bar(T) -> Bar<typename T::I>;",
24182       Style);
24183 
24184   verifyFormat("template <typename T>\n"
24185                "  requires(Foo<T> && std::trait<T>)\n"
24186                "constexpr T MyGlobal;",
24187                Style);
24188 
24189   verifyFormat("template <typename T>\n"
24190                "  requires Foo<T> && requires(T t) {\n"
24191                "                       { t.baz() } -> std::same_as<bool>;\n"
24192                "                       requires std::same_as<T::Factor, int>;\n"
24193                "                     }\n"
24194                "inline int bar(T t) {\n"
24195                "  return t.baz() ? T::Factor : 5;\n"
24196                "}",
24197                Style);
24198 
24199   verifyFormat("template <typename T>\n"
24200                "inline int bar(T t)\n"
24201                "  requires Foo<T> && requires(T t) {\n"
24202                "                       { t.baz() } -> std::same_as<bool>;\n"
24203                "                       requires std::same_as<T::Factor, int>;\n"
24204                "                     }\n"
24205                "{\n"
24206                "  return t.baz() ? T::Factor : 5;\n"
24207                "}",
24208                Style);
24209 
24210   verifyFormat("template <typename T>\n"
24211                "  requires F<T>\n"
24212                "int bar(T t) {\n"
24213                "  return 5;\n"
24214                "}",
24215                Style);
24216 
24217   verifyFormat("template <typename T>\n"
24218                "int bar(T t)\n"
24219                "  requires F<T>\n"
24220                "{\n"
24221                "  return 5;\n"
24222                "}",
24223                Style);
24224 
24225   verifyFormat("template <typename T>\n"
24226                "int bar(T t)\n"
24227                "  requires F<T>;",
24228                Style);
24229 
24230   Style.IndentRequiresClause = false;
24231   verifyFormat("template <typename T>\n"
24232                "requires F<T>\n"
24233                "int bar(T t) {\n"
24234                "  return 5;\n"
24235                "}",
24236                Style);
24237 
24238   verifyFormat("template <typename T>\n"
24239                "int bar(T t)\n"
24240                "requires F<T>\n"
24241                "{\n"
24242                "  return 5;\n"
24243                "}",
24244                Style);
24245 
24246   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
24247   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
24248                "template <typename T> requires Foo<T> void bar() {}\n"
24249                "template <typename T> void bar() requires Foo<T> {}\n"
24250                "template <typename T> void bar() requires Foo<T>;\n"
24251                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
24252                Style);
24253 
24254   auto ColumnStyle = Style;
24255   ColumnStyle.ColumnLimit = 40;
24256   verifyFormat("template <typename AAAAAAA>\n"
24257                "requires Foo<T> struct Bar {};\n"
24258                "template <typename AAAAAAA>\n"
24259                "requires Foo<T> void bar() {}\n"
24260                "template <typename AAAAAAA>\n"
24261                "void bar() requires Foo<T> {}\n"
24262                "template <typename AAAAAAA>\n"
24263                "requires Foo<T> Baz(T) -> Baz<T>;",
24264                ColumnStyle);
24265 
24266   verifyFormat("template <typename T>\n"
24267                "requires Foo<AAAAAAA> struct Bar {};\n"
24268                "template <typename T>\n"
24269                "requires Foo<AAAAAAA> void bar() {}\n"
24270                "template <typename T>\n"
24271                "void bar() requires Foo<AAAAAAA> {}\n"
24272                "template <typename T>\n"
24273                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
24274                ColumnStyle);
24275 
24276   verifyFormat("template <typename AAAAAAA>\n"
24277                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24278                "struct Bar {};\n"
24279                "template <typename AAAAAAA>\n"
24280                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24281                "void bar() {}\n"
24282                "template <typename AAAAAAA>\n"
24283                "void bar()\n"
24284                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24285                "template <typename AAAAAAA>\n"
24286                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24287                "template <typename AAAAAAA>\n"
24288                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24289                "Bar(T) -> Bar<T>;",
24290                ColumnStyle);
24291 
24292   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24293   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24294 
24295   verifyFormat("template <typename T>\n"
24296                "requires Foo<T> struct Bar {};\n"
24297                "template <typename T>\n"
24298                "requires Foo<T> void bar() {}\n"
24299                "template <typename T>\n"
24300                "void bar()\n"
24301                "requires Foo<T> {}\n"
24302                "template <typename T>\n"
24303                "void bar()\n"
24304                "requires Foo<T>;\n"
24305                "template <typename T>\n"
24306                "requires Foo<T> Bar(T) -> Bar<T>;",
24307                Style);
24308 
24309   verifyFormat("template <typename AAAAAAA>\n"
24310                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24311                "struct Bar {};\n"
24312                "template <typename AAAAAAA>\n"
24313                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24314                "void bar() {}\n"
24315                "template <typename AAAAAAA>\n"
24316                "void bar()\n"
24317                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24318                "template <typename AAAAAAA>\n"
24319                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24320                "template <typename AAAAAAA>\n"
24321                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24322                "Bar(T) -> Bar<T>;",
24323                ColumnStyle);
24324 
24325   Style.IndentRequiresClause = true;
24326   ColumnStyle.IndentRequiresClause = true;
24327 
24328   verifyFormat("template <typename T>\n"
24329                "  requires Foo<T> struct Bar {};\n"
24330                "template <typename T>\n"
24331                "  requires Foo<T> void bar() {}\n"
24332                "template <typename T>\n"
24333                "void bar()\n"
24334                "  requires Foo<T> {}\n"
24335                "template <typename T>\n"
24336                "  requires Foo<T> Bar(T) -> Bar<T>;",
24337                Style);
24338 
24339   verifyFormat("template <typename AAAAAAA>\n"
24340                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24341                "struct Bar {};\n"
24342                "template <typename AAAAAAA>\n"
24343                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24344                "void bar() {}\n"
24345                "template <typename AAAAAAA>\n"
24346                "void bar()\n"
24347                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24348                "template <typename AAAAAAA>\n"
24349                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24350                "template <typename AAAAAAA>\n"
24351                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24352                "Bar(T) -> Bar<T>;",
24353                ColumnStyle);
24354 
24355   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24356   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24357 
24358   verifyFormat("template <typename T> requires Foo<T>\n"
24359                "struct Bar {};\n"
24360                "template <typename T> requires Foo<T>\n"
24361                "void bar() {}\n"
24362                "template <typename T>\n"
24363                "void bar() requires Foo<T>\n"
24364                "{}\n"
24365                "template <typename T> void bar() requires Foo<T>;\n"
24366                "template <typename T> requires Foo<T>\n"
24367                "Bar(T) -> Bar<T>;",
24368                Style);
24369 
24370   verifyFormat("template <typename AAAAAAA>\n"
24371                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24372                "struct Bar {};\n"
24373                "template <typename AAAAAAA>\n"
24374                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24375                "void bar() {}\n"
24376                "template <typename AAAAAAA>\n"
24377                "void bar()\n"
24378                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24379                "{}\n"
24380                "template <typename AAAAAAA>\n"
24381                "requires Foo<AAAAAAAA>\n"
24382                "Bar(T) -> Bar<T>;\n"
24383                "template <typename AAAAAAA>\n"
24384                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24385                "Bar(T) -> Bar<T>;",
24386                ColumnStyle);
24387 }
24388 
24389 TEST_F(FormatTest, RequiresClauses) {
24390   verifyFormat("struct [[nodiscard]] zero_t {\n"
24391                "  template <class T>\n"
24392                "    requires requires { number_zero_v<T>; }\n"
24393                "  [[nodiscard]] constexpr operator T() const {\n"
24394                "    return number_zero_v<T>;\n"
24395                "  }\n"
24396                "};");
24397 
24398   auto Style = getLLVMStyle();
24399 
24400   verifyFormat(
24401       "template <typename T>\n"
24402       "  requires is_default_constructible_v<hash<T>> and\n"
24403       "           is_copy_constructible_v<hash<T>> and\n"
24404       "           is_move_constructible_v<hash<T>> and\n"
24405       "           is_copy_assignable_v<hash<T>> and "
24406       "is_move_assignable_v<hash<T>> and\n"
24407       "           is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
24408       "           is_callable_v<hash<T>(T)> and\n"
24409       "           is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
24410       "           is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
24411       "           is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
24412       "struct S {};",
24413       Style);
24414 
24415   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
24416   verifyFormat(
24417       "template <typename T>\n"
24418       "  requires is_default_constructible_v<hash<T>>\n"
24419       "           and is_copy_constructible_v<hash<T>>\n"
24420       "           and is_move_constructible_v<hash<T>>\n"
24421       "           and is_copy_assignable_v<hash<T>> and "
24422       "is_move_assignable_v<hash<T>>\n"
24423       "           and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
24424       "           and is_callable_v<hash<T>(T)>\n"
24425       "           and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
24426       "           and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
24427       "           and is_same_v<size_t, decltype(hash<T>(declval<const T "
24428       "&>()))>\n"
24429       "struct S {};",
24430       Style);
24431 
24432   // Not a clause, but we once hit an assert.
24433   verifyFormat("#if 0\n"
24434                "#else\n"
24435                "foo();\n"
24436                "#endif\n"
24437                "bar(requires);");
24438 }
24439 
24440 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24441   FormatStyle Style = getLLVMStyle();
24442   StringRef Source = "void Foo::slot() {\n"
24443                      "  unsigned char MyChar = 'x';\n"
24444                      "  emit signal(MyChar);\n"
24445                      "  Q_EMIT signal(MyChar);\n"
24446                      "}";
24447 
24448   EXPECT_EQ(Source, format(Source, Style));
24449 
24450   Style.AlignConsecutiveDeclarations.Enabled = true;
24451   EXPECT_EQ("void Foo::slot() {\n"
24452             "  unsigned char MyChar = 'x';\n"
24453             "  emit          signal(MyChar);\n"
24454             "  Q_EMIT signal(MyChar);\n"
24455             "}",
24456             format(Source, Style));
24457 
24458   Style.StatementAttributeLikeMacros.push_back("emit");
24459   EXPECT_EQ(Source, format(Source, Style));
24460 
24461   Style.StatementAttributeLikeMacros = {};
24462   EXPECT_EQ("void Foo::slot() {\n"
24463             "  unsigned char MyChar = 'x';\n"
24464             "  emit          signal(MyChar);\n"
24465             "  Q_EMIT        signal(MyChar);\n"
24466             "}",
24467             format(Source, Style));
24468 }
24469 
24470 TEST_F(FormatTest, IndentAccessModifiers) {
24471   FormatStyle Style = getLLVMStyle();
24472   Style.IndentAccessModifiers = true;
24473   // Members are *two* levels below the record;
24474   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24475   verifyFormat("class C {\n"
24476                "    int i;\n"
24477                "};\n",
24478                Style);
24479   verifyFormat("union C {\n"
24480                "    int i;\n"
24481                "    unsigned u;\n"
24482                "};\n",
24483                Style);
24484   // Access modifiers should be indented one level below the record.
24485   verifyFormat("class C {\n"
24486                "  public:\n"
24487                "    int i;\n"
24488                "};\n",
24489                Style);
24490   verifyFormat("struct S {\n"
24491                "  private:\n"
24492                "    class C {\n"
24493                "        int j;\n"
24494                "\n"
24495                "      public:\n"
24496                "        C();\n"
24497                "    };\n"
24498                "\n"
24499                "  public:\n"
24500                "    int i;\n"
24501                "};\n",
24502                Style);
24503   // Enumerations are not records and should be unaffected.
24504   Style.AllowShortEnumsOnASingleLine = false;
24505   verifyFormat("enum class E {\n"
24506                "  A,\n"
24507                "  B\n"
24508                "};\n",
24509                Style);
24510   // Test with a different indentation width;
24511   // also proves that the result is Style.AccessModifierOffset agnostic.
24512   Style.IndentWidth = 3;
24513   verifyFormat("class C {\n"
24514                "   public:\n"
24515                "      int i;\n"
24516                "};\n",
24517                Style);
24518 }
24519 
24520 TEST_F(FormatTest, LimitlessStringsAndComments) {
24521   auto Style = getLLVMStyleWithColumns(0);
24522   constexpr StringRef Code =
24523       "/**\n"
24524       " * This is a multiline comment with quite some long lines, at least for "
24525       "the LLVM Style.\n"
24526       " * We will redo this with strings and line comments. Just to  check if "
24527       "everything is working.\n"
24528       " */\n"
24529       "bool foo() {\n"
24530       "  /* Single line multi line comment. */\n"
24531       "  const std::string String = \"This is a multiline string with quite "
24532       "some long lines, at least for the LLVM Style.\"\n"
24533       "                             \"We already did it with multi line "
24534       "comments, and we will do it with line comments. Just to check if "
24535       "everything is working.\";\n"
24536       "  // This is a line comment (block) with quite some long lines, at "
24537       "least for the LLVM Style.\n"
24538       "  // We already did this with multi line comments and strings. Just to "
24539       "check if everything is working.\n"
24540       "  const std::string SmallString = \"Hello World\";\n"
24541       "  // Small line comment\n"
24542       "  return String.size() > SmallString.size();\n"
24543       "}";
24544   EXPECT_EQ(Code, format(Code, Style));
24545 }
24546 
24547 TEST_F(FormatTest, FormatDecayCopy) {
24548   // error cases from unit tests
24549   verifyFormat("foo(auto())");
24550   verifyFormat("foo(auto{})");
24551   verifyFormat("foo(auto({}))");
24552   verifyFormat("foo(auto{{}})");
24553 
24554   verifyFormat("foo(auto(1))");
24555   verifyFormat("foo(auto{1})");
24556   verifyFormat("foo(new auto(1))");
24557   verifyFormat("foo(new auto{1})");
24558   verifyFormat("decltype(auto(1)) x;");
24559   verifyFormat("decltype(auto{1}) x;");
24560   verifyFormat("auto(x);");
24561   verifyFormat("auto{x};");
24562   verifyFormat("new auto{x};");
24563   verifyFormat("auto{x} = y;");
24564   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24565                                 // the user's own fault
24566   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24567                                          // clearly the user's own fault
24568   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24569 }
24570 
24571 TEST_F(FormatTest, Cpp20ModulesSupport) {
24572   FormatStyle Style = getLLVMStyle();
24573   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24574   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24575 
24576   verifyFormat("export import foo;", Style);
24577   verifyFormat("export import foo:bar;", Style);
24578   verifyFormat("export import foo.bar;", Style);
24579   verifyFormat("export import foo.bar:baz;", Style);
24580   verifyFormat("export import :bar;", Style);
24581   verifyFormat("export module foo:bar;", Style);
24582   verifyFormat("export module foo;", Style);
24583   verifyFormat("export module foo.bar;", Style);
24584   verifyFormat("export module foo.bar:baz;", Style);
24585   verifyFormat("export import <string_view>;", Style);
24586 
24587   verifyFormat("export type_name var;", Style);
24588   verifyFormat("template <class T> export using A = B<T>;", Style);
24589   verifyFormat("export using A = B;", Style);
24590   verifyFormat("export int func() {\n"
24591                "  foo();\n"
24592                "}",
24593                Style);
24594   verifyFormat("export struct {\n"
24595                "  int foo;\n"
24596                "};",
24597                Style);
24598   verifyFormat("export {\n"
24599                "  int foo;\n"
24600                "};",
24601                Style);
24602   verifyFormat("export export char const *hello() { return \"hello\"; }");
24603 
24604   verifyFormat("import bar;", Style);
24605   verifyFormat("import foo.bar;", Style);
24606   verifyFormat("import foo:bar;", Style);
24607   verifyFormat("import :bar;", Style);
24608   verifyFormat("import <ctime>;", Style);
24609   verifyFormat("import \"header\";", Style);
24610 
24611   verifyFormat("module foo;", Style);
24612   verifyFormat("module foo:bar;", Style);
24613   verifyFormat("module foo.bar;", Style);
24614   verifyFormat("module;", Style);
24615 
24616   verifyFormat("export namespace hi {\n"
24617                "const char *sayhi();\n"
24618                "}",
24619                Style);
24620 
24621   verifyFormat("module :private;", Style);
24622   verifyFormat("import <foo/bar.h>;", Style);
24623   verifyFormat("import foo...bar;", Style);
24624   verifyFormat("import ..........;", Style);
24625   verifyFormat("module foo:private;", Style);
24626   verifyFormat("import a", Style);
24627   verifyFormat("module a", Style);
24628   verifyFormat("export import a", Style);
24629   verifyFormat("export module a", Style);
24630 
24631   verifyFormat("import", Style);
24632   verifyFormat("module", Style);
24633   verifyFormat("export", Style);
24634 }
24635 
24636 TEST_F(FormatTest, CoroutineForCoawait) {
24637   FormatStyle Style = getLLVMStyle();
24638   verifyFormat("for co_await (auto x : range())\n  ;");
24639   verifyFormat("for (auto i : arr) {\n"
24640                "}",
24641                Style);
24642   verifyFormat("for co_await (auto i : arr) {\n"
24643                "}",
24644                Style);
24645   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24646                "}",
24647                Style);
24648 }
24649 
24650 TEST_F(FormatTest, CoroutineCoAwait) {
24651   verifyFormat("int x = co_await foo();");
24652   verifyFormat("int x = (co_await foo());");
24653   verifyFormat("co_await (42);");
24654   verifyFormat("void operator co_await(int);");
24655   verifyFormat("void operator co_await(a);");
24656   verifyFormat("co_await a;");
24657   verifyFormat("co_await missing_await_resume{};");
24658   verifyFormat("co_await a; // comment");
24659   verifyFormat("void test0() { co_await a; }");
24660   verifyFormat("co_await co_await co_await foo();");
24661   verifyFormat("co_await foo().bar();");
24662   verifyFormat("co_await [this]() -> Task { co_return x; }");
24663   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24664                "foo(); }(x, y);");
24665 
24666   FormatStyle Style = getLLVMStyleWithColumns(40);
24667   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24668                "  co_return co_await foo();\n"
24669                "}(x, y);",
24670                Style);
24671   verifyFormat("co_await;");
24672 }
24673 
24674 TEST_F(FormatTest, CoroutineCoYield) {
24675   verifyFormat("int x = co_yield foo();");
24676   verifyFormat("int x = (co_yield foo());");
24677   verifyFormat("co_yield (42);");
24678   verifyFormat("co_yield {42};");
24679   verifyFormat("co_yield 42;");
24680   verifyFormat("co_yield n++;");
24681   verifyFormat("co_yield ++n;");
24682   verifyFormat("co_yield;");
24683 }
24684 
24685 TEST_F(FormatTest, CoroutineCoReturn) {
24686   verifyFormat("co_return (42);");
24687   verifyFormat("co_return;");
24688   verifyFormat("co_return {};");
24689   verifyFormat("co_return x;");
24690   verifyFormat("co_return co_await foo();");
24691   verifyFormat("co_return co_yield foo();");
24692 }
24693 
24694 TEST_F(FormatTest, EmptyShortBlock) {
24695   auto Style = getLLVMStyle();
24696   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24697 
24698   verifyFormat("try {\n"
24699                "  doA();\n"
24700                "} catch (Exception &e) {\n"
24701                "  e.printStackTrace();\n"
24702                "}\n",
24703                Style);
24704 
24705   verifyFormat("try {\n"
24706                "  doA();\n"
24707                "} catch (Exception &e) {}\n",
24708                Style);
24709 }
24710 
24711 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
24712   auto Style = getLLVMStyle();
24713 
24714   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
24715   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
24716   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
24717   verifyFormat("struct Y<[] { return 0; }> {};", Style);
24718 
24719   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
24720   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
24721 }
24722 
24723 TEST_F(FormatTest, InsertBraces) {
24724   FormatStyle Style = getLLVMStyle();
24725   Style.InsertBraces = true;
24726 
24727   verifyFormat("// clang-format off\n"
24728                "// comment\n"
24729                "if (a) f();\n"
24730                "// clang-format on\n"
24731                "if (b) {\n"
24732                "  g();\n"
24733                "}",
24734                "// clang-format off\n"
24735                "// comment\n"
24736                "if (a) f();\n"
24737                "// clang-format on\n"
24738                "if (b) g();",
24739                Style);
24740 
24741   verifyFormat("if (a) {\n"
24742                "  switch (b) {\n"
24743                "  case 1:\n"
24744                "    c = 0;\n"
24745                "    break;\n"
24746                "  default:\n"
24747                "    c = 1;\n"
24748                "  }\n"
24749                "}",
24750                "if (a)\n"
24751                "  switch (b) {\n"
24752                "  case 1:\n"
24753                "    c = 0;\n"
24754                "    break;\n"
24755                "  default:\n"
24756                "    c = 1;\n"
24757                "  }",
24758                Style);
24759 
24760   verifyFormat("for (auto node : nodes) {\n"
24761                "  if (node) {\n"
24762                "    break;\n"
24763                "  }\n"
24764                "}",
24765                "for (auto node : nodes)\n"
24766                "  if (node)\n"
24767                "    break;",
24768                Style);
24769 
24770   verifyFormat("for (auto node : nodes) {\n"
24771                "  if (node)\n"
24772                "}",
24773                "for (auto node : nodes)\n"
24774                "  if (node)",
24775                Style);
24776 
24777   verifyFormat("do {\n"
24778                "  --a;\n"
24779                "} while (a);",
24780                "do\n"
24781                "  --a;\n"
24782                "while (a);",
24783                Style);
24784 
24785   verifyFormat("if (i) {\n"
24786                "  ++i;\n"
24787                "} else {\n"
24788                "  --i;\n"
24789                "}",
24790                "if (i)\n"
24791                "  ++i;\n"
24792                "else {\n"
24793                "  --i;\n"
24794                "}",
24795                Style);
24796 
24797   verifyFormat("void f() {\n"
24798                "  while (j--) {\n"
24799                "    while (i) {\n"
24800                "      --i;\n"
24801                "    }\n"
24802                "  }\n"
24803                "}",
24804                "void f() {\n"
24805                "  while (j--)\n"
24806                "    while (i)\n"
24807                "      --i;\n"
24808                "}",
24809                Style);
24810 
24811   verifyFormat("f({\n"
24812                "  if (a) {\n"
24813                "    g();\n"
24814                "  }\n"
24815                "});",
24816                "f({\n"
24817                "  if (a)\n"
24818                "    g();\n"
24819                "});",
24820                Style);
24821 
24822   verifyFormat("if (a) {\n"
24823                "  f();\n"
24824                "} else if (b) {\n"
24825                "  g();\n"
24826                "} else {\n"
24827                "  h();\n"
24828                "}",
24829                "if (a)\n"
24830                "  f();\n"
24831                "else if (b)\n"
24832                "  g();\n"
24833                "else\n"
24834                "  h();",
24835                Style);
24836 
24837   verifyFormat("if (a) {\n"
24838                "  f();\n"
24839                "}\n"
24840                "// comment\n"
24841                "/* comment */",
24842                "if (a)\n"
24843                "  f();\n"
24844                "// comment\n"
24845                "/* comment */",
24846                Style);
24847 
24848   verifyFormat("if (a) {\n"
24849                "  // foo\n"
24850                "  // bar\n"
24851                "  f();\n"
24852                "}",
24853                "if (a)\n"
24854                "  // foo\n"
24855                "  // bar\n"
24856                "  f();",
24857                Style);
24858 
24859   verifyFormat("if (a) { // comment\n"
24860                "  // comment\n"
24861                "  f();\n"
24862                "}",
24863                "if (a) // comment\n"
24864                "  // comment\n"
24865                "  f();",
24866                Style);
24867 
24868   verifyFormat("if (a) {\n"
24869                "  f(); // comment\n"
24870                "}",
24871                "if (a)\n"
24872                "  f(); // comment",
24873                Style);
24874 
24875   verifyFormat("if (a) {\n"
24876                "  f();\n"
24877                "}\n"
24878                "#undef A\n"
24879                "#undef B",
24880                "if (a)\n"
24881                "  f();\n"
24882                "#undef A\n"
24883                "#undef B",
24884                Style);
24885 
24886   verifyFormat("if (a)\n"
24887                "#ifdef A\n"
24888                "  f();\n"
24889                "#else\n"
24890                "  g();\n"
24891                "#endif",
24892                Style);
24893 
24894   verifyFormat("#if 0\n"
24895                "#elif 1\n"
24896                "#endif\n"
24897                "void f() {\n"
24898                "  if (a) {\n"
24899                "    g();\n"
24900                "  }\n"
24901                "}",
24902                "#if 0\n"
24903                "#elif 1\n"
24904                "#endif\n"
24905                "void f() {\n"
24906                "  if (a) g();\n"
24907                "}",
24908                Style);
24909 
24910   Style.ColumnLimit = 15;
24911 
24912   verifyFormat("#define A     \\\n"
24913                "  if (a)      \\\n"
24914                "    f();",
24915                Style);
24916 
24917   verifyFormat("if (a + b >\n"
24918                "    c) {\n"
24919                "  f();\n"
24920                "}",
24921                "if (a + b > c)\n"
24922                "  f();",
24923                Style);
24924 }
24925 
24926 TEST_F(FormatTest, RemoveBraces) {
24927   FormatStyle Style = getLLVMStyle();
24928   Style.RemoveBracesLLVM = true;
24929 
24930   // The following eight test cases are fully-braced versions of the examples at
24931   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
24932   // statement-bodies-of-if-else-loop-statements".
24933 
24934   // 1. Omit the braces, since the body is simple and clearly associated with
24935   // the if.
24936   verifyFormat("if (isa<FunctionDecl>(D))\n"
24937                "  handleFunctionDecl(D);\n"
24938                "else if (isa<VarDecl>(D))\n"
24939                "  handleVarDecl(D);",
24940                "if (isa<FunctionDecl>(D)) {\n"
24941                "  handleFunctionDecl(D);\n"
24942                "} else if (isa<VarDecl>(D)) {\n"
24943                "  handleVarDecl(D);\n"
24944                "}",
24945                Style);
24946 
24947   // 2. Here we document the condition itself and not the body.
24948   verifyFormat("if (isa<VarDecl>(D)) {\n"
24949                "  // It is necessary that we explain the situation with this\n"
24950                "  // surprisingly long comment, so it would be unclear\n"
24951                "  // without the braces whether the following statement is in\n"
24952                "  // the scope of the `if`.\n"
24953                "  // Because the condition is documented, we can't really\n"
24954                "  // hoist this comment that applies to the body above the\n"
24955                "  // if.\n"
24956                "  handleOtherDecl(D);\n"
24957                "}",
24958                Style);
24959 
24960   // 3. Use braces on the outer `if` to avoid a potential dangling else
24961   // situation.
24962   verifyFormat("if (isa<VarDecl>(D)) {\n"
24963                "  for (auto *A : D.attrs())\n"
24964                "    if (shouldProcessAttr(A))\n"
24965                "      handleAttr(A);\n"
24966                "}",
24967                "if (isa<VarDecl>(D)) {\n"
24968                "  for (auto *A : D.attrs()) {\n"
24969                "    if (shouldProcessAttr(A)) {\n"
24970                "      handleAttr(A);\n"
24971                "    }\n"
24972                "  }\n"
24973                "}",
24974                Style);
24975 
24976   // 4. Use braces for the `if` block to keep it uniform with the else block.
24977   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24978                "  handleFunctionDecl(D);\n"
24979                "} else {\n"
24980                "  // In this else case, it is necessary that we explain the\n"
24981                "  // situation with this surprisingly long comment, so it\n"
24982                "  // would be unclear without the braces whether the\n"
24983                "  // following statement is in the scope of the `if`.\n"
24984                "  handleOtherDecl(D);\n"
24985                "}",
24986                Style);
24987 
24988   // 5. This should also omit braces.  The `for` loop contains only a single
24989   // statement, so it shouldn't have braces.  The `if` also only contains a
24990   // single simple statement (the for loop), so it also should omit braces.
24991   verifyFormat("if (isa<FunctionDecl>(D))\n"
24992                "  for (auto *A : D.attrs())\n"
24993                "    handleAttr(A);",
24994                "if (isa<FunctionDecl>(D)) {\n"
24995                "  for (auto *A : D.attrs()) {\n"
24996                "    handleAttr(A);\n"
24997                "  }\n"
24998                "}",
24999                Style);
25000 
25001   // 6. Use braces for the outer `if` since the nested `for` is braced.
25002   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25003                "  for (auto *A : D.attrs()) {\n"
25004                "    // In this for loop body, it is necessary that we explain\n"
25005                "    // the situation with this surprisingly long comment,\n"
25006                "    // forcing braces on the `for` block.\n"
25007                "    handleAttr(A);\n"
25008                "  }\n"
25009                "}",
25010                Style);
25011 
25012   // 7. Use braces on the outer block because there are more than two levels of
25013   // nesting.
25014   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25015                "  for (auto *A : D.attrs())\n"
25016                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
25017                "      handleAttrOnDecl(D, A, i);\n"
25018                "}",
25019                "if (isa<FunctionDecl>(D)) {\n"
25020                "  for (auto *A : D.attrs()) {\n"
25021                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
25022                "      handleAttrOnDecl(D, A, i);\n"
25023                "    }\n"
25024                "  }\n"
25025                "}",
25026                Style);
25027 
25028   // 8. Use braces on the outer block because of a nested `if`, otherwise the
25029   // compiler would warn: `add explicit braces to avoid dangling else`
25030   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25031                "  if (shouldProcess(D))\n"
25032                "    handleVarDecl(D);\n"
25033                "  else\n"
25034                "    markAsIgnored(D);\n"
25035                "}",
25036                "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                "  }\n"
25042                "}",
25043                Style);
25044 
25045   verifyFormat("// clang-format off\n"
25046                "// comment\n"
25047                "while (i > 0) { --i; }\n"
25048                "// clang-format on\n"
25049                "while (j < 0)\n"
25050                "  ++j;",
25051                "// clang-format off\n"
25052                "// comment\n"
25053                "while (i > 0) { --i; }\n"
25054                "// clang-format on\n"
25055                "while (j < 0) { ++j; }",
25056                Style);
25057 
25058   verifyFormat("if (a)\n"
25059                "  b; // comment\n"
25060                "else if (c)\n"
25061                "  d; /* comment */\n"
25062                "else\n"
25063                "  e;",
25064                "if (a) {\n"
25065                "  b; // comment\n"
25066                "} else if (c) {\n"
25067                "  d; /* comment */\n"
25068                "} else {\n"
25069                "  e;\n"
25070                "}",
25071                Style);
25072 
25073   verifyFormat("if (a) {\n"
25074                "  b;\n"
25075                "  c;\n"
25076                "} else if (d) {\n"
25077                "  e;\n"
25078                "}",
25079                Style);
25080 
25081   verifyFormat("if (a) {\n"
25082                "#undef NDEBUG\n"
25083                "  b;\n"
25084                "} else {\n"
25085                "  c;\n"
25086                "}",
25087                Style);
25088 
25089   verifyFormat("if (a) {\n"
25090                "  // comment\n"
25091                "} else if (b) {\n"
25092                "  c;\n"
25093                "}",
25094                Style);
25095 
25096   verifyFormat("if (a) {\n"
25097                "  b;\n"
25098                "} else {\n"
25099                "  { c; }\n"
25100                "}",
25101                Style);
25102 
25103   verifyFormat("if (a) {\n"
25104                "  if (b) // comment\n"
25105                "    c;\n"
25106                "} else if (d) {\n"
25107                "  e;\n"
25108                "}",
25109                "if (a) {\n"
25110                "  if (b) { // comment\n"
25111                "    c;\n"
25112                "  }\n"
25113                "} else if (d) {\n"
25114                "  e;\n"
25115                "}",
25116                Style);
25117 
25118   verifyFormat("if (a) {\n"
25119                "  if (b) {\n"
25120                "    c;\n"
25121                "    // comment\n"
25122                "  } else if (d) {\n"
25123                "    e;\n"
25124                "  }\n"
25125                "}",
25126                Style);
25127 
25128   verifyFormat("if (a) {\n"
25129                "  if (b)\n"
25130                "    c;\n"
25131                "}",
25132                "if (a) {\n"
25133                "  if (b) {\n"
25134                "    c;\n"
25135                "  }\n"
25136                "}",
25137                Style);
25138 
25139   verifyFormat("if (a)\n"
25140                "  if (b)\n"
25141                "    c;\n"
25142                "  else\n"
25143                "    d;\n"
25144                "else\n"
25145                "  e;",
25146                "if (a) {\n"
25147                "  if (b) {\n"
25148                "    c;\n"
25149                "  } else {\n"
25150                "    d;\n"
25151                "  }\n"
25152                "} else {\n"
25153                "  e;\n"
25154                "}",
25155                Style);
25156 
25157   verifyFormat("if (a) {\n"
25158                "  // comment\n"
25159                "  if (b)\n"
25160                "    c;\n"
25161                "  else if (d)\n"
25162                "    e;\n"
25163                "} else {\n"
25164                "  g;\n"
25165                "}",
25166                "if (a) {\n"
25167                "  // comment\n"
25168                "  if (b) {\n"
25169                "    c;\n"
25170                "  } else if (d) {\n"
25171                "    e;\n"
25172                "  }\n"
25173                "} else {\n"
25174                "  g;\n"
25175                "}",
25176                Style);
25177 
25178   verifyFormat("if (a)\n"
25179                "  b;\n"
25180                "else if (c)\n"
25181                "  d;\n"
25182                "else\n"
25183                "  e;",
25184                "if (a) {\n"
25185                "  b;\n"
25186                "} else {\n"
25187                "  if (c) {\n"
25188                "    d;\n"
25189                "  } else {\n"
25190                "    e;\n"
25191                "  }\n"
25192                "}",
25193                Style);
25194 
25195   verifyFormat("if (a) {\n"
25196                "  if (b)\n"
25197                "    c;\n"
25198                "  else if (d)\n"
25199                "    e;\n"
25200                "} else {\n"
25201                "  g;\n"
25202                "}",
25203                "if (a) {\n"
25204                "  if (b)\n"
25205                "    c;\n"
25206                "  else {\n"
25207                "    if (d)\n"
25208                "      e;\n"
25209                "  }\n"
25210                "} else {\n"
25211                "  g;\n"
25212                "}",
25213                Style);
25214 
25215   verifyFormat("if (a)\n"
25216                "  b;\n"
25217                "else if (c)\n"
25218                "  while (d)\n"
25219                "    e;\n"
25220                "// comment",
25221                "if (a)\n"
25222                "{\n"
25223                "  b;\n"
25224                "} else if (c) {\n"
25225                "  while (d) {\n"
25226                "    e;\n"
25227                "  }\n"
25228                "}\n"
25229                "// comment",
25230                Style);
25231 
25232   verifyFormat("if (a) {\n"
25233                "  b;\n"
25234                "} else if (c) {\n"
25235                "  d;\n"
25236                "} else {\n"
25237                "  e;\n"
25238                "  g;\n"
25239                "}",
25240                Style);
25241 
25242   verifyFormat("if (a) {\n"
25243                "  b;\n"
25244                "} else if (c) {\n"
25245                "  d;\n"
25246                "} else {\n"
25247                "  e;\n"
25248                "} // comment",
25249                Style);
25250 
25251   verifyFormat("int abs = [](int i) {\n"
25252                "  if (i >= 0)\n"
25253                "    return i;\n"
25254                "  return -i;\n"
25255                "};",
25256                "int abs = [](int i) {\n"
25257                "  if (i >= 0) {\n"
25258                "    return i;\n"
25259                "  }\n"
25260                "  return -i;\n"
25261                "};",
25262                Style);
25263 
25264   verifyFormat("if (a)\n"
25265                "  foo();\n"
25266                "else\n"
25267                "  bar();",
25268                "if (a)\n"
25269                "{\n"
25270                "  foo();\n"
25271                "}\n"
25272                "else\n"
25273                "{\n"
25274                "  bar();\n"
25275                "}",
25276                Style);
25277 
25278   verifyFormat("if (a) {\n"
25279                "Label:\n"
25280                "}",
25281                Style);
25282 
25283   verifyFormat("if (a) {\n"
25284                "Label:\n"
25285                "  f();\n"
25286                "}",
25287                Style);
25288 
25289   verifyFormat("if (a) {\n"
25290                "  f();\n"
25291                "Label:\n"
25292                "}",
25293                Style);
25294 
25295   // FIXME: See https://github.com/llvm/llvm-project/issues/53543.
25296 #if 0
25297   Style.ColumnLimit = 65;
25298 
25299   verifyFormat("if (condition) {\n"
25300                "  ff(Indices,\n"
25301                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25302                "} else {\n"
25303                "  ff(Indices,\n"
25304                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25305                "}",
25306                Style);
25307 
25308   Style.ColumnLimit = 20;
25309 
25310   verifyFormat("if (a) {\n"
25311                "  b = c + // 1 -\n"
25312                "      d;\n"
25313                "}",
25314                Style);
25315 
25316   verifyFormat("if (a) {\n"
25317                "  b = c >= 0 ? d\n"
25318                "             : e;\n"
25319                "}",
25320                "if (a) {\n"
25321                "  b = c >= 0 ? d : e;\n"
25322                "}",
25323                Style);
25324 #endif
25325 
25326   Style.ColumnLimit = 20;
25327 
25328   verifyFormat("if (a)\n"
25329                "  b = c > 0 ? d : e;",
25330                "if (a) {\n"
25331                "  b = c > 0 ? d : e;\n"
25332                "}",
25333                Style);
25334 
25335   Style.ColumnLimit = 0;
25336 
25337   verifyFormat("if (a)\n"
25338                "  b234567890223456789032345678904234567890 = "
25339                "c234567890223456789032345678904234567890;",
25340                "if (a) {\n"
25341                "  b234567890223456789032345678904234567890 = "
25342                "c234567890223456789032345678904234567890;\n"
25343                "}",
25344                Style);
25345 }
25346 
25347 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
25348   auto Style = getLLVMStyle();
25349 
25350   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
25351                     "void functionDecl(int a, int b, int c);";
25352 
25353   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25354                      "paramF, paramG, paramH, paramI);\n"
25355                      "void functionDecl(int argumentA, int argumentB, int "
25356                      "argumentC, int argumentD, int argumentE);";
25357 
25358   verifyFormat(Short, Style);
25359 
25360   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25361                       "paramF, paramG, paramH,\n"
25362                       "             paramI);\n"
25363                       "void functionDecl(int argumentA, int argumentB, int "
25364                       "argumentC, int argumentD,\n"
25365                       "                  int argumentE);";
25366 
25367   verifyFormat(NoBreak, Medium, Style);
25368   verifyFormat(NoBreak,
25369                "functionCall(\n"
25370                "    paramA,\n"
25371                "    paramB,\n"
25372                "    paramC,\n"
25373                "    paramD,\n"
25374                "    paramE,\n"
25375                "    paramF,\n"
25376                "    paramG,\n"
25377                "    paramH,\n"
25378                "    paramI\n"
25379                ");\n"
25380                "void functionDecl(\n"
25381                "    int argumentA,\n"
25382                "    int argumentB,\n"
25383                "    int argumentC,\n"
25384                "    int argumentD,\n"
25385                "    int argumentE\n"
25386                ");",
25387                Style);
25388 
25389   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
25390                "                  nestedLongFunctionCall(argument1, "
25391                "argument2, argument3,\n"
25392                "                                         argument4, "
25393                "argument5));",
25394                Style);
25395 
25396   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25397 
25398   verifyFormat(Short, Style);
25399   verifyFormat(
25400       "functionCall(\n"
25401       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25402       "paramI\n"
25403       ");\n"
25404       "void functionDecl(\n"
25405       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25406       "argumentE\n"
25407       ");",
25408       Medium, Style);
25409 
25410   Style.AllowAllArgumentsOnNextLine = false;
25411   Style.AllowAllParametersOfDeclarationOnNextLine = false;
25412 
25413   verifyFormat(Short, Style);
25414   verifyFormat(
25415       "functionCall(\n"
25416       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25417       "paramI\n"
25418       ");\n"
25419       "void functionDecl(\n"
25420       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25421       "argumentE\n"
25422       ");",
25423       Medium, Style);
25424 
25425   Style.BinPackArguments = false;
25426   Style.BinPackParameters = false;
25427 
25428   verifyFormat(Short, Style);
25429 
25430   verifyFormat("functionCall(\n"
25431                "    paramA,\n"
25432                "    paramB,\n"
25433                "    paramC,\n"
25434                "    paramD,\n"
25435                "    paramE,\n"
25436                "    paramF,\n"
25437                "    paramG,\n"
25438                "    paramH,\n"
25439                "    paramI\n"
25440                ");\n"
25441                "void functionDecl(\n"
25442                "    int argumentA,\n"
25443                "    int argumentB,\n"
25444                "    int argumentC,\n"
25445                "    int argumentD,\n"
25446                "    int argumentE\n"
25447                ");",
25448                Medium, Style);
25449 
25450   verifyFormat("outerFunctionCall(\n"
25451                "    nestedFunctionCall(argument1),\n"
25452                "    nestedLongFunctionCall(\n"
25453                "        argument1,\n"
25454                "        argument2,\n"
25455                "        argument3,\n"
25456                "        argument4,\n"
25457                "        argument5\n"
25458                "    )\n"
25459                ");",
25460                Style);
25461 
25462   verifyFormat("int a = (int)b;", Style);
25463   verifyFormat("int a = (int)b;",
25464                "int a = (\n"
25465                "    int\n"
25466                ") b;",
25467                Style);
25468 
25469   verifyFormat("return (true);", Style);
25470   verifyFormat("return (true);",
25471                "return (\n"
25472                "    true\n"
25473                ");",
25474                Style);
25475 
25476   verifyFormat("void foo();", Style);
25477   verifyFormat("void foo();",
25478                "void foo(\n"
25479                ");",
25480                Style);
25481 
25482   verifyFormat("void foo() {}", Style);
25483   verifyFormat("void foo() {}",
25484                "void foo(\n"
25485                ") {\n"
25486                "}",
25487                Style);
25488 
25489   verifyFormat("auto string = std::string();", Style);
25490   verifyFormat("auto string = std::string();",
25491                "auto string = std::string(\n"
25492                ");",
25493                Style);
25494 
25495   verifyFormat("void (*functionPointer)() = nullptr;", Style);
25496   verifyFormat("void (*functionPointer)() = nullptr;",
25497                "void (\n"
25498                "    *functionPointer\n"
25499                ")\n"
25500                "(\n"
25501                ") = nullptr;",
25502                Style);
25503 }
25504 
25505 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
25506   auto Style = getLLVMStyle();
25507 
25508   verifyFormat("if (foo()) {\n"
25509                "  return;\n"
25510                "}",
25511                Style);
25512 
25513   verifyFormat("if (quitelongarg !=\n"
25514                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25515                "comment\n"
25516                "  return;\n"
25517                "}",
25518                Style);
25519 
25520   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25521 
25522   verifyFormat("if (foo()) {\n"
25523                "  return;\n"
25524                "}",
25525                Style);
25526 
25527   verifyFormat("if (quitelongarg !=\n"
25528                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25529                "comment\n"
25530                "  return;\n"
25531                "}",
25532                Style);
25533 }
25534 
25535 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
25536   auto Style = getLLVMStyle();
25537 
25538   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25539                "  doSomething();\n"
25540                "}",
25541                Style);
25542 
25543   verifyFormat("for (int myReallyLongCountVariable = 0; "
25544                "myReallyLongCountVariable < count;\n"
25545                "     myReallyLongCountVariable++) {\n"
25546                "  doSomething();\n"
25547                "}",
25548                Style);
25549 
25550   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25551 
25552   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25553                "  doSomething();\n"
25554                "}",
25555                Style);
25556 
25557   verifyFormat("for (int myReallyLongCountVariable = 0; "
25558                "myReallyLongCountVariable < count;\n"
25559                "     myReallyLongCountVariable++) {\n"
25560                "  doSomething();\n"
25561                "}",
25562                Style);
25563 }
25564 
25565 TEST_F(FormatTest, UnderstandsDigraphs) {
25566   verifyFormat("int arr<:5:> = {};");
25567   verifyFormat("int arr[5] = <%%>;");
25568   verifyFormat("int arr<:::qualified_variable:> = {};");
25569   verifyFormat("int arr[::qualified_variable] = <%%>;");
25570   verifyFormat("%:include <header>");
25571   verifyFormat("%:define A x##y");
25572   verifyFormat("#define A x%:%:y");
25573 }
25574 
25575 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
25576   auto Style = getLLVMStyle();
25577   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
25578   Style.AlignConsecutiveAssignments.Enabled = true;
25579   Style.AlignConsecutiveDeclarations.Enabled = true;
25580 
25581   // The AlignArray code is incorrect for non square Arrays and can cause
25582   // crashes, these tests assert that the array is not changed but will
25583   // also act as regression tests for when it is properly fixed
25584   verifyFormat("struct test demo[] = {\n"
25585                "    {1, 2},\n"
25586                "    {3, 4, 5},\n"
25587                "    {6, 7, 8}\n"
25588                "};",
25589                Style);
25590   verifyFormat("struct test demo[] = {\n"
25591                "    {1, 2, 3, 4, 5},\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, 9, 10, 11, 12}\n"
25600                "};",
25601                Style);
25602   verifyFormat("struct test demo[] = {\n"
25603                "    {1, 2, 3},\n"
25604                "    {3, 4, 5},\n"
25605                "    {6, 7, 8, 9, 10, 11, 12}\n"
25606                "};",
25607                Style);
25608 
25609   verifyFormat("S{\n"
25610                "    {},\n"
25611                "    {},\n"
25612                "    {a, b}\n"
25613                "};",
25614                Style);
25615   verifyFormat("S{\n"
25616                "    {},\n"
25617                "    {},\n"
25618                "    {a, b},\n"
25619                "};",
25620                Style);
25621   verifyFormat("void foo() {\n"
25622                "  auto thing = test{\n"
25623                "      {\n"
25624                "       {13}, {something}, // A\n"
25625                "      }\n"
25626                "  };\n"
25627                "}",
25628                "void foo() {\n"
25629                "  auto thing = test{\n"
25630                "      {\n"
25631                "       {13},\n"
25632                "       {something}, // A\n"
25633                "      }\n"
25634                "  };\n"
25635                "}",
25636                Style);
25637 }
25638 
25639 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
25640   auto Style = getLLVMStyle();
25641   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
25642   Style.AlignConsecutiveAssignments.Enabled = true;
25643   Style.AlignConsecutiveDeclarations.Enabled = true;
25644 
25645   // The AlignArray code is incorrect for non square Arrays and can cause
25646   // crashes, these tests assert that the array is not changed but will
25647   // also act as regression tests for when it is properly fixed
25648   verifyFormat("struct test demo[] = {\n"
25649                "    {1, 2},\n"
25650                "    {3, 4, 5},\n"
25651                "    {6, 7, 8}\n"
25652                "};",
25653                Style);
25654   verifyFormat("struct test demo[] = {\n"
25655                "    {1, 2, 3, 4, 5},\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, 9, 10, 11, 12}\n"
25664                "};",
25665                Style);
25666   verifyFormat("struct test demo[] = {\n"
25667                "    {1, 2, 3},\n"
25668                "    {3, 4, 5},\n"
25669                "    {6, 7, 8, 9, 10, 11, 12}\n"
25670                "};",
25671                Style);
25672 
25673   verifyFormat("S{\n"
25674                "    {},\n"
25675                "    {},\n"
25676                "    {a, b}\n"
25677                "};",
25678                Style);
25679   verifyFormat("S{\n"
25680                "    {},\n"
25681                "    {},\n"
25682                "    {a, b},\n"
25683                "};",
25684                Style);
25685   verifyFormat("void foo() {\n"
25686                "  auto thing = test{\n"
25687                "      {\n"
25688                "       {13}, {something}, // A\n"
25689                "      }\n"
25690                "  };\n"
25691                "}",
25692                "void foo() {\n"
25693                "  auto thing = test{\n"
25694                "      {\n"
25695                "       {13},\n"
25696                "       {something}, // A\n"
25697                "      }\n"
25698                "  };\n"
25699                "}",
25700                Style);
25701 }
25702 
25703 TEST_F(FormatTest, FormatsVariableTemplates) {
25704   verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
25705   verifyFormat("template <typename T> "
25706                "inline bool var = is_integral_v<T> && is_signed_v<T>;");
25707 }
25708 
25709 } // namespace
25710 } // namespace format
25711 } // namespace clang
25712