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   verifyFormat("class A {\n"
3341                "public:\n"
3342                "  std::unique_ptr<int *[]> b() { return nullptr; }\n"
3343                "\n"
3344                "private:\n"
3345                "  int c;\n"
3346                "};");
3347 }
3348 
3349 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3350   EXPECT_EQ("class A {\n"
3351             "public:\n"
3352             "  void f();\n"
3353             "\n"
3354             "private:\n"
3355             "  void g() {}\n"
3356             "  // test\n"
3357             "protected:\n"
3358             "  int h;\n"
3359             "};",
3360             format("class A {\n"
3361                    "public:\n"
3362                    "void f();\n"
3363                    "private:\n"
3364                    "void g() {}\n"
3365                    "// test\n"
3366                    "protected:\n"
3367                    "int h;\n"
3368                    "};"));
3369   EXPECT_EQ("class A {\n"
3370             "protected:\n"
3371             "public:\n"
3372             "  void f();\n"
3373             "};",
3374             format("class A {\n"
3375                    "protected:\n"
3376                    "\n"
3377                    "public:\n"
3378                    "\n"
3379                    "  void f();\n"
3380                    "};"));
3381 
3382   // Even ensure proper spacing inside macros.
3383   EXPECT_EQ("#define B     \\\n"
3384             "  class A {   \\\n"
3385             "   protected: \\\n"
3386             "   public:    \\\n"
3387             "    void f(); \\\n"
3388             "  };",
3389             format("#define B     \\\n"
3390                    "  class A {   \\\n"
3391                    "   protected: \\\n"
3392                    "              \\\n"
3393                    "   public:    \\\n"
3394                    "              \\\n"
3395                    "    void f(); \\\n"
3396                    "  };",
3397                    getGoogleStyle()));
3398   // But don't remove empty lines after macros ending in access specifiers.
3399   EXPECT_EQ("#define A private:\n"
3400             "\n"
3401             "int i;",
3402             format("#define A         private:\n"
3403                    "\n"
3404                    "int              i;"));
3405 }
3406 
3407 TEST_F(FormatTest, FormatsClasses) {
3408   verifyFormat("class A : public B {};");
3409   verifyFormat("class A : public ::B {};");
3410 
3411   verifyFormat(
3412       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3413       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3414   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3415                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3416                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3417   verifyFormat(
3418       "class A : public B, public C, public D, public E, public F {};");
3419   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3420                "                     public C,\n"
3421                "                     public D,\n"
3422                "                     public E,\n"
3423                "                     public F,\n"
3424                "                     public G {};");
3425 
3426   verifyFormat("class\n"
3427                "    ReallyReallyLongClassName {\n"
3428                "  int i;\n"
3429                "};",
3430                getLLVMStyleWithColumns(32));
3431   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3432                "                           aaaaaaaaaaaaaaaa> {};");
3433   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3434                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3435                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3436   verifyFormat("template <class R, class C>\n"
3437                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3438                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3439   verifyFormat("class ::A::B {};");
3440 }
3441 
3442 TEST_F(FormatTest, BreakInheritanceStyle) {
3443   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3444   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3445       FormatStyle::BILS_BeforeComma;
3446   verifyFormat("class MyClass : public X {};",
3447                StyleWithInheritanceBreakBeforeComma);
3448   verifyFormat("class MyClass\n"
3449                "    : public X\n"
3450                "    , public Y {};",
3451                StyleWithInheritanceBreakBeforeComma);
3452   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3453                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3454                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3455                StyleWithInheritanceBreakBeforeComma);
3456   verifyFormat("struct aaaaaaaaaaaaa\n"
3457                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3458                "          aaaaaaaaaaaaaaaa> {};",
3459                StyleWithInheritanceBreakBeforeComma);
3460 
3461   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3462   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3463       FormatStyle::BILS_AfterColon;
3464   verifyFormat("class MyClass : public X {};",
3465                StyleWithInheritanceBreakAfterColon);
3466   verifyFormat("class MyClass : public X, public Y {};",
3467                StyleWithInheritanceBreakAfterColon);
3468   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3469                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3470                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3471                StyleWithInheritanceBreakAfterColon);
3472   verifyFormat("struct aaaaaaaaaaaaa :\n"
3473                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3474                "        aaaaaaaaaaaaaaaa> {};",
3475                StyleWithInheritanceBreakAfterColon);
3476 
3477   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3478   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3479       FormatStyle::BILS_AfterComma;
3480   verifyFormat("class MyClass : public X {};",
3481                StyleWithInheritanceBreakAfterComma);
3482   verifyFormat("class MyClass : public X,\n"
3483                "                public Y {};",
3484                StyleWithInheritanceBreakAfterComma);
3485   verifyFormat(
3486       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3487       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3488       "{};",
3489       StyleWithInheritanceBreakAfterComma);
3490   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3491                "                           aaaaaaaaaaaaaaaa> {};",
3492                StyleWithInheritanceBreakAfterComma);
3493   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3494                "    : public OnceBreak,\n"
3495                "      public AlwaysBreak,\n"
3496                "      EvenBasesFitInOneLine {};",
3497                StyleWithInheritanceBreakAfterComma);
3498 }
3499 
3500 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
3501   verifyFormat("class A {\n} a, b;");
3502   verifyFormat("struct A {\n} a, b;");
3503   verifyFormat("union A {\n} a, b;");
3504 
3505   verifyFormat("constexpr class A {\n} a, b;");
3506   verifyFormat("constexpr struct A {\n} a, b;");
3507   verifyFormat("constexpr union A {\n} a, b;");
3508 
3509   verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
3510   verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
3511   verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
3512 
3513   verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
3514   verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
3515   verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
3516 
3517   verifyFormat("namespace ns {\n"
3518                "class {\n"
3519                "} a, b;\n"
3520                "} // namespace ns");
3521   verifyFormat("namespace ns {\n"
3522                "const class {\n"
3523                "} a, b;\n"
3524                "} // namespace ns");
3525   verifyFormat("namespace ns {\n"
3526                "constexpr class C {\n"
3527                "} a, b;\n"
3528                "} // namespace ns");
3529   verifyFormat("namespace ns {\n"
3530                "class { /* comment */\n"
3531                "} a, b;\n"
3532                "} // namespace ns");
3533   verifyFormat("namespace ns {\n"
3534                "const class { /* comment */\n"
3535                "} a, b;\n"
3536                "} // namespace ns");
3537 }
3538 
3539 TEST_F(FormatTest, FormatsEnum) {
3540   verifyFormat("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   verifyGoogleFormat("enum {\n"
3549                      "  Zero,\n"
3550                      "  One = 1,\n"
3551                      "  Two = One + 1,\n"
3552                      "  Three = (One + Two),\n"
3553                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3554                      "  Five = (One, Two, Three, Four, 5)\n"
3555                      "};");
3556   verifyFormat("enum Enum {};");
3557   verifyFormat("enum {};");
3558   verifyFormat("enum X E {} d;");
3559   verifyFormat("enum __attribute__((...)) E {} d;");
3560   verifyFormat("enum __declspec__((...)) E {} d;");
3561   verifyFormat("enum {\n"
3562                "  Bar = Foo<int, int>::value\n"
3563                "};",
3564                getLLVMStyleWithColumns(30));
3565 
3566   verifyFormat("enum ShortEnum { A, B, C };");
3567   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3568 
3569   EXPECT_EQ("enum KeepEmptyLines {\n"
3570             "  ONE,\n"
3571             "\n"
3572             "  TWO,\n"
3573             "\n"
3574             "  THREE\n"
3575             "}",
3576             format("enum KeepEmptyLines {\n"
3577                    "  ONE,\n"
3578                    "\n"
3579                    "  TWO,\n"
3580                    "\n"
3581                    "\n"
3582                    "  THREE\n"
3583                    "}"));
3584   verifyFormat("enum E { // comment\n"
3585                "  ONE,\n"
3586                "  TWO\n"
3587                "};\n"
3588                "int i;");
3589 
3590   FormatStyle EightIndent = getLLVMStyle();
3591   EightIndent.IndentWidth = 8;
3592   verifyFormat("enum {\n"
3593                "        VOID,\n"
3594                "        CHAR,\n"
3595                "        SHORT,\n"
3596                "        INT,\n"
3597                "        LONG,\n"
3598                "        SIGNED,\n"
3599                "        UNSIGNED,\n"
3600                "        BOOL,\n"
3601                "        FLOAT,\n"
3602                "        DOUBLE,\n"
3603                "        COMPLEX\n"
3604                "};",
3605                EightIndent);
3606 
3607   // Not enums.
3608   verifyFormat("enum X f() {\n"
3609                "  a();\n"
3610                "  return 42;\n"
3611                "}");
3612   verifyFormat("enum X Type::f() {\n"
3613                "  a();\n"
3614                "  return 42;\n"
3615                "}");
3616   verifyFormat("enum ::X f() {\n"
3617                "  a();\n"
3618                "  return 42;\n"
3619                "}");
3620   verifyFormat("enum ns::X f() {\n"
3621                "  a();\n"
3622                "  return 42;\n"
3623                "}");
3624 }
3625 
3626 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3627   verifyFormat("enum Type {\n"
3628                "  One = 0; // These semicolons should be commas.\n"
3629                "  Two = 1;\n"
3630                "};");
3631   verifyFormat("namespace n {\n"
3632                "enum Type {\n"
3633                "  One,\n"
3634                "  Two, // missing };\n"
3635                "  int i;\n"
3636                "}\n"
3637                "void g() {}");
3638 }
3639 
3640 TEST_F(FormatTest, FormatsEnumStruct) {
3641   verifyFormat("enum struct {\n"
3642                "  Zero,\n"
3643                "  One = 1,\n"
3644                "  Two = One + 1,\n"
3645                "  Three = (One + Two),\n"
3646                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3647                "  Five = (One, Two, Three, Four, 5)\n"
3648                "};");
3649   verifyFormat("enum struct Enum {};");
3650   verifyFormat("enum struct {};");
3651   verifyFormat("enum struct X E {} d;");
3652   verifyFormat("enum struct __attribute__((...)) E {} d;");
3653   verifyFormat("enum struct __declspec__((...)) E {} d;");
3654   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3655 }
3656 
3657 TEST_F(FormatTest, FormatsEnumClass) {
3658   verifyFormat("enum class {\n"
3659                "  Zero,\n"
3660                "  One = 1,\n"
3661                "  Two = One + 1,\n"
3662                "  Three = (One + Two),\n"
3663                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3664                "  Five = (One, Two, Three, Four, 5)\n"
3665                "};");
3666   verifyFormat("enum class Enum {};");
3667   verifyFormat("enum class {};");
3668   verifyFormat("enum class X E {} d;");
3669   verifyFormat("enum class __attribute__((...)) E {} d;");
3670   verifyFormat("enum class __declspec__((...)) E {} d;");
3671   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3672 }
3673 
3674 TEST_F(FormatTest, FormatsEnumTypes) {
3675   verifyFormat("enum X : int {\n"
3676                "  A, // Force multiple lines.\n"
3677                "  B\n"
3678                "};");
3679   verifyFormat("enum X : int { A, B };");
3680   verifyFormat("enum X : std::uint32_t { A, B };");
3681 }
3682 
3683 TEST_F(FormatTest, FormatsTypedefEnum) {
3684   FormatStyle Style = getLLVMStyleWithColumns(40);
3685   verifyFormat("typedef enum {} EmptyEnum;");
3686   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3687   verifyFormat("typedef enum {\n"
3688                "  ZERO = 0,\n"
3689                "  ONE = 1,\n"
3690                "  TWO = 2,\n"
3691                "  THREE = 3\n"
3692                "} LongEnum;",
3693                Style);
3694   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3695   Style.BraceWrapping.AfterEnum = true;
3696   verifyFormat("typedef enum {} EmptyEnum;");
3697   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3698   verifyFormat("typedef enum\n"
3699                "{\n"
3700                "  ZERO = 0,\n"
3701                "  ONE = 1,\n"
3702                "  TWO = 2,\n"
3703                "  THREE = 3\n"
3704                "} LongEnum;",
3705                Style);
3706 }
3707 
3708 TEST_F(FormatTest, FormatsNSEnums) {
3709   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3710   verifyGoogleFormat(
3711       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3712   verifyGoogleFormat("typedef NS_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_CLOSED_ENUM(NSInteger, MyType) {\n"
3721                      "  // Information about someDecentlyLongValue.\n"
3722                      "  someDecentlyLongValue,\n"
3723                      "  // Information about anotherDecentlyLongValue.\n"
3724                      "  anotherDecentlyLongValue,\n"
3725                      "  // Information about aThirdDecentlyLongValue.\n"
3726                      "  aThirdDecentlyLongValue\n"
3727                      "};");
3728   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3729                      "  a = 1,\n"
3730                      "  b = 2,\n"
3731                      "  c = 3,\n"
3732                      "};");
3733   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3734                      "  a = 1,\n"
3735                      "  b = 2,\n"
3736                      "  c = 3,\n"
3737                      "};");
3738   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3739                      "  a = 1,\n"
3740                      "  b = 2,\n"
3741                      "  c = 3,\n"
3742                      "};");
3743   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3744                      "  a = 1,\n"
3745                      "  b = 2,\n"
3746                      "  c = 3,\n"
3747                      "};");
3748 }
3749 
3750 TEST_F(FormatTest, FormatsBitfields) {
3751   verifyFormat("struct Bitfields {\n"
3752                "  unsigned sClass : 8;\n"
3753                "  unsigned ValueKind : 2;\n"
3754                "};");
3755   verifyFormat("struct A {\n"
3756                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3757                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3758                "};");
3759   verifyFormat("struct MyStruct {\n"
3760                "  uchar data;\n"
3761                "  uchar : 8;\n"
3762                "  uchar : 8;\n"
3763                "  uchar other;\n"
3764                "};");
3765   FormatStyle Style = getLLVMStyle();
3766   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3767   verifyFormat("struct Bitfields {\n"
3768                "  unsigned sClass:8;\n"
3769                "  unsigned ValueKind:2;\n"
3770                "  uchar other;\n"
3771                "};",
3772                Style);
3773   verifyFormat("struct A {\n"
3774                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3775                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3776                "};",
3777                Style);
3778   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3779   verifyFormat("struct Bitfields {\n"
3780                "  unsigned sClass :8;\n"
3781                "  unsigned ValueKind :2;\n"
3782                "  uchar other;\n"
3783                "};",
3784                Style);
3785   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3786   verifyFormat("struct Bitfields {\n"
3787                "  unsigned sClass: 8;\n"
3788                "  unsigned ValueKind: 2;\n"
3789                "  uchar other;\n"
3790                "};",
3791                Style);
3792 }
3793 
3794 TEST_F(FormatTest, FormatsNamespaces) {
3795   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3796   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3797 
3798   verifyFormat("namespace some_namespace {\n"
3799                "class A {};\n"
3800                "void f() { f(); }\n"
3801                "}",
3802                LLVMWithNoNamespaceFix);
3803   verifyFormat("#define M(x) x##x\n"
3804                "namespace M(x) {\n"
3805                "class A {};\n"
3806                "void f() { f(); }\n"
3807                "}",
3808                LLVMWithNoNamespaceFix);
3809   verifyFormat("#define M(x) x##x\n"
3810                "namespace N::inline M(x) {\n"
3811                "class A {};\n"
3812                "void f() { f(); }\n"
3813                "}",
3814                LLVMWithNoNamespaceFix);
3815   verifyFormat("#define M(x) x##x\n"
3816                "namespace M(x)::inline N {\n"
3817                "class A {};\n"
3818                "void f() { f(); }\n"
3819                "}",
3820                LLVMWithNoNamespaceFix);
3821   verifyFormat("#define M(x) x##x\n"
3822                "namespace N::M(x) {\n"
3823                "class A {};\n"
3824                "void f() { f(); }\n"
3825                "}",
3826                LLVMWithNoNamespaceFix);
3827   verifyFormat("#define M(x) x##x\n"
3828                "namespace M::N(x) {\n"
3829                "class A {};\n"
3830                "void f() { f(); }\n"
3831                "}",
3832                LLVMWithNoNamespaceFix);
3833   verifyFormat("namespace N::inline D {\n"
3834                "class A {};\n"
3835                "void f() { f(); }\n"
3836                "}",
3837                LLVMWithNoNamespaceFix);
3838   verifyFormat("namespace N::inline D::E {\n"
3839                "class A {};\n"
3840                "void f() { f(); }\n"
3841                "}",
3842                LLVMWithNoNamespaceFix);
3843   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3844                "class A {};\n"
3845                "void f() { f(); }\n"
3846                "}",
3847                LLVMWithNoNamespaceFix);
3848   verifyFormat("/* something */ namespace some_namespace {\n"
3849                "class A {};\n"
3850                "void f() { f(); }\n"
3851                "}",
3852                LLVMWithNoNamespaceFix);
3853   verifyFormat("namespace {\n"
3854                "class A {};\n"
3855                "void f() { f(); }\n"
3856                "}",
3857                LLVMWithNoNamespaceFix);
3858   verifyFormat("/* something */ namespace {\n"
3859                "class A {};\n"
3860                "void f() { f(); }\n"
3861                "}",
3862                LLVMWithNoNamespaceFix);
3863   verifyFormat("inline namespace X {\n"
3864                "class A {};\n"
3865                "void f() { f(); }\n"
3866                "}",
3867                LLVMWithNoNamespaceFix);
3868   verifyFormat("/* something */ inline namespace X {\n"
3869                "class A {};\n"
3870                "void f() { f(); }\n"
3871                "}",
3872                LLVMWithNoNamespaceFix);
3873   verifyFormat("export namespace X {\n"
3874                "class A {};\n"
3875                "void f() { f(); }\n"
3876                "}",
3877                LLVMWithNoNamespaceFix);
3878   verifyFormat("using namespace some_namespace;\n"
3879                "class A {};\n"
3880                "void f() { f(); }",
3881                LLVMWithNoNamespaceFix);
3882 
3883   // This code is more common than we thought; if we
3884   // layout this correctly the semicolon will go into
3885   // its own line, which is undesirable.
3886   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3887   verifyFormat("namespace {\n"
3888                "class A {};\n"
3889                "};",
3890                LLVMWithNoNamespaceFix);
3891 
3892   verifyFormat("namespace {\n"
3893                "int SomeVariable = 0; // comment\n"
3894                "} // namespace",
3895                LLVMWithNoNamespaceFix);
3896   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3897             "#define HEADER_GUARD\n"
3898             "namespace my_namespace {\n"
3899             "int i;\n"
3900             "} // my_namespace\n"
3901             "#endif // HEADER_GUARD",
3902             format("#ifndef HEADER_GUARD\n"
3903                    " #define HEADER_GUARD\n"
3904                    "   namespace my_namespace {\n"
3905                    "int i;\n"
3906                    "}    // my_namespace\n"
3907                    "#endif    // HEADER_GUARD",
3908                    LLVMWithNoNamespaceFix));
3909 
3910   EXPECT_EQ("namespace A::B {\n"
3911             "class C {};\n"
3912             "}",
3913             format("namespace A::B {\n"
3914                    "class C {};\n"
3915                    "}",
3916                    LLVMWithNoNamespaceFix));
3917 
3918   FormatStyle Style = getLLVMStyle();
3919   Style.NamespaceIndentation = FormatStyle::NI_All;
3920   EXPECT_EQ("namespace out {\n"
3921             "  int i;\n"
3922             "  namespace in {\n"
3923             "    int i;\n"
3924             "  } // namespace in\n"
3925             "} // namespace out",
3926             format("namespace out {\n"
3927                    "int i;\n"
3928                    "namespace in {\n"
3929                    "int i;\n"
3930                    "} // namespace in\n"
3931                    "} // namespace out",
3932                    Style));
3933 
3934   FormatStyle ShortInlineFunctions = getLLVMStyle();
3935   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3936   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3937       FormatStyle::SFS_Inline;
3938   verifyFormat("namespace {\n"
3939                "  void f() {\n"
3940                "    return;\n"
3941                "  }\n"
3942                "} // namespace\n",
3943                ShortInlineFunctions);
3944   verifyFormat("namespace { /* comment */\n"
3945                "  void f() {\n"
3946                "    return;\n"
3947                "  }\n"
3948                "} // namespace\n",
3949                ShortInlineFunctions);
3950   verifyFormat("namespace { // comment\n"
3951                "  void f() {\n"
3952                "    return;\n"
3953                "  }\n"
3954                "} // namespace\n",
3955                ShortInlineFunctions);
3956   verifyFormat("namespace {\n"
3957                "  int some_int;\n"
3958                "  void f() {\n"
3959                "    return;\n"
3960                "  }\n"
3961                "} // namespace\n",
3962                ShortInlineFunctions);
3963   verifyFormat("namespace interface {\n"
3964                "  void f() {\n"
3965                "    return;\n"
3966                "  }\n"
3967                "} // namespace interface\n",
3968                ShortInlineFunctions);
3969   verifyFormat("namespace {\n"
3970                "  class X {\n"
3971                "    void f() { return; }\n"
3972                "  };\n"
3973                "} // namespace\n",
3974                ShortInlineFunctions);
3975   verifyFormat("namespace {\n"
3976                "  class X { /* comment */\n"
3977                "    void f() { return; }\n"
3978                "  };\n"
3979                "} // namespace\n",
3980                ShortInlineFunctions);
3981   verifyFormat("namespace {\n"
3982                "  class X { // comment\n"
3983                "    void f() { return; }\n"
3984                "  };\n"
3985                "} // namespace\n",
3986                ShortInlineFunctions);
3987   verifyFormat("namespace {\n"
3988                "  struct X {\n"
3989                "    void f() { return; }\n"
3990                "  };\n"
3991                "} // namespace\n",
3992                ShortInlineFunctions);
3993   verifyFormat("namespace {\n"
3994                "  union X {\n"
3995                "    void f() { return; }\n"
3996                "  };\n"
3997                "} // namespace\n",
3998                ShortInlineFunctions);
3999   verifyFormat("extern \"C\" {\n"
4000                "void f() {\n"
4001                "  return;\n"
4002                "}\n"
4003                "} // namespace\n",
4004                ShortInlineFunctions);
4005   verifyFormat("namespace {\n"
4006                "  class X {\n"
4007                "    void f() { return; }\n"
4008                "  } x;\n"
4009                "} // namespace\n",
4010                ShortInlineFunctions);
4011   verifyFormat("namespace {\n"
4012                "  [[nodiscard]] class X {\n"
4013                "    void f() { return; }\n"
4014                "  };\n"
4015                "} // namespace\n",
4016                ShortInlineFunctions);
4017   verifyFormat("namespace {\n"
4018                "  static class X {\n"
4019                "    void f() { return; }\n"
4020                "  } x;\n"
4021                "} // namespace\n",
4022                ShortInlineFunctions);
4023   verifyFormat("namespace {\n"
4024                "  constexpr class X {\n"
4025                "    void f() { return; }\n"
4026                "  } x;\n"
4027                "} // namespace\n",
4028                ShortInlineFunctions);
4029 
4030   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
4031   verifyFormat("extern \"C\" {\n"
4032                "  void f() {\n"
4033                "    return;\n"
4034                "  }\n"
4035                "} // namespace\n",
4036                ShortInlineFunctions);
4037 
4038   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4039   EXPECT_EQ("namespace out {\n"
4040             "int i;\n"
4041             "namespace in {\n"
4042             "  int i;\n"
4043             "} // namespace in\n"
4044             "} // namespace out",
4045             format("namespace out {\n"
4046                    "int i;\n"
4047                    "namespace in {\n"
4048                    "int i;\n"
4049                    "} // namespace in\n"
4050                    "} // namespace out",
4051                    Style));
4052 
4053   Style.NamespaceIndentation = FormatStyle::NI_None;
4054   verifyFormat("template <class T>\n"
4055                "concept a_concept = X<>;\n"
4056                "namespace B {\n"
4057                "struct b_struct {};\n"
4058                "} // namespace B\n",
4059                Style);
4060   verifyFormat("template <int I>\n"
4061                "constexpr void foo()\n"
4062                "  requires(I == 42)\n"
4063                "{}\n"
4064                "namespace ns {\n"
4065                "void foo() {}\n"
4066                "} // namespace ns\n",
4067                Style);
4068 }
4069 
4070 TEST_F(FormatTest, NamespaceMacros) {
4071   FormatStyle Style = getLLVMStyle();
4072   Style.NamespaceMacros.push_back("TESTSUITE");
4073 
4074   verifyFormat("TESTSUITE(A) {\n"
4075                "int foo();\n"
4076                "} // TESTSUITE(A)",
4077                Style);
4078 
4079   verifyFormat("TESTSUITE(A, B) {\n"
4080                "int foo();\n"
4081                "} // TESTSUITE(A)",
4082                Style);
4083 
4084   // Properly indent according to NamespaceIndentation style
4085   Style.NamespaceIndentation = FormatStyle::NI_All;
4086   verifyFormat("TESTSUITE(A) {\n"
4087                "  int foo();\n"
4088                "} // TESTSUITE(A)",
4089                Style);
4090   verifyFormat("TESTSUITE(A) {\n"
4091                "  namespace B {\n"
4092                "    int foo();\n"
4093                "  } // namespace B\n"
4094                "} // TESTSUITE(A)",
4095                Style);
4096   verifyFormat("namespace A {\n"
4097                "  TESTSUITE(B) {\n"
4098                "    int foo();\n"
4099                "  } // TESTSUITE(B)\n"
4100                "} // namespace A",
4101                Style);
4102 
4103   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4104   verifyFormat("TESTSUITE(A) {\n"
4105                "TESTSUITE(B) {\n"
4106                "  int foo();\n"
4107                "} // TESTSUITE(B)\n"
4108                "} // TESTSUITE(A)",
4109                Style);
4110   verifyFormat("TESTSUITE(A) {\n"
4111                "namespace B {\n"
4112                "  int foo();\n"
4113                "} // namespace B\n"
4114                "} // TESTSUITE(A)",
4115                Style);
4116   verifyFormat("namespace A {\n"
4117                "TESTSUITE(B) {\n"
4118                "  int foo();\n"
4119                "} // TESTSUITE(B)\n"
4120                "} // namespace A",
4121                Style);
4122 
4123   // Properly merge namespace-macros blocks in CompactNamespaces mode
4124   Style.NamespaceIndentation = FormatStyle::NI_None;
4125   Style.CompactNamespaces = true;
4126   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
4127                "}} // TESTSUITE(A::B)",
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   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4139             "}} // TESTSUITE(out::in)",
4140             format("TESTSUITE(out) {\n"
4141                    "TESTSUITE(in) {\n"
4142                    "} // TESTSUITE(in)\n"
4143                    "} // TESTSUITE(out)",
4144                    Style));
4145 
4146   // Do not merge different namespaces/macros
4147   EXPECT_EQ("namespace out {\n"
4148             "TESTSUITE(in) {\n"
4149             "} // TESTSUITE(in)\n"
4150             "} // namespace out",
4151             format("namespace out {\n"
4152                    "TESTSUITE(in) {\n"
4153                    "} // TESTSUITE(in)\n"
4154                    "} // namespace out",
4155                    Style));
4156   EXPECT_EQ("TESTSUITE(out) {\n"
4157             "namespace in {\n"
4158             "} // namespace in\n"
4159             "} // TESTSUITE(out)",
4160             format("TESTSUITE(out) {\n"
4161                    "namespace in {\n"
4162                    "} // namespace in\n"
4163                    "} // TESTSUITE(out)",
4164                    Style));
4165   Style.NamespaceMacros.push_back("FOOBAR");
4166   EXPECT_EQ("TESTSUITE(out) {\n"
4167             "FOOBAR(in) {\n"
4168             "} // FOOBAR(in)\n"
4169             "} // TESTSUITE(out)",
4170             format("TESTSUITE(out) {\n"
4171                    "FOOBAR(in) {\n"
4172                    "} // FOOBAR(in)\n"
4173                    "} // TESTSUITE(out)",
4174                    Style));
4175 }
4176 
4177 TEST_F(FormatTest, FormatsCompactNamespaces) {
4178   FormatStyle Style = getLLVMStyle();
4179   Style.CompactNamespaces = true;
4180   Style.NamespaceMacros.push_back("TESTSUITE");
4181 
4182   verifyFormat("namespace A { namespace B {\n"
4183                "}} // namespace A::B",
4184                Style);
4185 
4186   EXPECT_EQ("namespace out { namespace in {\n"
4187             "}} // namespace out::in",
4188             format("namespace out {\n"
4189                    "namespace in {\n"
4190                    "} // namespace in\n"
4191                    "} // namespace out",
4192                    Style));
4193 
4194   // Only namespaces which have both consecutive opening and end get compacted
4195   EXPECT_EQ("namespace out {\n"
4196             "namespace in1 {\n"
4197             "} // namespace in1\n"
4198             "namespace in2 {\n"
4199             "} // namespace in2\n"
4200             "} // namespace out",
4201             format("namespace out {\n"
4202                    "namespace in1 {\n"
4203                    "} // namespace in1\n"
4204                    "namespace in2 {\n"
4205                    "} // namespace in2\n"
4206                    "} // namespace out",
4207                    Style));
4208 
4209   EXPECT_EQ("namespace out {\n"
4210             "int i;\n"
4211             "namespace in {\n"
4212             "int j;\n"
4213             "} // namespace in\n"
4214             "int k;\n"
4215             "} // namespace out",
4216             format("namespace out { int i;\n"
4217                    "namespace in { int j; } // namespace in\n"
4218                    "int k; } // namespace out",
4219                    Style));
4220 
4221   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
4222             "}}} // namespace A::B::C\n",
4223             format("namespace A { namespace B {\n"
4224                    "namespace C {\n"
4225                    "}} // namespace B::C\n"
4226                    "} // namespace A\n",
4227                    Style));
4228 
4229   Style.ColumnLimit = 40;
4230   EXPECT_EQ("namespace aaaaaaaaaa {\n"
4231             "namespace bbbbbbbbbb {\n"
4232             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
4233             format("namespace aaaaaaaaaa {\n"
4234                    "namespace bbbbbbbbbb {\n"
4235                    "} // namespace bbbbbbbbbb\n"
4236                    "} // namespace aaaaaaaaaa",
4237                    Style));
4238 
4239   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
4240             "namespace cccccc {\n"
4241             "}}} // namespace aaaaaa::bbbbbb::cccccc",
4242             format("namespace aaaaaa {\n"
4243                    "namespace bbbbbb {\n"
4244                    "namespace cccccc {\n"
4245                    "} // namespace cccccc\n"
4246                    "} // namespace bbbbbb\n"
4247                    "} // namespace aaaaaa",
4248                    Style));
4249   Style.ColumnLimit = 80;
4250 
4251   // Extra semicolon after 'inner' closing brace prevents merging
4252   EXPECT_EQ("namespace out { namespace in {\n"
4253             "}; } // namespace out::in",
4254             format("namespace out {\n"
4255                    "namespace in {\n"
4256                    "}; // namespace in\n"
4257                    "} // namespace out",
4258                    Style));
4259 
4260   // Extra semicolon after 'outer' closing brace is conserved
4261   EXPECT_EQ("namespace out { namespace in {\n"
4262             "}}; // namespace out::in",
4263             format("namespace out {\n"
4264                    "namespace in {\n"
4265                    "} // namespace in\n"
4266                    "}; // namespace out",
4267                    Style));
4268 
4269   Style.NamespaceIndentation = FormatStyle::NI_All;
4270   EXPECT_EQ("namespace out { namespace in {\n"
4271             "  int i;\n"
4272             "}} // namespace out::in",
4273             format("namespace out {\n"
4274                    "namespace in {\n"
4275                    "int i;\n"
4276                    "} // namespace in\n"
4277                    "} // namespace out",
4278                    Style));
4279   EXPECT_EQ("namespace out { namespace mid {\n"
4280             "  namespace in {\n"
4281             "    int j;\n"
4282             "  } // namespace in\n"
4283             "  int k;\n"
4284             "}} // namespace out::mid",
4285             format("namespace out { namespace mid {\n"
4286                    "namespace in { int j; } // namespace in\n"
4287                    "int k; }} // namespace out::mid",
4288                    Style));
4289 
4290   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4291   EXPECT_EQ("namespace out { namespace in {\n"
4292             "  int i;\n"
4293             "}} // namespace out::in",
4294             format("namespace out {\n"
4295                    "namespace in {\n"
4296                    "int i;\n"
4297                    "} // namespace in\n"
4298                    "} // namespace out",
4299                    Style));
4300   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
4301             "  int i;\n"
4302             "}}} // namespace out::mid::in",
4303             format("namespace out {\n"
4304                    "namespace mid {\n"
4305                    "namespace in {\n"
4306                    "int i;\n"
4307                    "} // namespace in\n"
4308                    "} // namespace mid\n"
4309                    "} // namespace out",
4310                    Style));
4311 
4312   Style.CompactNamespaces = true;
4313   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4314   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4315   Style.BraceWrapping.BeforeLambdaBody = true;
4316   verifyFormat("namespace out { namespace in {\n"
4317                "}} // namespace out::in",
4318                Style);
4319   EXPECT_EQ("namespace out { namespace in {\n"
4320             "}} // namespace out::in",
4321             format("namespace out {\n"
4322                    "namespace in {\n"
4323                    "} // namespace in\n"
4324                    "} // namespace out",
4325                    Style));
4326 }
4327 
4328 TEST_F(FormatTest, FormatsExternC) {
4329   verifyFormat("extern \"C\" {\nint a;");
4330   verifyFormat("extern \"C\" {}");
4331   verifyFormat("extern \"C\" {\n"
4332                "int foo();\n"
4333                "}");
4334   verifyFormat("extern \"C\" int foo() {}");
4335   verifyFormat("extern \"C\" int foo();");
4336   verifyFormat("extern \"C\" int foo() {\n"
4337                "  int i = 42;\n"
4338                "  return i;\n"
4339                "}");
4340 
4341   FormatStyle Style = getLLVMStyle();
4342   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4343   Style.BraceWrapping.AfterFunction = true;
4344   verifyFormat("extern \"C\" int foo() {}", Style);
4345   verifyFormat("extern \"C\" int foo();", Style);
4346   verifyFormat("extern \"C\" int foo()\n"
4347                "{\n"
4348                "  int i = 42;\n"
4349                "  return i;\n"
4350                "}",
4351                Style);
4352 
4353   Style.BraceWrapping.AfterExternBlock = true;
4354   Style.BraceWrapping.SplitEmptyRecord = false;
4355   verifyFormat("extern \"C\"\n"
4356                "{}",
4357                Style);
4358   verifyFormat("extern \"C\"\n"
4359                "{\n"
4360                "  int foo();\n"
4361                "}",
4362                Style);
4363 }
4364 
4365 TEST_F(FormatTest, IndentExternBlockStyle) {
4366   FormatStyle Style = getLLVMStyle();
4367   Style.IndentWidth = 2;
4368 
4369   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4370   verifyFormat("extern \"C\" { /*9*/\n"
4371                "}",
4372                Style);
4373   verifyFormat("extern \"C\" {\n"
4374                "  int foo10();\n"
4375                "}",
4376                Style);
4377 
4378   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4379   verifyFormat("extern \"C\" { /*11*/\n"
4380                "}",
4381                Style);
4382   verifyFormat("extern \"C\" {\n"
4383                "int foo12();\n"
4384                "}",
4385                Style);
4386 
4387   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4388   Style.BraceWrapping.AfterExternBlock = true;
4389   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4390   verifyFormat("extern \"C\"\n"
4391                "{ /*13*/\n"
4392                "}",
4393                Style);
4394   verifyFormat("extern \"C\"\n{\n"
4395                "  int foo14();\n"
4396                "}",
4397                Style);
4398 
4399   Style.BraceWrapping.AfterExternBlock = false;
4400   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4401   verifyFormat("extern \"C\" { /*15*/\n"
4402                "}",
4403                Style);
4404   verifyFormat("extern \"C\" {\n"
4405                "int foo16();\n"
4406                "}",
4407                Style);
4408 
4409   Style.BraceWrapping.AfterExternBlock = true;
4410   verifyFormat("extern \"C\"\n"
4411                "{ /*13*/\n"
4412                "}",
4413                Style);
4414   verifyFormat("extern \"C\"\n"
4415                "{\n"
4416                "int foo14();\n"
4417                "}",
4418                Style);
4419 
4420   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4421   verifyFormat("extern \"C\"\n"
4422                "{ /*13*/\n"
4423                "}",
4424                Style);
4425   verifyFormat("extern \"C\"\n"
4426                "{\n"
4427                "  int foo14();\n"
4428                "}",
4429                Style);
4430 }
4431 
4432 TEST_F(FormatTest, FormatsInlineASM) {
4433   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4434   verifyFormat("asm(\"nop\" ::: \"memory\");");
4435   verifyFormat(
4436       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4437       "    \"cpuid\\n\\t\"\n"
4438       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4439       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4440       "    : \"a\"(value));");
4441   EXPECT_EQ(
4442       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4443       "  __asm {\n"
4444       "        mov     edx,[that] // vtable in edx\n"
4445       "        mov     eax,methodIndex\n"
4446       "        call    [edx][eax*4] // stdcall\n"
4447       "  }\n"
4448       "}",
4449       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4450              "    __asm {\n"
4451              "        mov     edx,[that] // vtable in edx\n"
4452              "        mov     eax,methodIndex\n"
4453              "        call    [edx][eax*4] // stdcall\n"
4454              "    }\n"
4455              "}"));
4456   EXPECT_EQ("_asm {\n"
4457             "  xor eax, eax;\n"
4458             "  cpuid;\n"
4459             "}",
4460             format("_asm {\n"
4461                    "  xor eax, eax;\n"
4462                    "  cpuid;\n"
4463                    "}"));
4464   verifyFormat("void function() {\n"
4465                "  // comment\n"
4466                "  asm(\"\");\n"
4467                "}");
4468   EXPECT_EQ("__asm {\n"
4469             "}\n"
4470             "int i;",
4471             format("__asm   {\n"
4472                    "}\n"
4473                    "int   i;"));
4474 }
4475 
4476 TEST_F(FormatTest, FormatTryCatch) {
4477   verifyFormat("try {\n"
4478                "  throw a * b;\n"
4479                "} catch (int a) {\n"
4480                "  // Do nothing.\n"
4481                "} catch (...) {\n"
4482                "  exit(42);\n"
4483                "}");
4484 
4485   // Function-level try statements.
4486   verifyFormat("int f() try { return 4; } catch (...) {\n"
4487                "  return 5;\n"
4488                "}");
4489   verifyFormat("class A {\n"
4490                "  int a;\n"
4491                "  A() try : a(0) {\n"
4492                "  } catch (...) {\n"
4493                "    throw;\n"
4494                "  }\n"
4495                "};\n");
4496   verifyFormat("class A {\n"
4497                "  int a;\n"
4498                "  A() try : a(0), b{1} {\n"
4499                "  } catch (...) {\n"
4500                "    throw;\n"
4501                "  }\n"
4502                "};\n");
4503   verifyFormat("class A {\n"
4504                "  int a;\n"
4505                "  A() try : a(0), b{1}, c{2} {\n"
4506                "  } catch (...) {\n"
4507                "    throw;\n"
4508                "  }\n"
4509                "};\n");
4510   verifyFormat("class A {\n"
4511                "  int a;\n"
4512                "  A() try : a(0), b{1}, c{2} {\n"
4513                "    { // New scope.\n"
4514                "    }\n"
4515                "  } catch (...) {\n"
4516                "    throw;\n"
4517                "  }\n"
4518                "};\n");
4519 
4520   // Incomplete try-catch blocks.
4521   verifyIncompleteFormat("try {} catch (");
4522 }
4523 
4524 TEST_F(FormatTest, FormatTryAsAVariable) {
4525   verifyFormat("int try;");
4526   verifyFormat("int try, size;");
4527   verifyFormat("try = foo();");
4528   verifyFormat("if (try < size) {\n  return true;\n}");
4529 
4530   verifyFormat("int catch;");
4531   verifyFormat("int catch, size;");
4532   verifyFormat("catch = foo();");
4533   verifyFormat("if (catch < size) {\n  return true;\n}");
4534 
4535   FormatStyle Style = getLLVMStyle();
4536   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4537   Style.BraceWrapping.AfterFunction = true;
4538   Style.BraceWrapping.BeforeCatch = true;
4539   verifyFormat("try {\n"
4540                "  int bar = 1;\n"
4541                "}\n"
4542                "catch (...) {\n"
4543                "  int bar = 1;\n"
4544                "}",
4545                Style);
4546   verifyFormat("#if NO_EX\n"
4547                "try\n"
4548                "#endif\n"
4549                "{\n"
4550                "}\n"
4551                "#if NO_EX\n"
4552                "catch (...) {\n"
4553                "}",
4554                Style);
4555   verifyFormat("try /* abc */ {\n"
4556                "  int bar = 1;\n"
4557                "}\n"
4558                "catch (...) {\n"
4559                "  int bar = 1;\n"
4560                "}",
4561                Style);
4562   verifyFormat("try\n"
4563                "// abc\n"
4564                "{\n"
4565                "  int bar = 1;\n"
4566                "}\n"
4567                "catch (...) {\n"
4568                "  int bar = 1;\n"
4569                "}",
4570                Style);
4571 }
4572 
4573 TEST_F(FormatTest, FormatSEHTryCatch) {
4574   verifyFormat("__try {\n"
4575                "  int a = b * c;\n"
4576                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4577                "  // Do nothing.\n"
4578                "}");
4579 
4580   verifyFormat("__try {\n"
4581                "  int a = b * c;\n"
4582                "} __finally {\n"
4583                "  // Do nothing.\n"
4584                "}");
4585 
4586   verifyFormat("DEBUG({\n"
4587                "  __try {\n"
4588                "  } __finally {\n"
4589                "  }\n"
4590                "});\n");
4591 }
4592 
4593 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4594   verifyFormat("try {\n"
4595                "  f();\n"
4596                "} catch {\n"
4597                "  g();\n"
4598                "}");
4599   verifyFormat("try {\n"
4600                "  f();\n"
4601                "} catch (A a) MACRO(x) {\n"
4602                "  g();\n"
4603                "} catch (B b) MACRO(x) {\n"
4604                "  g();\n"
4605                "}");
4606 }
4607 
4608 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4609   FormatStyle Style = getLLVMStyle();
4610   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4611                           FormatStyle::BS_WebKit}) {
4612     Style.BreakBeforeBraces = BraceStyle;
4613     verifyFormat("try {\n"
4614                  "  // something\n"
4615                  "} catch (...) {\n"
4616                  "  // something\n"
4617                  "}",
4618                  Style);
4619   }
4620   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4621   verifyFormat("try {\n"
4622                "  // something\n"
4623                "}\n"
4624                "catch (...) {\n"
4625                "  // something\n"
4626                "}",
4627                Style);
4628   verifyFormat("__try {\n"
4629                "  // something\n"
4630                "}\n"
4631                "__finally {\n"
4632                "  // something\n"
4633                "}",
4634                Style);
4635   verifyFormat("@try {\n"
4636                "  // something\n"
4637                "}\n"
4638                "@finally {\n"
4639                "  // something\n"
4640                "}",
4641                Style);
4642   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4643   verifyFormat("try\n"
4644                "{\n"
4645                "  // something\n"
4646                "}\n"
4647                "catch (...)\n"
4648                "{\n"
4649                "  // something\n"
4650                "}",
4651                Style);
4652   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4653   verifyFormat("try\n"
4654                "  {\n"
4655                "  // something white\n"
4656                "  }\n"
4657                "catch (...)\n"
4658                "  {\n"
4659                "  // something white\n"
4660                "  }",
4661                Style);
4662   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4663   verifyFormat("try\n"
4664                "  {\n"
4665                "    // something\n"
4666                "  }\n"
4667                "catch (...)\n"
4668                "  {\n"
4669                "    // something\n"
4670                "  }",
4671                Style);
4672   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4673   Style.BraceWrapping.BeforeCatch = true;
4674   verifyFormat("try {\n"
4675                "  // something\n"
4676                "}\n"
4677                "catch (...) {\n"
4678                "  // something\n"
4679                "}",
4680                Style);
4681 }
4682 
4683 TEST_F(FormatTest, StaticInitializers) {
4684   verifyFormat("static SomeClass SC = {1, 'a'};");
4685 
4686   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4687                "    100000000, "
4688                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4689 
4690   // Here, everything other than the "}" would fit on a line.
4691   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4692                "    10000000000000000000000000};");
4693   EXPECT_EQ("S s = {a,\n"
4694             "\n"
4695             "       b};",
4696             format("S s = {\n"
4697                    "  a,\n"
4698                    "\n"
4699                    "  b\n"
4700                    "};"));
4701 
4702   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4703   // line. However, the formatting looks a bit off and this probably doesn't
4704   // happen often in practice.
4705   verifyFormat("static int Variable[1] = {\n"
4706                "    {1000000000000000000000000000000000000}};",
4707                getLLVMStyleWithColumns(40));
4708 }
4709 
4710 TEST_F(FormatTest, DesignatedInitializers) {
4711   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4712   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4713                "                    .bbbbbbbbbb = 2,\n"
4714                "                    .cccccccccc = 3,\n"
4715                "                    .dddddddddd = 4,\n"
4716                "                    .eeeeeeeeee = 5};");
4717   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4718                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4719                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4720                "    .ccccccccccccccccccccccccccc = 3,\n"
4721                "    .ddddddddddddddddddddddddddd = 4,\n"
4722                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4723 
4724   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4725 
4726   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4727   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4728                "                    [2] = bbbbbbbbbb,\n"
4729                "                    [3] = cccccccccc,\n"
4730                "                    [4] = dddddddddd,\n"
4731                "                    [5] = eeeeeeeeee};");
4732   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4733                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4734                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4735                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4736                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4737                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4738 }
4739 
4740 TEST_F(FormatTest, NestedStaticInitializers) {
4741   verifyFormat("static A x = {{{}}};\n");
4742   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4743                "               {init1, init2, init3, init4}}};",
4744                getLLVMStyleWithColumns(50));
4745 
4746   verifyFormat("somes Status::global_reps[3] = {\n"
4747                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4748                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4749                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4750                getLLVMStyleWithColumns(60));
4751   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4752                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4753                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4754                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4755   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4756                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4757                "rect.fTop}};");
4758 
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   verifyFormat(
4768       "SomeArrayOfSomeType a = {\n"
4769       "    {{1, 2, 3}},\n"
4770       "    {{1, 2, 3}},\n"
4771       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4772       "      333333333333333333333333333333}},\n"
4773       "    {{1, 2, 3}},\n"
4774       "    {{1, 2, 3}}};");
4775 
4776   verifyFormat("struct {\n"
4777                "  unsigned bit;\n"
4778                "  const char *const name;\n"
4779                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4780                "                 {kOsWin, \"Windows\"},\n"
4781                "                 {kOsLinux, \"Linux\"},\n"
4782                "                 {kOsCrOS, \"Chrome OS\"}};");
4783   verifyFormat("struct {\n"
4784                "  unsigned bit;\n"
4785                "  const char *const name;\n"
4786                "} kBitsToOs[] = {\n"
4787                "    {kOsMac, \"Mac\"},\n"
4788                "    {kOsWin, \"Windows\"},\n"
4789                "    {kOsLinux, \"Linux\"},\n"
4790                "    {kOsCrOS, \"Chrome OS\"},\n"
4791                "};");
4792 }
4793 
4794 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4795   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4796                "                      \\\n"
4797                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4798 }
4799 
4800 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4801   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4802                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4803 
4804   // Do break defaulted and deleted functions.
4805   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4806                "    default;",
4807                getLLVMStyleWithColumns(40));
4808   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4809                "    delete;",
4810                getLLVMStyleWithColumns(40));
4811 }
4812 
4813 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4814   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4815                getLLVMStyleWithColumns(40));
4816   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4817                getLLVMStyleWithColumns(40));
4818   EXPECT_EQ("#define Q                              \\\n"
4819             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4820             "  \"aaaaaaaa.cpp\"",
4821             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4822                    getLLVMStyleWithColumns(40)));
4823 }
4824 
4825 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4826   EXPECT_EQ("# 123 \"A string literal\"",
4827             format("   #     123    \"A string literal\""));
4828 }
4829 
4830 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4831   EXPECT_EQ("#;", format("#;"));
4832   verifyFormat("#\n;\n;\n;");
4833 }
4834 
4835 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4836   EXPECT_EQ("#line 42 \"test\"\n",
4837             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4838   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4839                                     getLLVMStyleWithColumns(12)));
4840 }
4841 
4842 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4843   EXPECT_EQ("#line 42 \"test\"",
4844             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4845   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4846 }
4847 
4848 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4849   verifyFormat("#define A \\x20");
4850   verifyFormat("#define A \\ x20");
4851   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4852   verifyFormat("#define A ''");
4853   verifyFormat("#define A ''qqq");
4854   verifyFormat("#define A `qqq");
4855   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4856   EXPECT_EQ("const char *c = STRINGIFY(\n"
4857             "\\na : b);",
4858             format("const char * c = STRINGIFY(\n"
4859                    "\\na : b);"));
4860 
4861   verifyFormat("a\r\\");
4862   verifyFormat("a\v\\");
4863   verifyFormat("a\f\\");
4864 }
4865 
4866 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4867   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4868   style.IndentWidth = 4;
4869   style.PPIndentWidth = 1;
4870 
4871   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4872   verifyFormat("#ifdef __linux__\n"
4873                "void foo() {\n"
4874                "    int x = 0;\n"
4875                "}\n"
4876                "#define FOO\n"
4877                "#endif\n"
4878                "void bar() {\n"
4879                "    int y = 0;\n"
4880                "}\n",
4881                style);
4882 
4883   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4884   verifyFormat("#ifdef __linux__\n"
4885                "void foo() {\n"
4886                "    int x = 0;\n"
4887                "}\n"
4888                "# define FOO foo\n"
4889                "#endif\n"
4890                "void bar() {\n"
4891                "    int y = 0;\n"
4892                "}\n",
4893                style);
4894 
4895   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4896   verifyFormat("#ifdef __linux__\n"
4897                "void foo() {\n"
4898                "    int x = 0;\n"
4899                "}\n"
4900                " #define FOO foo\n"
4901                "#endif\n"
4902                "void bar() {\n"
4903                "    int y = 0;\n"
4904                "}\n",
4905                style);
4906 }
4907 
4908 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4909   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4910   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4911   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4912   // FIXME: We never break before the macro name.
4913   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4914 
4915   verifyFormat("#define A A\n#define A A");
4916   verifyFormat("#define A(X) A\n#define A A");
4917 
4918   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4919   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4920 }
4921 
4922 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4923   EXPECT_EQ("// somecomment\n"
4924             "#include \"a.h\"\n"
4925             "#define A(  \\\n"
4926             "    A, B)\n"
4927             "#include \"b.h\"\n"
4928             "// somecomment\n",
4929             format("  // somecomment\n"
4930                    "  #include \"a.h\"\n"
4931                    "#define A(A,\\\n"
4932                    "    B)\n"
4933                    "    #include \"b.h\"\n"
4934                    " // somecomment\n",
4935                    getLLVMStyleWithColumns(13)));
4936 }
4937 
4938 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4939 
4940 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4941   EXPECT_EQ("#define A    \\\n"
4942             "  c;         \\\n"
4943             "  e;\n"
4944             "f;",
4945             format("#define A c; e;\n"
4946                    "f;",
4947                    getLLVMStyleWithColumns(14)));
4948 }
4949 
4950 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4951 
4952 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4953   EXPECT_EQ("int x,\n"
4954             "#define A\n"
4955             "    y;",
4956             format("int x,\n#define A\ny;"));
4957 }
4958 
4959 TEST_F(FormatTest, HashInMacroDefinition) {
4960   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4961   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4962   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4963   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4964   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4965   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4966   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4967   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4968   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4969   verifyFormat("#define A  \\\n"
4970                "  {        \\\n"
4971                "    f(#c); \\\n"
4972                "  }",
4973                getLLVMStyleWithColumns(11));
4974 
4975   verifyFormat("#define A(X)         \\\n"
4976                "  void function##X()",
4977                getLLVMStyleWithColumns(22));
4978 
4979   verifyFormat("#define A(a, b, c)   \\\n"
4980                "  void a##b##c()",
4981                getLLVMStyleWithColumns(22));
4982 
4983   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4984 }
4985 
4986 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4987   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4988   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4989 
4990   FormatStyle Style = getLLVMStyle();
4991   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4992   verifyFormat("#define true ((foo)1)", Style);
4993   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4994   verifyFormat("#define false((foo)0)", Style);
4995 }
4996 
4997 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4998   EXPECT_EQ("#define A b;", format("#define A \\\n"
4999                                    "          \\\n"
5000                                    "  b;",
5001                                    getLLVMStyleWithColumns(25)));
5002   EXPECT_EQ("#define A \\\n"
5003             "          \\\n"
5004             "  a;      \\\n"
5005             "  b;",
5006             format("#define A \\\n"
5007                    "          \\\n"
5008                    "  a;      \\\n"
5009                    "  b;",
5010                    getLLVMStyleWithColumns(11)));
5011   EXPECT_EQ("#define A \\\n"
5012             "  a;      \\\n"
5013             "          \\\n"
5014             "  b;",
5015             format("#define A \\\n"
5016                    "  a;      \\\n"
5017                    "          \\\n"
5018                    "  b;",
5019                    getLLVMStyleWithColumns(11)));
5020 }
5021 
5022 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
5023   verifyIncompleteFormat("#define A :");
5024   verifyFormat("#define SOMECASES  \\\n"
5025                "  case 1:          \\\n"
5026                "  case 2\n",
5027                getLLVMStyleWithColumns(20));
5028   verifyFormat("#define MACRO(a) \\\n"
5029                "  if (a)         \\\n"
5030                "    f();         \\\n"
5031                "  else           \\\n"
5032                "    g()",
5033                getLLVMStyleWithColumns(18));
5034   verifyFormat("#define A template <typename T>");
5035   verifyIncompleteFormat("#define STR(x) #x\n"
5036                          "f(STR(this_is_a_string_literal{));");
5037   verifyFormat("#pragma omp threadprivate( \\\n"
5038                "    y)), // expected-warning",
5039                getLLVMStyleWithColumns(28));
5040   verifyFormat("#d, = };");
5041   verifyFormat("#if \"a");
5042   verifyIncompleteFormat("({\n"
5043                          "#define b     \\\n"
5044                          "  }           \\\n"
5045                          "  a\n"
5046                          "a",
5047                          getLLVMStyleWithColumns(15));
5048   verifyFormat("#define A     \\\n"
5049                "  {           \\\n"
5050                "    {\n"
5051                "#define B     \\\n"
5052                "  }           \\\n"
5053                "  }",
5054                getLLVMStyleWithColumns(15));
5055   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
5056   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
5057   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
5058   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
5059 }
5060 
5061 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
5062   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
5063   EXPECT_EQ("class A : public QObject {\n"
5064             "  Q_OBJECT\n"
5065             "\n"
5066             "  A() {}\n"
5067             "};",
5068             format("class A  :  public QObject {\n"
5069                    "     Q_OBJECT\n"
5070                    "\n"
5071                    "  A() {\n}\n"
5072                    "}  ;"));
5073   EXPECT_EQ("MACRO\n"
5074             "/*static*/ int i;",
5075             format("MACRO\n"
5076                    " /*static*/ int   i;"));
5077   EXPECT_EQ("SOME_MACRO\n"
5078             "namespace {\n"
5079             "void f();\n"
5080             "} // namespace",
5081             format("SOME_MACRO\n"
5082                    "  namespace    {\n"
5083                    "void   f(  );\n"
5084                    "} // namespace"));
5085   // Only if the identifier contains at least 5 characters.
5086   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
5087   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
5088   // Only if everything is upper case.
5089   EXPECT_EQ("class A : public QObject {\n"
5090             "  Q_Object A() {}\n"
5091             "};",
5092             format("class A  :  public QObject {\n"
5093                    "     Q_Object\n"
5094                    "  A() {\n}\n"
5095                    "}  ;"));
5096 
5097   // Only if the next line can actually start an unwrapped line.
5098   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
5099             format("SOME_WEIRD_LOG_MACRO\n"
5100                    "<< SomeThing;"));
5101 
5102   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
5103                "(n, buffers))\n",
5104                getChromiumStyle(FormatStyle::LK_Cpp));
5105 
5106   // See PR41483
5107   EXPECT_EQ("/**/ FOO(a)\n"
5108             "FOO(b)",
5109             format("/**/ FOO(a)\n"
5110                    "FOO(b)"));
5111 }
5112 
5113 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
5114   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5115             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5116             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5117             "class X {};\n"
5118             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5119             "int *createScopDetectionPass() { return 0; }",
5120             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5121                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5122                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5123                    "  class X {};\n"
5124                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5125                    "  int *createScopDetectionPass() { return 0; }"));
5126   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
5127   // braces, so that inner block is indented one level more.
5128   EXPECT_EQ("int q() {\n"
5129             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5130             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5131             "  IPC_END_MESSAGE_MAP()\n"
5132             "}",
5133             format("int q() {\n"
5134                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5135                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5136                    "  IPC_END_MESSAGE_MAP()\n"
5137                    "}"));
5138 
5139   // Same inside macros.
5140   EXPECT_EQ("#define LIST(L) \\\n"
5141             "  L(A)          \\\n"
5142             "  L(B)          \\\n"
5143             "  L(C)",
5144             format("#define LIST(L) \\\n"
5145                    "  L(A) \\\n"
5146                    "  L(B) \\\n"
5147                    "  L(C)",
5148                    getGoogleStyle()));
5149 
5150   // These must not be recognized as macros.
5151   EXPECT_EQ("int q() {\n"
5152             "  f(x);\n"
5153             "  f(x) {}\n"
5154             "  f(x)->g();\n"
5155             "  f(x)->*g();\n"
5156             "  f(x).g();\n"
5157             "  f(x) = x;\n"
5158             "  f(x) += x;\n"
5159             "  f(x) -= x;\n"
5160             "  f(x) *= x;\n"
5161             "  f(x) /= x;\n"
5162             "  f(x) %= x;\n"
5163             "  f(x) &= x;\n"
5164             "  f(x) |= x;\n"
5165             "  f(x) ^= x;\n"
5166             "  f(x) >>= x;\n"
5167             "  f(x) <<= x;\n"
5168             "  f(x)[y].z();\n"
5169             "  LOG(INFO) << x;\n"
5170             "  ifstream(x) >> x;\n"
5171             "}\n",
5172             format("int q() {\n"
5173                    "  f(x)\n;\n"
5174                    "  f(x)\n {}\n"
5175                    "  f(x)\n->g();\n"
5176                    "  f(x)\n->*g();\n"
5177                    "  f(x)\n.g();\n"
5178                    "  f(x)\n = x;\n"
5179                    "  f(x)\n += x;\n"
5180                    "  f(x)\n -= x;\n"
5181                    "  f(x)\n *= x;\n"
5182                    "  f(x)\n /= x;\n"
5183                    "  f(x)\n %= x;\n"
5184                    "  f(x)\n &= x;\n"
5185                    "  f(x)\n |= x;\n"
5186                    "  f(x)\n ^= x;\n"
5187                    "  f(x)\n >>= x;\n"
5188                    "  f(x)\n <<= x;\n"
5189                    "  f(x)\n[y].z();\n"
5190                    "  LOG(INFO)\n << x;\n"
5191                    "  ifstream(x)\n >> x;\n"
5192                    "}\n"));
5193   EXPECT_EQ("int q() {\n"
5194             "  F(x)\n"
5195             "  if (1) {\n"
5196             "  }\n"
5197             "  F(x)\n"
5198             "  while (1) {\n"
5199             "  }\n"
5200             "  F(x)\n"
5201             "  G(x);\n"
5202             "  F(x)\n"
5203             "  try {\n"
5204             "    Q();\n"
5205             "  } catch (...) {\n"
5206             "  }\n"
5207             "}\n",
5208             format("int q() {\n"
5209                    "F(x)\n"
5210                    "if (1) {}\n"
5211                    "F(x)\n"
5212                    "while (1) {}\n"
5213                    "F(x)\n"
5214                    "G(x);\n"
5215                    "F(x)\n"
5216                    "try { Q(); } catch (...) {}\n"
5217                    "}\n"));
5218   EXPECT_EQ("class A {\n"
5219             "  A() : t(0) {}\n"
5220             "  A(int i) noexcept() : {}\n"
5221             "  A(X x)\n" // FIXME: function-level try blocks are broken.
5222             "  try : t(0) {\n"
5223             "  } catch (...) {\n"
5224             "  }\n"
5225             "};",
5226             format("class A {\n"
5227                    "  A()\n : t(0) {}\n"
5228                    "  A(int i)\n noexcept() : {}\n"
5229                    "  A(X x)\n"
5230                    "  try : t(0) {} catch (...) {}\n"
5231                    "};"));
5232   FormatStyle Style = getLLVMStyle();
5233   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5234   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5235   Style.BraceWrapping.AfterFunction = true;
5236   EXPECT_EQ("void f()\n"
5237             "try\n"
5238             "{\n"
5239             "}",
5240             format("void f() try {\n"
5241                    "}",
5242                    Style));
5243   EXPECT_EQ("class SomeClass {\n"
5244             "public:\n"
5245             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5246             "};",
5247             format("class SomeClass {\n"
5248                    "public:\n"
5249                    "  SomeClass()\n"
5250                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5251                    "};"));
5252   EXPECT_EQ("class SomeClass {\n"
5253             "public:\n"
5254             "  SomeClass()\n"
5255             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5256             "};",
5257             format("class SomeClass {\n"
5258                    "public:\n"
5259                    "  SomeClass()\n"
5260                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5261                    "};",
5262                    getLLVMStyleWithColumns(40)));
5263 
5264   verifyFormat("MACRO(>)");
5265 
5266   // Some macros contain an implicit semicolon.
5267   Style = getLLVMStyle();
5268   Style.StatementMacros.push_back("FOO");
5269   verifyFormat("FOO(a) int b = 0;");
5270   verifyFormat("FOO(a)\n"
5271                "int b = 0;",
5272                Style);
5273   verifyFormat("FOO(a);\n"
5274                "int b = 0;",
5275                Style);
5276   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
5277                "int b = 0;",
5278                Style);
5279   verifyFormat("FOO()\n"
5280                "int b = 0;",
5281                Style);
5282   verifyFormat("FOO\n"
5283                "int b = 0;",
5284                Style);
5285   verifyFormat("void f() {\n"
5286                "  FOO(a)\n"
5287                "  return a;\n"
5288                "}",
5289                Style);
5290   verifyFormat("FOO(a)\n"
5291                "FOO(b)",
5292                Style);
5293   verifyFormat("int a = 0;\n"
5294                "FOO(b)\n"
5295                "int c = 0;",
5296                Style);
5297   verifyFormat("int a = 0;\n"
5298                "int x = FOO(a)\n"
5299                "int b = 0;",
5300                Style);
5301   verifyFormat("void foo(int a) { FOO(a) }\n"
5302                "uint32_t bar() {}",
5303                Style);
5304 }
5305 
5306 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
5307   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
5308 
5309   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
5310                ZeroColumn);
5311 }
5312 
5313 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5314   verifyFormat("#define A \\\n"
5315                "  f({     \\\n"
5316                "    g();  \\\n"
5317                "  });",
5318                getLLVMStyleWithColumns(11));
5319 }
5320 
5321 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5322   FormatStyle Style = getLLVMStyleWithColumns(40);
5323   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5324   verifyFormat("#ifdef _WIN32\n"
5325                "#define A 0\n"
5326                "#ifdef VAR2\n"
5327                "#define B 1\n"
5328                "#include <someheader.h>\n"
5329                "#define MACRO                          \\\n"
5330                "  some_very_long_func_aaaaaaaaaa();\n"
5331                "#endif\n"
5332                "#else\n"
5333                "#define A 1\n"
5334                "#endif",
5335                Style);
5336   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5337   verifyFormat("#ifdef _WIN32\n"
5338                "#  define A 0\n"
5339                "#  ifdef VAR2\n"
5340                "#    define B 1\n"
5341                "#    include <someheader.h>\n"
5342                "#    define MACRO                      \\\n"
5343                "      some_very_long_func_aaaaaaaaaa();\n"
5344                "#  endif\n"
5345                "#else\n"
5346                "#  define A 1\n"
5347                "#endif",
5348                Style);
5349   verifyFormat("#if A\n"
5350                "#  define MACRO                        \\\n"
5351                "    void a(int x) {                    \\\n"
5352                "      b();                             \\\n"
5353                "      c();                             \\\n"
5354                "      d();                             \\\n"
5355                "      e();                             \\\n"
5356                "      f();                             \\\n"
5357                "    }\n"
5358                "#endif",
5359                Style);
5360   // Comments before include guard.
5361   verifyFormat("// file comment\n"
5362                "// file comment\n"
5363                "#ifndef HEADER_H\n"
5364                "#define HEADER_H\n"
5365                "code();\n"
5366                "#endif",
5367                Style);
5368   // Test with include guards.
5369   verifyFormat("#ifndef HEADER_H\n"
5370                "#define HEADER_H\n"
5371                "code();\n"
5372                "#endif",
5373                Style);
5374   // Include guards must have a #define with the same variable immediately
5375   // after #ifndef.
5376   verifyFormat("#ifndef NOT_GUARD\n"
5377                "#  define FOO\n"
5378                "code();\n"
5379                "#endif",
5380                Style);
5381 
5382   // Include guards must cover the entire file.
5383   verifyFormat("code();\n"
5384                "code();\n"
5385                "#ifndef NOT_GUARD\n"
5386                "#  define NOT_GUARD\n"
5387                "code();\n"
5388                "#endif",
5389                Style);
5390   verifyFormat("#ifndef NOT_GUARD\n"
5391                "#  define NOT_GUARD\n"
5392                "code();\n"
5393                "#endif\n"
5394                "code();",
5395                Style);
5396   // Test with trailing blank lines.
5397   verifyFormat("#ifndef HEADER_H\n"
5398                "#define HEADER_H\n"
5399                "code();\n"
5400                "#endif\n",
5401                Style);
5402   // Include guards don't have #else.
5403   verifyFormat("#ifndef NOT_GUARD\n"
5404                "#  define NOT_GUARD\n"
5405                "code();\n"
5406                "#else\n"
5407                "#endif",
5408                Style);
5409   verifyFormat("#ifndef NOT_GUARD\n"
5410                "#  define NOT_GUARD\n"
5411                "code();\n"
5412                "#elif FOO\n"
5413                "#endif",
5414                Style);
5415   // Non-identifier #define after potential include guard.
5416   verifyFormat("#ifndef FOO\n"
5417                "#  define 1\n"
5418                "#endif\n",
5419                Style);
5420   // #if closes past last non-preprocessor line.
5421   verifyFormat("#ifndef FOO\n"
5422                "#define FOO\n"
5423                "#if 1\n"
5424                "int i;\n"
5425                "#  define A 0\n"
5426                "#endif\n"
5427                "#endif\n",
5428                Style);
5429   // Don't crash if there is an #elif directive without a condition.
5430   verifyFormat("#if 1\n"
5431                "int x;\n"
5432                "#elif\n"
5433                "int y;\n"
5434                "#else\n"
5435                "int z;\n"
5436                "#endif",
5437                Style);
5438   // FIXME: This doesn't handle the case where there's code between the
5439   // #ifndef and #define but all other conditions hold. This is because when
5440   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5441   // previous code line yet, so we can't detect it.
5442   EXPECT_EQ("#ifndef NOT_GUARD\n"
5443             "code();\n"
5444             "#define NOT_GUARD\n"
5445             "code();\n"
5446             "#endif",
5447             format("#ifndef NOT_GUARD\n"
5448                    "code();\n"
5449                    "#  define NOT_GUARD\n"
5450                    "code();\n"
5451                    "#endif",
5452                    Style));
5453   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5454   // be outside an include guard. Examples are #pragma once and
5455   // #pragma GCC diagnostic, or anything else that does not change the meaning
5456   // of the file if it's included multiple times.
5457   EXPECT_EQ("#ifdef WIN32\n"
5458             "#  pragma once\n"
5459             "#endif\n"
5460             "#ifndef HEADER_H\n"
5461             "#  define HEADER_H\n"
5462             "code();\n"
5463             "#endif",
5464             format("#ifdef WIN32\n"
5465                    "#  pragma once\n"
5466                    "#endif\n"
5467                    "#ifndef HEADER_H\n"
5468                    "#define HEADER_H\n"
5469                    "code();\n"
5470                    "#endif",
5471                    Style));
5472   // FIXME: This does not detect when there is a single non-preprocessor line
5473   // in front of an include-guard-like structure where other conditions hold
5474   // because ScopedLineState hides the line.
5475   EXPECT_EQ("code();\n"
5476             "#ifndef HEADER_H\n"
5477             "#define HEADER_H\n"
5478             "code();\n"
5479             "#endif",
5480             format("code();\n"
5481                    "#ifndef HEADER_H\n"
5482                    "#  define HEADER_H\n"
5483                    "code();\n"
5484                    "#endif",
5485                    Style));
5486   // Keep comments aligned with #, otherwise indent comments normally. These
5487   // tests cannot use verifyFormat because messUp manipulates leading
5488   // whitespace.
5489   {
5490     const char *Expected = ""
5491                            "void f() {\n"
5492                            "#if 1\n"
5493                            "// Preprocessor aligned.\n"
5494                            "#  define A 0\n"
5495                            "  // Code. Separated by blank line.\n"
5496                            "\n"
5497                            "#  define B 0\n"
5498                            "  // Code. Not aligned with #\n"
5499                            "#  define C 0\n"
5500                            "#endif";
5501     const char *ToFormat = ""
5502                            "void f() {\n"
5503                            "#if 1\n"
5504                            "// Preprocessor aligned.\n"
5505                            "#  define A 0\n"
5506                            "// Code. Separated by blank line.\n"
5507                            "\n"
5508                            "#  define B 0\n"
5509                            "   // Code. Not aligned with #\n"
5510                            "#  define C 0\n"
5511                            "#endif";
5512     EXPECT_EQ(Expected, format(ToFormat, Style));
5513     EXPECT_EQ(Expected, format(Expected, Style));
5514   }
5515   // Keep block quotes aligned.
5516   {
5517     const char *Expected = ""
5518                            "void f() {\n"
5519                            "#if 1\n"
5520                            "/* Preprocessor aligned. */\n"
5521                            "#  define A 0\n"
5522                            "  /* Code. Separated by blank line. */\n"
5523                            "\n"
5524                            "#  define B 0\n"
5525                            "  /* Code. Not aligned with # */\n"
5526                            "#  define C 0\n"
5527                            "#endif";
5528     const char *ToFormat = ""
5529                            "void f() {\n"
5530                            "#if 1\n"
5531                            "/* Preprocessor aligned. */\n"
5532                            "#  define A 0\n"
5533                            "/* Code. Separated by blank line. */\n"
5534                            "\n"
5535                            "#  define B 0\n"
5536                            "   /* Code. Not aligned with # */\n"
5537                            "#  define C 0\n"
5538                            "#endif";
5539     EXPECT_EQ(Expected, format(ToFormat, Style));
5540     EXPECT_EQ(Expected, format(Expected, Style));
5541   }
5542   // Keep comments aligned with un-indented directives.
5543   {
5544     const char *Expected = ""
5545                            "void f() {\n"
5546                            "// Preprocessor aligned.\n"
5547                            "#define A 0\n"
5548                            "  // Code. Separated by blank line.\n"
5549                            "\n"
5550                            "#define B 0\n"
5551                            "  // Code. Not aligned with #\n"
5552                            "#define C 0\n";
5553     const char *ToFormat = ""
5554                            "void f() {\n"
5555                            "// Preprocessor aligned.\n"
5556                            "#define A 0\n"
5557                            "// Code. Separated by blank line.\n"
5558                            "\n"
5559                            "#define B 0\n"
5560                            "   // Code. Not aligned with #\n"
5561                            "#define C 0\n";
5562     EXPECT_EQ(Expected, format(ToFormat, Style));
5563     EXPECT_EQ(Expected, format(Expected, Style));
5564   }
5565   // Test AfterHash with tabs.
5566   {
5567     FormatStyle Tabbed = Style;
5568     Tabbed.UseTab = FormatStyle::UT_Always;
5569     Tabbed.IndentWidth = 8;
5570     Tabbed.TabWidth = 8;
5571     verifyFormat("#ifdef _WIN32\n"
5572                  "#\tdefine A 0\n"
5573                  "#\tifdef VAR2\n"
5574                  "#\t\tdefine B 1\n"
5575                  "#\t\tinclude <someheader.h>\n"
5576                  "#\t\tdefine MACRO          \\\n"
5577                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5578                  "#\tendif\n"
5579                  "#else\n"
5580                  "#\tdefine A 1\n"
5581                  "#endif",
5582                  Tabbed);
5583   }
5584 
5585   // Regression test: Multiline-macro inside include guards.
5586   verifyFormat("#ifndef HEADER_H\n"
5587                "#define HEADER_H\n"
5588                "#define A()        \\\n"
5589                "  int i;           \\\n"
5590                "  int j;\n"
5591                "#endif // HEADER_H",
5592                getLLVMStyleWithColumns(20));
5593 
5594   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5595   // Basic before hash indent tests
5596   verifyFormat("#ifdef _WIN32\n"
5597                "  #define A 0\n"
5598                "  #ifdef VAR2\n"
5599                "    #define B 1\n"
5600                "    #include <someheader.h>\n"
5601                "    #define MACRO                      \\\n"
5602                "      some_very_long_func_aaaaaaaaaa();\n"
5603                "  #endif\n"
5604                "#else\n"
5605                "  #define A 1\n"
5606                "#endif",
5607                Style);
5608   verifyFormat("#if A\n"
5609                "  #define MACRO                        \\\n"
5610                "    void a(int x) {                    \\\n"
5611                "      b();                             \\\n"
5612                "      c();                             \\\n"
5613                "      d();                             \\\n"
5614                "      e();                             \\\n"
5615                "      f();                             \\\n"
5616                "    }\n"
5617                "#endif",
5618                Style);
5619   // Keep comments aligned with indented directives. These
5620   // tests cannot use verifyFormat because messUp manipulates leading
5621   // whitespace.
5622   {
5623     const char *Expected = "void f() {\n"
5624                            "// Aligned to preprocessor.\n"
5625                            "#if 1\n"
5626                            "  // Aligned to code.\n"
5627                            "  int a;\n"
5628                            "  #if 1\n"
5629                            "    // Aligned to preprocessor.\n"
5630                            "    #define A 0\n"
5631                            "  // Aligned to code.\n"
5632                            "  int b;\n"
5633                            "  #endif\n"
5634                            "#endif\n"
5635                            "}";
5636     const char *ToFormat = "void f() {\n"
5637                            "// Aligned to preprocessor.\n"
5638                            "#if 1\n"
5639                            "// Aligned to code.\n"
5640                            "int a;\n"
5641                            "#if 1\n"
5642                            "// Aligned to preprocessor.\n"
5643                            "#define A 0\n"
5644                            "// Aligned to code.\n"
5645                            "int b;\n"
5646                            "#endif\n"
5647                            "#endif\n"
5648                            "}";
5649     EXPECT_EQ(Expected, format(ToFormat, Style));
5650     EXPECT_EQ(Expected, format(Expected, Style));
5651   }
5652   {
5653     const char *Expected = "void f() {\n"
5654                            "/* Aligned to preprocessor. */\n"
5655                            "#if 1\n"
5656                            "  /* Aligned to code. */\n"
5657                            "  int a;\n"
5658                            "  #if 1\n"
5659                            "    /* Aligned to preprocessor. */\n"
5660                            "    #define A 0\n"
5661                            "  /* Aligned to code. */\n"
5662                            "  int b;\n"
5663                            "  #endif\n"
5664                            "#endif\n"
5665                            "}";
5666     const char *ToFormat = "void f() {\n"
5667                            "/* Aligned to preprocessor. */\n"
5668                            "#if 1\n"
5669                            "/* Aligned to code. */\n"
5670                            "int a;\n"
5671                            "#if 1\n"
5672                            "/* Aligned to preprocessor. */\n"
5673                            "#define A 0\n"
5674                            "/* Aligned to code. */\n"
5675                            "int b;\n"
5676                            "#endif\n"
5677                            "#endif\n"
5678                            "}";
5679     EXPECT_EQ(Expected, format(ToFormat, Style));
5680     EXPECT_EQ(Expected, format(Expected, Style));
5681   }
5682 
5683   // Test single comment before preprocessor
5684   verifyFormat("// Comment\n"
5685                "\n"
5686                "#if 1\n"
5687                "#endif",
5688                Style);
5689 }
5690 
5691 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5692   verifyFormat("{\n  { a #c; }\n}");
5693 }
5694 
5695 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5696   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5697             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5698   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5699             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5700 }
5701 
5702 TEST_F(FormatTest, EscapedNewlines) {
5703   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5704   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5705             format("#define A \\\nint i;\\\n  int j;", Narrow));
5706   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5707   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5708   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5709   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5710 
5711   FormatStyle AlignLeft = getLLVMStyle();
5712   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5713   EXPECT_EQ("#define MACRO(x) \\\n"
5714             "private:         \\\n"
5715             "  int x(int a);\n",
5716             format("#define MACRO(x) \\\n"
5717                    "private:         \\\n"
5718                    "  int x(int a);\n",
5719                    AlignLeft));
5720 
5721   // CRLF line endings
5722   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5723             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5724   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5725   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5726   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5727   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5728   EXPECT_EQ("#define MACRO(x) \\\r\n"
5729             "private:         \\\r\n"
5730             "  int x(int a);\r\n",
5731             format("#define MACRO(x) \\\r\n"
5732                    "private:         \\\r\n"
5733                    "  int x(int a);\r\n",
5734                    AlignLeft));
5735 
5736   FormatStyle DontAlign = getLLVMStyle();
5737   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5738   DontAlign.MaxEmptyLinesToKeep = 3;
5739   // FIXME: can't use verifyFormat here because the newline before
5740   // "public:" is not inserted the first time it's reformatted
5741   EXPECT_EQ("#define A \\\n"
5742             "  class Foo { \\\n"
5743             "    void bar(); \\\n"
5744             "\\\n"
5745             "\\\n"
5746             "\\\n"
5747             "  public: \\\n"
5748             "    void baz(); \\\n"
5749             "  };",
5750             format("#define A \\\n"
5751                    "  class Foo { \\\n"
5752                    "    void bar(); \\\n"
5753                    "\\\n"
5754                    "\\\n"
5755                    "\\\n"
5756                    "  public: \\\n"
5757                    "    void baz(); \\\n"
5758                    "  };",
5759                    DontAlign));
5760 }
5761 
5762 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5763   verifyFormat("#define A \\\n"
5764                "  int v(  \\\n"
5765                "      a); \\\n"
5766                "  int i;",
5767                getLLVMStyleWithColumns(11));
5768 }
5769 
5770 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5771   EXPECT_EQ(
5772       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5773       "                      \\\n"
5774       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5775       "\n"
5776       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5777       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5778       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5779              "\\\n"
5780              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5781              "  \n"
5782              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5783              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5784 }
5785 
5786 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5787   EXPECT_EQ("int\n"
5788             "#define A\n"
5789             "    a;",
5790             format("int\n#define A\na;"));
5791   verifyFormat("functionCallTo(\n"
5792                "    someOtherFunction(\n"
5793                "        withSomeParameters, whichInSequence,\n"
5794                "        areLongerThanALine(andAnotherCall,\n"
5795                "#define A B\n"
5796                "                           withMoreParamters,\n"
5797                "                           whichStronglyInfluenceTheLayout),\n"
5798                "        andMoreParameters),\n"
5799                "    trailing);",
5800                getLLVMStyleWithColumns(69));
5801   verifyFormat("Foo::Foo()\n"
5802                "#ifdef BAR\n"
5803                "    : baz(0)\n"
5804                "#endif\n"
5805                "{\n"
5806                "}");
5807   verifyFormat("void f() {\n"
5808                "  if (true)\n"
5809                "#ifdef A\n"
5810                "    f(42);\n"
5811                "  x();\n"
5812                "#else\n"
5813                "    g();\n"
5814                "  x();\n"
5815                "#endif\n"
5816                "}");
5817   verifyFormat("void f(param1, param2,\n"
5818                "       param3,\n"
5819                "#ifdef A\n"
5820                "       param4(param5,\n"
5821                "#ifdef A1\n"
5822                "              param6,\n"
5823                "#ifdef A2\n"
5824                "              param7),\n"
5825                "#else\n"
5826                "              param8),\n"
5827                "       param9,\n"
5828                "#endif\n"
5829                "       param10,\n"
5830                "#endif\n"
5831                "       param11)\n"
5832                "#else\n"
5833                "       param12)\n"
5834                "#endif\n"
5835                "{\n"
5836                "  x();\n"
5837                "}",
5838                getLLVMStyleWithColumns(28));
5839   verifyFormat("#if 1\n"
5840                "int i;");
5841   verifyFormat("#if 1\n"
5842                "#endif\n"
5843                "#if 1\n"
5844                "#else\n"
5845                "#endif\n");
5846   verifyFormat("DEBUG({\n"
5847                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5848                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5849                "});\n"
5850                "#if a\n"
5851                "#else\n"
5852                "#endif");
5853 
5854   verifyIncompleteFormat("void f(\n"
5855                          "#if A\n"
5856                          ");\n"
5857                          "#else\n"
5858                          "#endif");
5859 }
5860 
5861 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5862   verifyFormat("#endif\n"
5863                "#if B");
5864 }
5865 
5866 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5867   FormatStyle SingleLine = getLLVMStyle();
5868   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5869   verifyFormat("#if 0\n"
5870                "#elif 1\n"
5871                "#endif\n"
5872                "void foo() {\n"
5873                "  if (test) foo2();\n"
5874                "}",
5875                SingleLine);
5876 }
5877 
5878 TEST_F(FormatTest, LayoutBlockInsideParens) {
5879   verifyFormat("functionCall({ int i; });");
5880   verifyFormat("functionCall({\n"
5881                "  int i;\n"
5882                "  int j;\n"
5883                "});");
5884   verifyFormat("functionCall(\n"
5885                "    {\n"
5886                "      int i;\n"
5887                "      int j;\n"
5888                "    },\n"
5889                "    aaaa, bbbb, cccc);");
5890   verifyFormat("functionA(functionB({\n"
5891                "            int i;\n"
5892                "            int j;\n"
5893                "          }),\n"
5894                "          aaaa, bbbb, cccc);");
5895   verifyFormat("functionCall(\n"
5896                "    {\n"
5897                "      int i;\n"
5898                "      int j;\n"
5899                "    },\n"
5900                "    aaaa, bbbb, // comment\n"
5901                "    cccc);");
5902   verifyFormat("functionA(functionB({\n"
5903                "            int i;\n"
5904                "            int j;\n"
5905                "          }),\n"
5906                "          aaaa, bbbb, // comment\n"
5907                "          cccc);");
5908   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5909   verifyFormat("functionCall(aaaa, bbbb, {\n"
5910                "  int i;\n"
5911                "  int j;\n"
5912                "});");
5913   verifyFormat(
5914       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5915       "    {\n"
5916       "      int i; // break\n"
5917       "    },\n"
5918       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5919       "                                     ccccccccccccccccc));");
5920   verifyFormat("DEBUG({\n"
5921                "  if (a)\n"
5922                "    f();\n"
5923                "});");
5924 }
5925 
5926 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5927   EXPECT_EQ("SOME_MACRO { int i; }\n"
5928             "int i;",
5929             format("  SOME_MACRO  {int i;}  int i;"));
5930 }
5931 
5932 TEST_F(FormatTest, LayoutNestedBlocks) {
5933   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5934                "  struct s {\n"
5935                "    int i;\n"
5936                "  };\n"
5937                "  s kBitsToOs[] = {{10}};\n"
5938                "  for (int i = 0; i < 10; ++i)\n"
5939                "    return;\n"
5940                "}");
5941   verifyFormat("call(parameter, {\n"
5942                "  something();\n"
5943                "  // Comment using all columns.\n"
5944                "  somethingelse();\n"
5945                "});",
5946                getLLVMStyleWithColumns(40));
5947   verifyFormat("DEBUG( //\n"
5948                "    { f(); }, a);");
5949   verifyFormat("DEBUG( //\n"
5950                "    {\n"
5951                "      f(); //\n"
5952                "    },\n"
5953                "    a);");
5954 
5955   EXPECT_EQ("call(parameter, {\n"
5956             "  something();\n"
5957             "  // Comment too\n"
5958             "  // looooooooooong.\n"
5959             "  somethingElse();\n"
5960             "});",
5961             format("call(parameter, {\n"
5962                    "  something();\n"
5963                    "  // Comment too looooooooooong.\n"
5964                    "  somethingElse();\n"
5965                    "});",
5966                    getLLVMStyleWithColumns(29)));
5967   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5968   EXPECT_EQ("DEBUG({ // comment\n"
5969             "  int i;\n"
5970             "});",
5971             format("DEBUG({ // comment\n"
5972                    "int  i;\n"
5973                    "});"));
5974   EXPECT_EQ("DEBUG({\n"
5975             "  int i;\n"
5976             "\n"
5977             "  // comment\n"
5978             "  int j;\n"
5979             "});",
5980             format("DEBUG({\n"
5981                    "  int  i;\n"
5982                    "\n"
5983                    "  // comment\n"
5984                    "  int  j;\n"
5985                    "});"));
5986 
5987   verifyFormat("DEBUG({\n"
5988                "  if (a)\n"
5989                "    return;\n"
5990                "});");
5991   verifyGoogleFormat("DEBUG({\n"
5992                      "  if (a) return;\n"
5993                      "});");
5994   FormatStyle Style = getGoogleStyle();
5995   Style.ColumnLimit = 45;
5996   verifyFormat("Debug(\n"
5997                "    aaaaa,\n"
5998                "    {\n"
5999                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
6000                "    },\n"
6001                "    a);",
6002                Style);
6003 
6004   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
6005 
6006   verifyNoCrash("^{v^{a}}");
6007 }
6008 
6009 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
6010   EXPECT_EQ("#define MACRO()                     \\\n"
6011             "  Debug(aaa, /* force line break */ \\\n"
6012             "        {                           \\\n"
6013             "          int i;                    \\\n"
6014             "          int j;                    \\\n"
6015             "        })",
6016             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
6017                    "          {  int   i;  int  j;   })",
6018                    getGoogleStyle()));
6019 
6020   EXPECT_EQ("#define A                                       \\\n"
6021             "  [] {                                          \\\n"
6022             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
6023             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
6024             "  }",
6025             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
6026                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
6027                    getGoogleStyle()));
6028 }
6029 
6030 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
6031   EXPECT_EQ("{}", format("{}"));
6032   verifyFormat("enum E {};");
6033   verifyFormat("enum E {}");
6034   FormatStyle Style = getLLVMStyle();
6035   Style.SpaceInEmptyBlock = true;
6036   EXPECT_EQ("void f() { }", format("void f() {}", Style));
6037   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
6038   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
6039   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
6040   Style.BraceWrapping.BeforeElse = false;
6041   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
6042   verifyFormat("if (a)\n"
6043                "{\n"
6044                "} else if (b)\n"
6045                "{\n"
6046                "} else\n"
6047                "{ }",
6048                Style);
6049   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
6050   verifyFormat("if (a) {\n"
6051                "} else if (b) {\n"
6052                "} else {\n"
6053                "}",
6054                Style);
6055   Style.BraceWrapping.BeforeElse = true;
6056   verifyFormat("if (a) { }\n"
6057                "else if (b) { }\n"
6058                "else { }",
6059                Style);
6060 }
6061 
6062 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
6063   FormatStyle Style = getLLVMStyle();
6064   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
6065   Style.MacroBlockEnd = "^[A-Z_]+_END$";
6066   verifyFormat("FOO_BEGIN\n"
6067                "  FOO_ENTRY\n"
6068                "FOO_END",
6069                Style);
6070   verifyFormat("FOO_BEGIN\n"
6071                "  NESTED_FOO_BEGIN\n"
6072                "    NESTED_FOO_ENTRY\n"
6073                "  NESTED_FOO_END\n"
6074                "FOO_END",
6075                Style);
6076   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
6077                "  int x;\n"
6078                "  x = 1;\n"
6079                "FOO_END(Baz)",
6080                Style);
6081 }
6082 
6083 //===----------------------------------------------------------------------===//
6084 // Line break tests.
6085 //===----------------------------------------------------------------------===//
6086 
6087 TEST_F(FormatTest, PreventConfusingIndents) {
6088   verifyFormat(
6089       "void f() {\n"
6090       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
6091       "                         parameter, parameter, parameter)),\n"
6092       "                     SecondLongCall(parameter));\n"
6093       "}");
6094   verifyFormat(
6095       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6096       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6097       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6098       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
6099   verifyFormat(
6100       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6101       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
6102       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6103       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
6104   verifyFormat(
6105       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
6106       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
6107       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
6108       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
6109   verifyFormat("int a = bbbb && ccc &&\n"
6110                "        fffff(\n"
6111                "#define A Just forcing a new line\n"
6112                "            ddd);");
6113 }
6114 
6115 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
6116   verifyFormat(
6117       "bool aaaaaaa =\n"
6118       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
6119       "    bbbbbbbb();");
6120   verifyFormat(
6121       "bool aaaaaaa =\n"
6122       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
6123       "    bbbbbbbb();");
6124 
6125   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6126                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
6127                "    ccccccccc == ddddddddddd;");
6128   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6129                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
6130                "    ccccccccc == ddddddddddd;");
6131   verifyFormat(
6132       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6133       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
6134       "    ccccccccc == ddddddddddd;");
6135 
6136   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6137                "                 aaaaaa) &&\n"
6138                "         bbbbbb && cccccc;");
6139   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6140                "                 aaaaaa) >>\n"
6141                "         bbbbbb;");
6142   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
6143                "    SourceMgr.getSpellingColumnNumber(\n"
6144                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
6145                "    1);");
6146 
6147   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6148                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
6149                "    cccccc) {\n}");
6150   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6151                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6152                "              cccccc) {\n}");
6153   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6154                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6155                "              cccccc) {\n}");
6156   verifyFormat("b = a &&\n"
6157                "    // Comment\n"
6158                "    b.c && d;");
6159 
6160   // If the LHS of a comparison is not a binary expression itself, the
6161   // additional linebreak confuses many people.
6162   verifyFormat(
6163       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6164       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
6165       "}");
6166   verifyFormat(
6167       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6168       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6169       "}");
6170   verifyFormat(
6171       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
6172       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6173       "}");
6174   verifyFormat(
6175       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6176       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
6177       "}");
6178   // Even explicit parentheses stress the precedence enough to make the
6179   // additional break unnecessary.
6180   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6181                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6182                "}");
6183   // This cases is borderline, but with the indentation it is still readable.
6184   verifyFormat(
6185       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6186       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6187       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6188       "}",
6189       getLLVMStyleWithColumns(75));
6190 
6191   // If the LHS is a binary expression, we should still use the additional break
6192   // as otherwise the formatting hides the operator precedence.
6193   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6194                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6195                "    5) {\n"
6196                "}");
6197   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6198                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
6199                "    5) {\n"
6200                "}");
6201 
6202   FormatStyle OnePerLine = getLLVMStyle();
6203   OnePerLine.BinPackParameters = false;
6204   verifyFormat(
6205       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6206       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6207       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
6208       OnePerLine);
6209 
6210   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
6211                "                .aaa(aaaaaaaaaaaaa) *\n"
6212                "            aaaaaaa +\n"
6213                "        aaaaaaa;",
6214                getLLVMStyleWithColumns(40));
6215 }
6216 
6217 TEST_F(FormatTest, ExpressionIndentation) {
6218   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6219                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6220                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6221                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6222                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6223                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
6224                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6225                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
6226                "                 ccccccccccccccccccccccccccccccccccccccccc;");
6227   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6228                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6229                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6230                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6231   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6232                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6233                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6234                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6235   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6236                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6237                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6238                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6239   verifyFormat("if () {\n"
6240                "} else if (aaaaa && bbbbb > // break\n"
6241                "                        ccccc) {\n"
6242                "}");
6243   verifyFormat("if () {\n"
6244                "} else if constexpr (aaaaa && bbbbb > // break\n"
6245                "                                  ccccc) {\n"
6246                "}");
6247   verifyFormat("if () {\n"
6248                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
6249                "                                  ccccc) {\n"
6250                "}");
6251   verifyFormat("if () {\n"
6252                "} else if (aaaaa &&\n"
6253                "           bbbbb > // break\n"
6254                "               ccccc &&\n"
6255                "           ddddd) {\n"
6256                "}");
6257 
6258   // Presence of a trailing comment used to change indentation of b.
6259   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
6260                "       b;\n"
6261                "return aaaaaaaaaaaaaaaaaaa +\n"
6262                "       b; //",
6263                getLLVMStyleWithColumns(30));
6264 }
6265 
6266 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
6267   // Not sure what the best system is here. Like this, the LHS can be found
6268   // immediately above an operator (everything with the same or a higher
6269   // indent). The RHS is aligned right of the operator and so compasses
6270   // everything until something with the same indent as the operator is found.
6271   // FIXME: Is this a good system?
6272   FormatStyle Style = getLLVMStyle();
6273   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6274   verifyFormat(
6275       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6276       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6277       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6278       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6279       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6280       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6281       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6282       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6283       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
6284       Style);
6285   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6286                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6287                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6288                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6289                Style);
6290   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6291                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6292                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6293                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6294                Style);
6295   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6296                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6297                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6298                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6299                Style);
6300   verifyFormat("if () {\n"
6301                "} else if (aaaaa\n"
6302                "           && bbbbb // break\n"
6303                "                  > ccccc) {\n"
6304                "}",
6305                Style);
6306   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6307                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6308                Style);
6309   verifyFormat("return (a)\n"
6310                "       // comment\n"
6311                "       + b;",
6312                Style);
6313   verifyFormat(
6314       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6315       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6316       "             + cc;",
6317       Style);
6318 
6319   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6320                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6321                Style);
6322 
6323   // Forced by comments.
6324   verifyFormat(
6325       "unsigned ContentSize =\n"
6326       "    sizeof(int16_t)   // DWARF ARange version number\n"
6327       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6328       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6329       "    + sizeof(int8_t); // Segment Size (in bytes)");
6330 
6331   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6332                "       == boost::fusion::at_c<1>(iiii).second;",
6333                Style);
6334 
6335   Style.ColumnLimit = 60;
6336   verifyFormat("zzzzzzzzzz\n"
6337                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6338                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6339                Style);
6340 
6341   Style.ColumnLimit = 80;
6342   Style.IndentWidth = 4;
6343   Style.TabWidth = 4;
6344   Style.UseTab = FormatStyle::UT_Always;
6345   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6346   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6347   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6348             "\t&& (someOtherLongishConditionPart1\n"
6349             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6350             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6351                    "(someOtherLongishConditionPart1 || "
6352                    "someOtherEvenLongerNestedConditionPart2);",
6353                    Style));
6354 }
6355 
6356 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6357   FormatStyle Style = getLLVMStyle();
6358   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6359   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6360 
6361   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6362                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6363                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6364                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6365                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6366                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6367                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6368                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6369                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6370                Style);
6371   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6372                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6373                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6374                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6375                Style);
6376   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6377                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6378                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6379                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6380                Style);
6381   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6382                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6383                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6384                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6385                Style);
6386   verifyFormat("if () {\n"
6387                "} else if (aaaaa\n"
6388                "           && bbbbb // break\n"
6389                "                  > ccccc) {\n"
6390                "}",
6391                Style);
6392   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6393                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6394                Style);
6395   verifyFormat("return (a)\n"
6396                "     // comment\n"
6397                "     + b;",
6398                Style);
6399   verifyFormat(
6400       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6401       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6402       "           + cc;",
6403       Style);
6404   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6405                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6406                "                        : 3333333333333333;",
6407                Style);
6408   verifyFormat(
6409       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6410       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6411       "                                             : eeeeeeeeeeeeeeeeee)\n"
6412       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6413       "                        : 3333333333333333;",
6414       Style);
6415   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6416                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6417                Style);
6418 
6419   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6420                "    == boost::fusion::at_c<1>(iiii).second;",
6421                Style);
6422 
6423   Style.ColumnLimit = 60;
6424   verifyFormat("zzzzzzzzzzzzz\n"
6425                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6426                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6427                Style);
6428 
6429   // Forced by comments.
6430   Style.ColumnLimit = 80;
6431   verifyFormat(
6432       "unsigned ContentSize\n"
6433       "    = sizeof(int16_t) // DWARF ARange version number\n"
6434       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6435       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6436       "    + sizeof(int8_t); // Segment Size (in bytes)",
6437       Style);
6438 
6439   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6440   verifyFormat(
6441       "unsigned ContentSize =\n"
6442       "    sizeof(int16_t)   // DWARF ARange version number\n"
6443       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6444       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6445       "    + sizeof(int8_t); // Segment Size (in bytes)",
6446       Style);
6447 
6448   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6449   verifyFormat(
6450       "unsigned ContentSize =\n"
6451       "    sizeof(int16_t)   // DWARF ARange version number\n"
6452       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6453       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6454       "    + sizeof(int8_t); // Segment Size (in bytes)",
6455       Style);
6456 }
6457 
6458 TEST_F(FormatTest, EnforcedOperatorWraps) {
6459   // Here we'd like to wrap after the || operators, but a comment is forcing an
6460   // earlier wrap.
6461   verifyFormat("bool x = aaaaa //\n"
6462                "         || bbbbb\n"
6463                "         //\n"
6464                "         || cccc;");
6465 }
6466 
6467 TEST_F(FormatTest, NoOperandAlignment) {
6468   FormatStyle Style = getLLVMStyle();
6469   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6470   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6471                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6472                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6473                Style);
6474   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6475   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6476                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6477                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6478                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6479                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6480                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6481                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6482                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6483                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6484                Style);
6485 
6486   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6487                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6488                "    + cc;",
6489                Style);
6490   verifyFormat("int a = aa\n"
6491                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6492                "        * cccccccccccccccccccccccccccccccccccc;\n",
6493                Style);
6494 
6495   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6496   verifyFormat("return (a > b\n"
6497                "    // comment1\n"
6498                "    // comment2\n"
6499                "    || c);",
6500                Style);
6501 }
6502 
6503 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6504   FormatStyle Style = getLLVMStyle();
6505   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6506   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6507                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6508                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6509                Style);
6510 }
6511 
6512 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6513   FormatStyle Style = getLLVMStyleWithColumns(40);
6514   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6515   Style.BinPackArguments = false;
6516   verifyFormat("void test() {\n"
6517                "  someFunction(\n"
6518                "      this + argument + is + quite\n"
6519                "      + long + so + it + gets + wrapped\n"
6520                "      + but + remains + bin - packed);\n"
6521                "}",
6522                Style);
6523   verifyFormat("void test() {\n"
6524                "  someFunction(arg1,\n"
6525                "               this + argument + is\n"
6526                "                   + quite + long + so\n"
6527                "                   + it + gets + wrapped\n"
6528                "                   + but + remains + bin\n"
6529                "                   - packed,\n"
6530                "               arg3);\n"
6531                "}",
6532                Style);
6533   verifyFormat("void test() {\n"
6534                "  someFunction(\n"
6535                "      arg1,\n"
6536                "      this + argument + has\n"
6537                "          + anotherFunc(nested,\n"
6538                "                        calls + whose\n"
6539                "                            + arguments\n"
6540                "                            + are + also\n"
6541                "                            + wrapped,\n"
6542                "                        in + addition)\n"
6543                "          + to + being + bin - packed,\n"
6544                "      arg3);\n"
6545                "}",
6546                Style);
6547 
6548   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6549   verifyFormat("void test() {\n"
6550                "  someFunction(\n"
6551                "      arg1,\n"
6552                "      this + argument + has +\n"
6553                "          anotherFunc(nested,\n"
6554                "                      calls + whose +\n"
6555                "                          arguments +\n"
6556                "                          are + also +\n"
6557                "                          wrapped,\n"
6558                "                      in + addition) +\n"
6559                "          to + being + bin - packed,\n"
6560                "      arg3);\n"
6561                "}",
6562                Style);
6563 }
6564 
6565 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) {
6566   auto Style = getLLVMStyleWithColumns(45);
6567   EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None);
6568   verifyFormat("bool b =\n"
6569                "    is_default_constructible_v<hash<T>> and\n"
6570                "    is_copy_constructible_v<hash<T>> and\n"
6571                "    is_move_constructible_v<hash<T>> and\n"
6572                "    is_copy_assignable_v<hash<T>> and\n"
6573                "    is_move_assignable_v<hash<T>> and\n"
6574                "    is_destructible_v<hash<T>> and\n"
6575                "    is_swappable_v<hash<T>> and\n"
6576                "    is_callable_v<hash<T>(T)>;",
6577                Style);
6578 
6579   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6580   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6581                "         and is_copy_constructible_v<hash<T>>\n"
6582                "         and is_move_constructible_v<hash<T>>\n"
6583                "         and is_copy_assignable_v<hash<T>>\n"
6584                "         and is_move_assignable_v<hash<T>>\n"
6585                "         and is_destructible_v<hash<T>>\n"
6586                "         and is_swappable_v<hash<T>>\n"
6587                "         and is_callable_v<hash<T>(T)>;",
6588                Style);
6589 
6590   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6591   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6592                "         and is_copy_constructible_v<hash<T>>\n"
6593                "         and is_move_constructible_v<hash<T>>\n"
6594                "         and is_copy_assignable_v<hash<T>>\n"
6595                "         and is_move_assignable_v<hash<T>>\n"
6596                "         and is_destructible_v<hash<T>>\n"
6597                "         and is_swappable_v<hash<T>>\n"
6598                "         and is_callable_v<hash<T>(T)>;",
6599                Style);
6600 }
6601 
6602 TEST_F(FormatTest, ConstructorInitializers) {
6603   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6604   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6605                getLLVMStyleWithColumns(45));
6606   verifyFormat("Constructor()\n"
6607                "    : Inttializer(FitsOnTheLine) {}",
6608                getLLVMStyleWithColumns(44));
6609   verifyFormat("Constructor()\n"
6610                "    : Inttializer(FitsOnTheLine) {}",
6611                getLLVMStyleWithColumns(43));
6612 
6613   verifyFormat("template <typename T>\n"
6614                "Constructor() : Initializer(FitsOnTheLine) {}",
6615                getLLVMStyleWithColumns(45));
6616 
6617   verifyFormat(
6618       "SomeClass::Constructor()\n"
6619       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6620 
6621   verifyFormat(
6622       "SomeClass::Constructor()\n"
6623       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6624       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6625   verifyFormat(
6626       "SomeClass::Constructor()\n"
6627       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6628       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6629   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6630                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6631                "    : aaaaaaaaaa(aaaaaa) {}");
6632 
6633   verifyFormat("Constructor()\n"
6634                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6635                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6636                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6637                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6638 
6639   verifyFormat("Constructor()\n"
6640                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6641                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6642 
6643   verifyFormat("Constructor(int Parameter = 0)\n"
6644                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6645                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6646   verifyFormat("Constructor()\n"
6647                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6648                "}",
6649                getLLVMStyleWithColumns(60));
6650   verifyFormat("Constructor()\n"
6651                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6652                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6653 
6654   // Here a line could be saved by splitting the second initializer onto two
6655   // lines, but that is not desirable.
6656   verifyFormat("Constructor()\n"
6657                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6658                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6659                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6660 
6661   FormatStyle OnePerLine = getLLVMStyle();
6662   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6663   verifyFormat("MyClass::MyClass()\n"
6664                "    : a(a),\n"
6665                "      b(b),\n"
6666                "      c(c) {}",
6667                OnePerLine);
6668   verifyFormat("MyClass::MyClass()\n"
6669                "    : a(a), // comment\n"
6670                "      b(b),\n"
6671                "      c(c) {}",
6672                OnePerLine);
6673   verifyFormat("MyClass::MyClass(int a)\n"
6674                "    : b(a),      // comment\n"
6675                "      c(a + 1) { // lined up\n"
6676                "}",
6677                OnePerLine);
6678   verifyFormat("Constructor()\n"
6679                "    : a(b, b, b) {}",
6680                OnePerLine);
6681   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6682   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6683   verifyFormat("SomeClass::Constructor()\n"
6684                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6685                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6686                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6687                OnePerLine);
6688   verifyFormat("SomeClass::Constructor()\n"
6689                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6690                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6691                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6692                OnePerLine);
6693   verifyFormat("MyClass::MyClass(int var)\n"
6694                "    : some_var_(var),            // 4 space indent\n"
6695                "      some_other_var_(var + 1) { // lined up\n"
6696                "}",
6697                OnePerLine);
6698   verifyFormat("Constructor()\n"
6699                "    : aaaaa(aaaaaa),\n"
6700                "      aaaaa(aaaaaa),\n"
6701                "      aaaaa(aaaaaa),\n"
6702                "      aaaaa(aaaaaa),\n"
6703                "      aaaaa(aaaaaa) {}",
6704                OnePerLine);
6705   verifyFormat("Constructor()\n"
6706                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6707                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6708                OnePerLine);
6709   OnePerLine.BinPackParameters = false;
6710   verifyFormat(
6711       "Constructor()\n"
6712       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6713       "          aaaaaaaaaaa().aaa(),\n"
6714       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6715       OnePerLine);
6716   OnePerLine.ColumnLimit = 60;
6717   verifyFormat("Constructor()\n"
6718                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6719                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6720                OnePerLine);
6721 
6722   EXPECT_EQ("Constructor()\n"
6723             "    : // Comment forcing unwanted break.\n"
6724             "      aaaa(aaaa) {}",
6725             format("Constructor() :\n"
6726                    "    // Comment forcing unwanted break.\n"
6727                    "    aaaa(aaaa) {}"));
6728 }
6729 
6730 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6731   FormatStyle Style = getLLVMStyleWithColumns(60);
6732   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6733   Style.BinPackParameters = false;
6734 
6735   for (int i = 0; i < 4; ++i) {
6736     // Test all combinations of parameters that should not have an effect.
6737     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6738     Style.AllowAllArgumentsOnNextLine = i & 2;
6739 
6740     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6741     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6742     verifyFormat("Constructor()\n"
6743                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6744                  Style);
6745     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6746 
6747     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6748     verifyFormat("Constructor()\n"
6749                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6750                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6751                  Style);
6752     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6753 
6754     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6755     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6756     verifyFormat("Constructor()\n"
6757                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6758                  Style);
6759 
6760     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6761     verifyFormat("Constructor()\n"
6762                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6763                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6764                  Style);
6765 
6766     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6767     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6768     verifyFormat("Constructor() :\n"
6769                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6770                  Style);
6771 
6772     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6773     verifyFormat("Constructor() :\n"
6774                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6775                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6776                  Style);
6777   }
6778 
6779   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6780   // AllowAllConstructorInitializersOnNextLine in all
6781   // BreakConstructorInitializers modes
6782   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6783   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6784   verifyFormat("SomeClassWithALongName::Constructor(\n"
6785                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6786                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6787                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6788                Style);
6789 
6790   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6791   verifyFormat("SomeClassWithALongName::Constructor(\n"
6792                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6793                "    int bbbbbbbbbbbbb,\n"
6794                "    int cccccccccccccccc)\n"
6795                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6796                Style);
6797 
6798   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6799   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6800   verifyFormat("SomeClassWithALongName::Constructor(\n"
6801                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6802                "    int bbbbbbbbbbbbb)\n"
6803                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6804                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6805                Style);
6806 
6807   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6808 
6809   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6810   verifyFormat("SomeClassWithALongName::Constructor(\n"
6811                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6812                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6813                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6814                Style);
6815 
6816   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6817   verifyFormat("SomeClassWithALongName::Constructor(\n"
6818                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6819                "    int bbbbbbbbbbbbb,\n"
6820                "    int cccccccccccccccc)\n"
6821                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6822                Style);
6823 
6824   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6825   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6826   verifyFormat("SomeClassWithALongName::Constructor(\n"
6827                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6828                "    int bbbbbbbbbbbbb)\n"
6829                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6830                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6831                Style);
6832 
6833   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6834   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6835   verifyFormat("SomeClassWithALongName::Constructor(\n"
6836                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6837                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6838                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6839                Style);
6840 
6841   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6842   verifyFormat("SomeClassWithALongName::Constructor(\n"
6843                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6844                "    int bbbbbbbbbbbbb,\n"
6845                "    int cccccccccccccccc) :\n"
6846                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6847                Style);
6848 
6849   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6850   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6851   verifyFormat("SomeClassWithALongName::Constructor(\n"
6852                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6853                "    int bbbbbbbbbbbbb) :\n"
6854                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6855                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6856                Style);
6857 }
6858 
6859 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6860   FormatStyle Style = getLLVMStyleWithColumns(60);
6861   Style.BinPackArguments = false;
6862   for (int i = 0; i < 4; ++i) {
6863     // Test all combinations of parameters that should not have an effect.
6864     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6865     Style.PackConstructorInitializers =
6866         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6867 
6868     Style.AllowAllArgumentsOnNextLine = true;
6869     verifyFormat("void foo() {\n"
6870                  "  FunctionCallWithReallyLongName(\n"
6871                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6872                  "}",
6873                  Style);
6874     Style.AllowAllArgumentsOnNextLine = false;
6875     verifyFormat("void foo() {\n"
6876                  "  FunctionCallWithReallyLongName(\n"
6877                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6878                  "      bbbbbbbbbbbb);\n"
6879                  "}",
6880                  Style);
6881 
6882     Style.AllowAllArgumentsOnNextLine = true;
6883     verifyFormat("void foo() {\n"
6884                  "  auto VariableWithReallyLongName = {\n"
6885                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6886                  "}",
6887                  Style);
6888     Style.AllowAllArgumentsOnNextLine = false;
6889     verifyFormat("void foo() {\n"
6890                  "  auto VariableWithReallyLongName = {\n"
6891                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6892                  "      bbbbbbbbbbbb};\n"
6893                  "}",
6894                  Style);
6895   }
6896 
6897   // This parameter should not affect declarations.
6898   Style.BinPackParameters = false;
6899   Style.AllowAllArgumentsOnNextLine = false;
6900   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6901   verifyFormat("void FunctionCallWithReallyLongName(\n"
6902                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6903                Style);
6904   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6905   verifyFormat("void FunctionCallWithReallyLongName(\n"
6906                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6907                "    int bbbbbbbbbbbb);",
6908                Style);
6909 }
6910 
6911 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6912   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6913   // and BAS_Align.
6914   FormatStyle Style = getLLVMStyleWithColumns(35);
6915   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6916                     "void functionDecl(int A, int B, int C);";
6917   Style.AllowAllArgumentsOnNextLine = false;
6918   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6919   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6920                       "    paramC);\n"
6921                       "void functionDecl(int A, int B,\n"
6922                       "    int C);"),
6923             format(Input, Style));
6924   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6925   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6926                       "             paramC);\n"
6927                       "void functionDecl(int A, int B,\n"
6928                       "                  int C);"),
6929             format(Input, Style));
6930   // However, BAS_AlwaysBreak should take precedence over
6931   // AllowAllArgumentsOnNextLine.
6932   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6933   EXPECT_EQ(StringRef("functionCall(\n"
6934                       "    paramA, paramB, paramC);\n"
6935                       "void functionDecl(\n"
6936                       "    int A, int B, int C);"),
6937             format(Input, Style));
6938 
6939   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6940   // first argument.
6941   Style.AllowAllArgumentsOnNextLine = true;
6942   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6943   EXPECT_EQ(StringRef("functionCall(\n"
6944                       "    paramA, paramB, paramC);\n"
6945                       "void functionDecl(\n"
6946                       "    int A, int B, int C);"),
6947             format(Input, Style));
6948   // It wouldn't fit on one line with aligned parameters so this setting
6949   // doesn't change anything for BAS_Align.
6950   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6951   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6952                       "             paramC);\n"
6953                       "void functionDecl(int A, int B,\n"
6954                       "                  int C);"),
6955             format(Input, Style));
6956   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6957   EXPECT_EQ(StringRef("functionCall(\n"
6958                       "    paramA, paramB, paramC);\n"
6959                       "void functionDecl(\n"
6960                       "    int A, int B, int C);"),
6961             format(Input, Style));
6962 }
6963 
6964 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6965   FormatStyle Style = getLLVMStyle();
6966   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6967 
6968   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6969   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6970                getStyleWithColumns(Style, 45));
6971   verifyFormat("Constructor() :\n"
6972                "    Initializer(FitsOnTheLine) {}",
6973                getStyleWithColumns(Style, 44));
6974   verifyFormat("Constructor() :\n"
6975                "    Initializer(FitsOnTheLine) {}",
6976                getStyleWithColumns(Style, 43));
6977 
6978   verifyFormat("template <typename T>\n"
6979                "Constructor() : Initializer(FitsOnTheLine) {}",
6980                getStyleWithColumns(Style, 50));
6981   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6982   verifyFormat(
6983       "SomeClass::Constructor() :\n"
6984       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6985       Style);
6986 
6987   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6988   verifyFormat(
6989       "SomeClass::Constructor() :\n"
6990       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6991       Style);
6992 
6993   verifyFormat(
6994       "SomeClass::Constructor() :\n"
6995       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6996       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6997       Style);
6998   verifyFormat(
6999       "SomeClass::Constructor() :\n"
7000       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7001       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
7002       Style);
7003   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7004                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7005                "    aaaaaaaaaa(aaaaaa) {}",
7006                Style);
7007 
7008   verifyFormat("Constructor() :\n"
7009                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7010                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7011                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7012                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
7013                Style);
7014 
7015   verifyFormat("Constructor() :\n"
7016                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7017                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7018                Style);
7019 
7020   verifyFormat("Constructor(int Parameter = 0) :\n"
7021                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
7022                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
7023                Style);
7024   verifyFormat("Constructor() :\n"
7025                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
7026                "}",
7027                getStyleWithColumns(Style, 60));
7028   verifyFormat("Constructor() :\n"
7029                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7030                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
7031                Style);
7032 
7033   // Here a line could be saved by splitting the second initializer onto two
7034   // lines, but that is not desirable.
7035   verifyFormat("Constructor() :\n"
7036                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
7037                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
7038                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7039                Style);
7040 
7041   FormatStyle OnePerLine = Style;
7042   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
7043   verifyFormat("SomeClass::Constructor() :\n"
7044                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7045                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7046                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7047                OnePerLine);
7048   verifyFormat("SomeClass::Constructor() :\n"
7049                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
7050                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7051                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7052                OnePerLine);
7053   verifyFormat("MyClass::MyClass(int var) :\n"
7054                "    some_var_(var),            // 4 space indent\n"
7055                "    some_other_var_(var + 1) { // lined up\n"
7056                "}",
7057                OnePerLine);
7058   verifyFormat("Constructor() :\n"
7059                "    aaaaa(aaaaaa),\n"
7060                "    aaaaa(aaaaaa),\n"
7061                "    aaaaa(aaaaaa),\n"
7062                "    aaaaa(aaaaaa),\n"
7063                "    aaaaa(aaaaaa) {}",
7064                OnePerLine);
7065   verifyFormat("Constructor() :\n"
7066                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
7067                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
7068                OnePerLine);
7069   OnePerLine.BinPackParameters = false;
7070   verifyFormat("Constructor() :\n"
7071                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7072                "        aaaaaaaaaaa().aaa(),\n"
7073                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7074                OnePerLine);
7075   OnePerLine.ColumnLimit = 60;
7076   verifyFormat("Constructor() :\n"
7077                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
7078                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
7079                OnePerLine);
7080 
7081   EXPECT_EQ("Constructor() :\n"
7082             "    // Comment forcing unwanted break.\n"
7083             "    aaaa(aaaa) {}",
7084             format("Constructor() :\n"
7085                    "    // Comment forcing unwanted break.\n"
7086                    "    aaaa(aaaa) {}",
7087                    Style));
7088 
7089   Style.ColumnLimit = 0;
7090   verifyFormat("SomeClass::Constructor() :\n"
7091                "    a(a) {}",
7092                Style);
7093   verifyFormat("SomeClass::Constructor() noexcept :\n"
7094                "    a(a) {}",
7095                Style);
7096   verifyFormat("SomeClass::Constructor() :\n"
7097                "    a(a), b(b), c(c) {}",
7098                Style);
7099   verifyFormat("SomeClass::Constructor() :\n"
7100                "    a(a) {\n"
7101                "  foo();\n"
7102                "  bar();\n"
7103                "}",
7104                Style);
7105 
7106   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
7107   verifyFormat("SomeClass::Constructor() :\n"
7108                "    a(a), b(b), c(c) {\n"
7109                "}",
7110                Style);
7111   verifyFormat("SomeClass::Constructor() :\n"
7112                "    a(a) {\n"
7113                "}",
7114                Style);
7115 
7116   Style.ColumnLimit = 80;
7117   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
7118   Style.ConstructorInitializerIndentWidth = 2;
7119   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
7120   verifyFormat("SomeClass::Constructor() :\n"
7121                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7122                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
7123                Style);
7124 
7125   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
7126   // well
7127   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
7128   verifyFormat(
7129       "class SomeClass\n"
7130       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7131       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7132       Style);
7133   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
7134   verifyFormat(
7135       "class SomeClass\n"
7136       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7137       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7138       Style);
7139   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
7140   verifyFormat(
7141       "class SomeClass :\n"
7142       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7143       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7144       Style);
7145   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
7146   verifyFormat(
7147       "class SomeClass\n"
7148       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7149       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7150       Style);
7151 }
7152 
7153 #ifndef EXPENSIVE_CHECKS
7154 // Expensive checks enables libstdc++ checking which includes validating the
7155 // state of ranges used in std::priority_queue - this blows out the
7156 // runtime/scalability of the function and makes this test unacceptably slow.
7157 TEST_F(FormatTest, MemoizationTests) {
7158   // This breaks if the memoization lookup does not take \c Indent and
7159   // \c LastSpace into account.
7160   verifyFormat(
7161       "extern CFRunLoopTimerRef\n"
7162       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
7163       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
7164       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
7165       "                     CFRunLoopTimerContext *context) {}");
7166 
7167   // Deep nesting somewhat works around our memoization.
7168   verifyFormat(
7169       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7170       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7171       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7172       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7173       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
7174       getLLVMStyleWithColumns(65));
7175   verifyFormat(
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(\n"
7193       "                                    aaaaa,\n"
7194       "                                    aaaaa(\n"
7195       "                                        aaaaa,\n"
7196       "                                        aaaaa(\n"
7197       "                                            aaaaa,\n"
7198       "                                            aaaaa(\n"
7199       "                                                aaaaa,\n"
7200       "                                                aaaaa))))))))))));",
7201       getLLVMStyleWithColumns(65));
7202   verifyFormat(
7203       "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"
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),\n"
7213       "                a),\n"
7214       "              a),\n"
7215       "            a),\n"
7216       "          a),\n"
7217       "        a),\n"
7218       "      a),\n"
7219       "    a),\n"
7220       "  a)",
7221       getLLVMStyleWithColumns(65));
7222 
7223   // This test takes VERY long when memoization is broken.
7224   FormatStyle OnePerLine = getLLVMStyle();
7225   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7226   OnePerLine.BinPackParameters = false;
7227   std::string input = "Constructor()\n"
7228                       "    : aaaa(a,\n";
7229   for (unsigned i = 0, e = 80; i != e; ++i)
7230     input += "           a,\n";
7231   input += "           a) {}";
7232   verifyFormat(input, OnePerLine);
7233 }
7234 #endif
7235 
7236 TEST_F(FormatTest, BreaksAsHighAsPossible) {
7237   verifyFormat(
7238       "void f() {\n"
7239       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
7240       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
7241       "    f();\n"
7242       "}");
7243   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
7244                "    Intervals[i - 1].getRange().getLast()) {\n}");
7245 }
7246 
7247 TEST_F(FormatTest, BreaksFunctionDeclarations) {
7248   // Principially, we break function declarations in a certain order:
7249   // 1) break amongst arguments.
7250   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
7251                "                              Cccccccccccccc cccccccccccccc);");
7252   verifyFormat("template <class TemplateIt>\n"
7253                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
7254                "                            TemplateIt *stop) {}");
7255 
7256   // 2) break after return type.
7257   verifyFormat(
7258       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7259       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
7260       getGoogleStyle());
7261 
7262   // 3) break after (.
7263   verifyFormat(
7264       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
7265       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
7266       getGoogleStyle());
7267 
7268   // 4) break before after nested name specifiers.
7269   verifyFormat(
7270       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7271       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
7272       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
7273       getGoogleStyle());
7274 
7275   // However, there are exceptions, if a sufficient amount of lines can be
7276   // saved.
7277   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
7278   // more adjusting.
7279   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7280                "                                  Cccccccccccccc cccccccccc,\n"
7281                "                                  Cccccccccccccc cccccccccc,\n"
7282                "                                  Cccccccccccccc cccccccccc,\n"
7283                "                                  Cccccccccccccc cccccccccc);");
7284   verifyFormat(
7285       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7286       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7287       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7288       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
7289       getGoogleStyle());
7290   verifyFormat(
7291       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7292       "                                          Cccccccccccccc cccccccccc,\n"
7293       "                                          Cccccccccccccc cccccccccc,\n"
7294       "                                          Cccccccccccccc cccccccccc,\n"
7295       "                                          Cccccccccccccc cccccccccc,\n"
7296       "                                          Cccccccccccccc cccccccccc,\n"
7297       "                                          Cccccccccccccc cccccccccc);");
7298   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7299                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7300                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7301                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7302                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
7303 
7304   // Break after multi-line parameters.
7305   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7306                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7307                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7308                "    bbbb bbbb);");
7309   verifyFormat("void SomeLoooooooooooongFunction(\n"
7310                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
7311                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7312                "    int bbbbbbbbbbbbb);");
7313 
7314   // Treat overloaded operators like other functions.
7315   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7316                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
7317   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7318                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
7319   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7320                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
7321   verifyGoogleFormat(
7322       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
7323       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7324   verifyGoogleFormat(
7325       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
7326       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7327   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7328                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7329   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
7330                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7331   verifyGoogleFormat(
7332       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
7333       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7334       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
7335   verifyGoogleFormat("template <typename T>\n"
7336                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7337                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
7338                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
7339 
7340   FormatStyle Style = getLLVMStyle();
7341   Style.PointerAlignment = FormatStyle::PAS_Left;
7342   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7343                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
7344                Style);
7345   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
7346                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7347                Style);
7348 }
7349 
7350 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
7351   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
7352   // Prefer keeping `::` followed by `operator` together.
7353   EXPECT_EQ("const aaaa::bbbbbbb &\n"
7354             "ccccccccc::operator++() {\n"
7355             "  stuff();\n"
7356             "}",
7357             format("const aaaa::bbbbbbb\n"
7358                    "&ccccccccc::operator++() { stuff(); }",
7359                    getLLVMStyleWithColumns(40)));
7360 }
7361 
7362 TEST_F(FormatTest, TrailingReturnType) {
7363   verifyFormat("auto foo() -> int;\n");
7364   // correct trailing return type spacing
7365   verifyFormat("auto operator->() -> int;\n");
7366   verifyFormat("auto operator++(int) -> int;\n");
7367 
7368   verifyFormat("struct S {\n"
7369                "  auto bar() const -> int;\n"
7370                "};");
7371   verifyFormat("template <size_t Order, typename T>\n"
7372                "auto load_img(const std::string &filename)\n"
7373                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
7374   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
7375                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
7376   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
7377   verifyFormat("template <typename T>\n"
7378                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
7379                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
7380 
7381   // Not trailing return types.
7382   verifyFormat("void f() { auto a = b->c(); }");
7383   verifyFormat("auto a = p->foo();");
7384   verifyFormat("int a = p->foo();");
7385   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
7386 }
7387 
7388 TEST_F(FormatTest, DeductionGuides) {
7389   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
7390   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
7391   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
7392   verifyFormat(
7393       "template <class... T>\n"
7394       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
7395   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
7396   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
7397   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
7398   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
7399   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
7400   verifyFormat("template <class T> x() -> x<1>;");
7401   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
7402 
7403   // Ensure not deduction guides.
7404   verifyFormat("c()->f<int>();");
7405   verifyFormat("x()->foo<1>;");
7406   verifyFormat("x = p->foo<3>();");
7407   verifyFormat("x()->x<1>();");
7408   verifyFormat("x()->x<1>;");
7409 }
7410 
7411 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
7412   // Avoid breaking before trailing 'const' or other trailing annotations, if
7413   // they are not function-like.
7414   FormatStyle Style = getGoogleStyleWithColumns(47);
7415   verifyFormat("void someLongFunction(\n"
7416                "    int someLoooooooooooooongParameter) const {\n}",
7417                getLLVMStyleWithColumns(47));
7418   verifyFormat("LoooooongReturnType\n"
7419                "someLoooooooongFunction() const {}",
7420                getLLVMStyleWithColumns(47));
7421   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
7422                "    const {}",
7423                Style);
7424   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7425                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
7426   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7427                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
7428   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7429                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
7430   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
7431                "                   aaaaaaaaaaa aaaaa) const override;");
7432   verifyGoogleFormat(
7433       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7434       "    const override;");
7435 
7436   // Even if the first parameter has to be wrapped.
7437   verifyFormat("void someLongFunction(\n"
7438                "    int someLongParameter) const {}",
7439                getLLVMStyleWithColumns(46));
7440   verifyFormat("void someLongFunction(\n"
7441                "    int someLongParameter) const {}",
7442                Style);
7443   verifyFormat("void someLongFunction(\n"
7444                "    int someLongParameter) override {}",
7445                Style);
7446   verifyFormat("void someLongFunction(\n"
7447                "    int someLongParameter) OVERRIDE {}",
7448                Style);
7449   verifyFormat("void someLongFunction(\n"
7450                "    int someLongParameter) final {}",
7451                Style);
7452   verifyFormat("void someLongFunction(\n"
7453                "    int someLongParameter) FINAL {}",
7454                Style);
7455   verifyFormat("void someLongFunction(\n"
7456                "    int parameter) const override {}",
7457                Style);
7458 
7459   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7460   verifyFormat("void someLongFunction(\n"
7461                "    int someLongParameter) const\n"
7462                "{\n"
7463                "}",
7464                Style);
7465 
7466   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7467   verifyFormat("void someLongFunction(\n"
7468                "    int someLongParameter) const\n"
7469                "  {\n"
7470                "  }",
7471                Style);
7472 
7473   // Unless these are unknown annotations.
7474   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7475                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7476                "    LONG_AND_UGLY_ANNOTATION;");
7477 
7478   // Breaking before function-like trailing annotations is fine to keep them
7479   // close to their arguments.
7480   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7481                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7482   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7483                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7484   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7485                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7486   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7487                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7488   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7489 
7490   verifyFormat(
7491       "void aaaaaaaaaaaaaaaaaa()\n"
7492       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7493       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7494   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7495                "    __attribute__((unused));");
7496   verifyGoogleFormat(
7497       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7498       "    GUARDED_BY(aaaaaaaaaaaa);");
7499   verifyGoogleFormat(
7500       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7501       "    GUARDED_BY(aaaaaaaaaaaa);");
7502   verifyGoogleFormat(
7503       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7504       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7505   verifyGoogleFormat(
7506       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7507       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7508 }
7509 
7510 TEST_F(FormatTest, FunctionAnnotations) {
7511   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7512                "int OldFunction(const string &parameter) {}");
7513   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7514                "string OldFunction(const string &parameter) {}");
7515   verifyFormat("template <typename T>\n"
7516                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7517                "string OldFunction(const string &parameter) {}");
7518 
7519   // Not function annotations.
7520   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7521                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7522   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7523                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7524   verifyFormat("MACRO(abc).function() // wrap\n"
7525                "    << abc;");
7526   verifyFormat("MACRO(abc)->function() // wrap\n"
7527                "    << abc;");
7528   verifyFormat("MACRO(abc)::function() // wrap\n"
7529                "    << abc;");
7530 }
7531 
7532 TEST_F(FormatTest, BreaksDesireably) {
7533   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7534                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7535                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7536   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7537                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7538                "}");
7539 
7540   verifyFormat(
7541       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7542       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7543 
7544   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7545                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7546                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7547 
7548   verifyFormat(
7549       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7550       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7551       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7552       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7553       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7554 
7555   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7556                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7557 
7558   verifyFormat(
7559       "void f() {\n"
7560       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7561       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7562       "}");
7563   verifyFormat(
7564       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7565       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7566   verifyFormat(
7567       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7568       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7569   verifyFormat(
7570       "aaaaaa(aaa,\n"
7571       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7572       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7573       "       aaaa);");
7574   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7575                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7576                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7577 
7578   // Indent consistently independent of call expression and unary operator.
7579   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7580                "    dddddddddddddddddddddddddddddd));");
7581   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7582                "    dddddddddddddddddddddddddddddd));");
7583   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7584                "    dddddddddddddddddddddddddddddd));");
7585 
7586   // This test case breaks on an incorrect memoization, i.e. an optimization not
7587   // taking into account the StopAt value.
7588   verifyFormat(
7589       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7590       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7591       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7592       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7593 
7594   verifyFormat("{\n  {\n    {\n"
7595                "      Annotation.SpaceRequiredBefore =\n"
7596                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7597                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7598                "    }\n  }\n}");
7599 
7600   // Break on an outer level if there was a break on an inner level.
7601   EXPECT_EQ("f(g(h(a, // comment\n"
7602             "      b, c),\n"
7603             "    d, e),\n"
7604             "  x, y);",
7605             format("f(g(h(a, // comment\n"
7606                    "    b, c), d, e), x, y);"));
7607 
7608   // Prefer breaking similar line breaks.
7609   verifyFormat(
7610       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7611       "                             NSTrackingMouseEnteredAndExited |\n"
7612       "                             NSTrackingActiveAlways;");
7613 }
7614 
7615 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7616   FormatStyle NoBinPacking = getGoogleStyle();
7617   NoBinPacking.BinPackParameters = false;
7618   NoBinPacking.BinPackArguments = true;
7619   verifyFormat("void f() {\n"
7620                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7621                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7622                "}",
7623                NoBinPacking);
7624   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7625                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7626                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7627                NoBinPacking);
7628 
7629   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7630   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7631                "                        vector<int> bbbbbbbbbbbbbbb);",
7632                NoBinPacking);
7633   // FIXME: This behavior difference is probably not wanted. However, currently
7634   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7635   // template arguments from BreakBeforeParameter being set because of the
7636   // one-per-line formatting.
7637   verifyFormat(
7638       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7639       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7640       NoBinPacking);
7641   verifyFormat(
7642       "void fffffffffff(\n"
7643       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7644       "        aaaaaaaaaa);");
7645 }
7646 
7647 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7648   FormatStyle NoBinPacking = getGoogleStyle();
7649   NoBinPacking.BinPackParameters = false;
7650   NoBinPacking.BinPackArguments = false;
7651   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7652                "  aaaaaaaaaaaaaaaaaaaa,\n"
7653                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7654                NoBinPacking);
7655   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7656                "        aaaaaaaaaaaaa,\n"
7657                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7658                NoBinPacking);
7659   verifyFormat(
7660       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7661       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7662       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7663       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7664       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7665       NoBinPacking);
7666   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7667                "    .aaaaaaaaaaaaaaaaaa();",
7668                NoBinPacking);
7669   verifyFormat("void f() {\n"
7670                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7671                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7672                "}",
7673                NoBinPacking);
7674 
7675   verifyFormat(
7676       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7677       "             aaaaaaaaaaaa,\n"
7678       "             aaaaaaaaaaaa);",
7679       NoBinPacking);
7680   verifyFormat(
7681       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7682       "                               ddddddddddddddddddddddddddddd),\n"
7683       "             test);",
7684       NoBinPacking);
7685 
7686   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7687                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7688                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7689                "    aaaaaaaaaaaaaaaaaa;",
7690                NoBinPacking);
7691   verifyFormat("a(\"a\"\n"
7692                "  \"a\",\n"
7693                "  a);");
7694 
7695   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7696   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7697                "                aaaaaaaaa,\n"
7698                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7699                NoBinPacking);
7700   verifyFormat(
7701       "void f() {\n"
7702       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7703       "      .aaaaaaa();\n"
7704       "}",
7705       NoBinPacking);
7706   verifyFormat(
7707       "template <class SomeType, class SomeOtherType>\n"
7708       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7709       NoBinPacking);
7710 }
7711 
7712 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7713   FormatStyle Style = getLLVMStyleWithColumns(15);
7714   Style.ExperimentalAutoDetectBinPacking = true;
7715   EXPECT_EQ("aaa(aaaa,\n"
7716             "    aaaa,\n"
7717             "    aaaa);\n"
7718             "aaa(aaaa,\n"
7719             "    aaaa,\n"
7720             "    aaaa);",
7721             format("aaa(aaaa,\n" // one-per-line
7722                    "  aaaa,\n"
7723                    "    aaaa  );\n"
7724                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7725                    Style));
7726   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7727             "    aaaa);\n"
7728             "aaa(aaaa, aaaa,\n"
7729             "    aaaa);",
7730             format("aaa(aaaa,  aaaa,\n" // bin-packed
7731                    "    aaaa  );\n"
7732                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7733                    Style));
7734 }
7735 
7736 TEST_F(FormatTest, FormatsBuilderPattern) {
7737   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7738                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7739                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7740                "    .StartsWith(\".init\", ORDER_INIT)\n"
7741                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7742                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7743                "    .Default(ORDER_TEXT);\n");
7744 
7745   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7746                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7747   verifyFormat("aaaaaaa->aaaaaaa\n"
7748                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7749                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7750                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7751   verifyFormat(
7752       "aaaaaaa->aaaaaaa\n"
7753       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7754       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7755   verifyFormat(
7756       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7757       "    aaaaaaaaaaaaaa);");
7758   verifyFormat(
7759       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7760       "    aaaaaa->aaaaaaaaaaaa()\n"
7761       "        ->aaaaaaaaaaaaaaaa(\n"
7762       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7763       "        ->aaaaaaaaaaaaaaaaa();");
7764   verifyGoogleFormat(
7765       "void f() {\n"
7766       "  someo->Add((new util::filetools::Handler(dir))\n"
7767       "                 ->OnEvent1(NewPermanentCallback(\n"
7768       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7769       "                 ->OnEvent2(NewPermanentCallback(\n"
7770       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7771       "                 ->OnEvent3(NewPermanentCallback(\n"
7772       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7773       "                 ->OnEvent5(NewPermanentCallback(\n"
7774       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7775       "                 ->OnEvent6(NewPermanentCallback(\n"
7776       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7777       "}");
7778 
7779   verifyFormat(
7780       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7781   verifyFormat("aaaaaaaaaaaaaaa()\n"
7782                "    .aaaaaaaaaaaaaaa()\n"
7783                "    .aaaaaaaaaaaaaaa()\n"
7784                "    .aaaaaaaaaaaaaaa()\n"
7785                "    .aaaaaaaaaaaaaaa();");
7786   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7787                "    .aaaaaaaaaaaaaaa()\n"
7788                "    .aaaaaaaaaaaaaaa()\n"
7789                "    .aaaaaaaaaaaaaaa();");
7790   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7791                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7792                "    .aaaaaaaaaaaaaaa();");
7793   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7794                "    ->aaaaaaaaaaaaaae(0)\n"
7795                "    ->aaaaaaaaaaaaaaa();");
7796 
7797   // Don't linewrap after very short segments.
7798   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7799                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7800                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7801   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7802                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7803                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7804   verifyFormat("aaa()\n"
7805                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7806                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7807                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7808 
7809   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7810                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7811                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7812   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7813                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7814                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7815 
7816   // Prefer not to break after empty parentheses.
7817   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7818                "    First->LastNewlineOffset);");
7819 
7820   // Prefer not to create "hanging" indents.
7821   verifyFormat(
7822       "return !soooooooooooooome_map\n"
7823       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7824       "            .second;");
7825   verifyFormat(
7826       "return aaaaaaaaaaaaaaaa\n"
7827       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7828       "    .aaaa(aaaaaaaaaaaaaa);");
7829   // No hanging indent here.
7830   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7831                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7832   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7833                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7834   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7835                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7836                getLLVMStyleWithColumns(60));
7837   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7838                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7839                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7840                getLLVMStyleWithColumns(59));
7841   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7842                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7843                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7844 
7845   // Dont break if only closing statements before member call
7846   verifyFormat("test() {\n"
7847                "  ([]() -> {\n"
7848                "    int b = 32;\n"
7849                "    return 3;\n"
7850                "  }).foo();\n"
7851                "}");
7852   verifyFormat("test() {\n"
7853                "  (\n"
7854                "      []() -> {\n"
7855                "        int b = 32;\n"
7856                "        return 3;\n"
7857                "      },\n"
7858                "      foo, bar)\n"
7859                "      .foo();\n"
7860                "}");
7861   verifyFormat("test() {\n"
7862                "  ([]() -> {\n"
7863                "    int b = 32;\n"
7864                "    return 3;\n"
7865                "  })\n"
7866                "      .foo()\n"
7867                "      .bar();\n"
7868                "}");
7869   verifyFormat("test() {\n"
7870                "  ([]() -> {\n"
7871                "    int b = 32;\n"
7872                "    return 3;\n"
7873                "  })\n"
7874                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7875                "           \"bbbb\");\n"
7876                "}",
7877                getLLVMStyleWithColumns(30));
7878 }
7879 
7880 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7881   verifyFormat(
7882       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7883       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7884   verifyFormat(
7885       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7886       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7887 
7888   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7889                "    ccccccccccccccccccccccccc) {\n}");
7890   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7891                "    ccccccccccccccccccccccccc) {\n}");
7892 
7893   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7894                "    ccccccccccccccccccccccccc) {\n}");
7895   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7896                "    ccccccccccccccccccccccccc) {\n}");
7897 
7898   verifyFormat(
7899       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7900       "    ccccccccccccccccccccccccc) {\n}");
7901   verifyFormat(
7902       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7903       "    ccccccccccccccccccccccccc) {\n}");
7904 
7905   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7906                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7907                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7908                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7909   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7910                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7911                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7912                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7913 
7914   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7915                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7916                "    aaaaaaaaaaaaaaa != aa) {\n}");
7917   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7918                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7919                "    aaaaaaaaaaaaaaa != aa) {\n}");
7920 }
7921 
7922 TEST_F(FormatTest, BreaksAfterAssignments) {
7923   verifyFormat(
7924       "unsigned Cost =\n"
7925       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7926       "                        SI->getPointerAddressSpaceee());\n");
7927   verifyFormat(
7928       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7929       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7930 
7931   verifyFormat(
7932       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7933       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7934   verifyFormat("unsigned OriginalStartColumn =\n"
7935                "    SourceMgr.getSpellingColumnNumber(\n"
7936                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7937                "    1;");
7938 }
7939 
7940 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7941   FormatStyle Style = getLLVMStyle();
7942   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7943                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7944                Style);
7945 
7946   Style.PenaltyBreakAssignment = 20;
7947   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7948                "                                 cccccccccccccccccccccccccc;",
7949                Style);
7950 }
7951 
7952 TEST_F(FormatTest, AlignsAfterAssignments) {
7953   verifyFormat(
7954       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7955       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7956   verifyFormat(
7957       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7958       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7959   verifyFormat(
7960       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7961       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7962   verifyFormat(
7963       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7964       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7965   verifyFormat(
7966       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7967       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7968       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7969 }
7970 
7971 TEST_F(FormatTest, AlignsAfterReturn) {
7972   verifyFormat(
7973       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7974       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7975   verifyFormat(
7976       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7977       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7978   verifyFormat(
7979       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7980       "       aaaaaaaaaaaaaaaaaaaaaa();");
7981   verifyFormat(
7982       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7983       "        aaaaaaaaaaaaaaaaaaaaaa());");
7984   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7985                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7986   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7987                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7988                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7989   verifyFormat("return\n"
7990                "    // true if code is one of a or b.\n"
7991                "    code == a || code == b;");
7992 }
7993 
7994 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7995   verifyFormat(
7996       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7997       "                                                aaaaaaaaa aaaaaaa) {}");
7998   verifyFormat(
7999       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
8000       "                                               aaaaaaaaaaa aaaaaaaaa);");
8001   verifyFormat(
8002       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
8003       "                                             aaaaaaaaaaaaaaaaaaaaa));");
8004   FormatStyle Style = getLLVMStyle();
8005   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8006   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8007                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
8008                Style);
8009   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8010                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
8011                Style);
8012   verifyFormat("SomeLongVariableName->someFunction(\n"
8013                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
8014                Style);
8015   verifyFormat(
8016       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
8017       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8018       Style);
8019   verifyFormat(
8020       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
8021       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8022       Style);
8023   verifyFormat(
8024       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
8025       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8026       Style);
8027 
8028   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
8029                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
8030                "        b));",
8031                Style);
8032 
8033   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8034   Style.BinPackArguments = false;
8035   Style.BinPackParameters = false;
8036   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8037                "    aaaaaaaaaaa aaaaaaaa,\n"
8038                "    aaaaaaaaa aaaaaaa,\n"
8039                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8040                Style);
8041   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8042                "    aaaaaaaaaaa aaaaaaaaa,\n"
8043                "    aaaaaaaaaaa aaaaaaaaa,\n"
8044                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8045                Style);
8046   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
8047                "    aaaaaaaaaaaaaaa,\n"
8048                "    aaaaaaaaaaaaaaaaaaaaa,\n"
8049                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8050                Style);
8051   verifyFormat(
8052       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
8053       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8054       Style);
8055   verifyFormat(
8056       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
8057       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8058       Style);
8059   verifyFormat(
8060       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8061       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8062       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
8063       "    aaaaaaaaaaaaaaaa);",
8064       Style);
8065   verifyFormat(
8066       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8067       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8068       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
8069       "    aaaaaaaaaaaaaaaa);",
8070       Style);
8071 }
8072 
8073 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
8074   FormatStyle Style = getLLVMStyleWithColumns(40);
8075   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8076                "          bbbbbbbbbbbbbbbbbbbbbb);",
8077                Style);
8078   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
8079   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8080   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8081                "          bbbbbbbbbbbbbbbbbbbbbb);",
8082                Style);
8083   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8084   Style.AlignOperands = FormatStyle::OAS_Align;
8085   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8086                "          bbbbbbbbbbbbbbbbbbbbbb);",
8087                Style);
8088   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8089   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8090   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8091                "    bbbbbbbbbbbbbbbbbbbbbb);",
8092                Style);
8093 }
8094 
8095 TEST_F(FormatTest, BreaksConditionalExpressions) {
8096   verifyFormat(
8097       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8098       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8099       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8100   verifyFormat(
8101       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8102       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8103       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8104   verifyFormat(
8105       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8106       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8107   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
8108                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8109                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8110   verifyFormat(
8111       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
8112       "                                                    : aaaaaaaaaaaaa);");
8113   verifyFormat(
8114       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8115       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8116       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8117       "                   aaaaaaaaaaaaa);");
8118   verifyFormat(
8119       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8120       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8121       "                   aaaaaaaaaaaaa);");
8122   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8123                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8124                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8125                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8126                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8127   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8128                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8129                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8130                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8131                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8132                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8133                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8134   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8135                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8136                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8137                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8138                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8139   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8140                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8141                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8142   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8143                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8144                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8145                "        : aaaaaaaaaaaaaaaa;");
8146   verifyFormat(
8147       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8148       "    ? aaaaaaaaaaaaaaa\n"
8149       "    : aaaaaaaaaaaaaaa;");
8150   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8151                "          aaaaaaaaa\n"
8152                "      ? b\n"
8153                "      : c);");
8154   verifyFormat("return aaaa == bbbb\n"
8155                "           // comment\n"
8156                "           ? aaaa\n"
8157                "           : bbbb;");
8158   verifyFormat("unsigned Indent =\n"
8159                "    format(TheLine.First,\n"
8160                "           IndentForLevel[TheLine.Level] >= 0\n"
8161                "               ? IndentForLevel[TheLine.Level]\n"
8162                "               : TheLine * 2,\n"
8163                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8164                getLLVMStyleWithColumns(60));
8165   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8166                "                  ? aaaaaaaaaaaaaaa\n"
8167                "                  : bbbbbbbbbbbbbbb //\n"
8168                "                        ? ccccccccccccccc\n"
8169                "                        : ddddddddddddddd;");
8170   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8171                "                  ? aaaaaaaaaaaaaaa\n"
8172                "                  : (bbbbbbbbbbbbbbb //\n"
8173                "                         ? ccccccccccccccc\n"
8174                "                         : ddddddddddddddd);");
8175   verifyFormat(
8176       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8177       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8178       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
8179       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
8180       "                                      : aaaaaaaaaa;");
8181   verifyFormat(
8182       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8183       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
8184       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8185 
8186   FormatStyle NoBinPacking = getLLVMStyle();
8187   NoBinPacking.BinPackArguments = false;
8188   verifyFormat(
8189       "void f() {\n"
8190       "  g(aaa,\n"
8191       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8192       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8193       "        ? aaaaaaaaaaaaaaa\n"
8194       "        : aaaaaaaaaaaaaaa);\n"
8195       "}",
8196       NoBinPacking);
8197   verifyFormat(
8198       "void f() {\n"
8199       "  g(aaa,\n"
8200       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8201       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8202       "        ?: aaaaaaaaaaaaaaa);\n"
8203       "}",
8204       NoBinPacking);
8205 
8206   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
8207                "             // comment.\n"
8208                "             ccccccccccccccccccccccccccccccccccccccc\n"
8209                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8210                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
8211 
8212   // Assignments in conditional expressions. Apparently not uncommon :-(.
8213   verifyFormat("return a != b\n"
8214                "           // comment\n"
8215                "           ? a = b\n"
8216                "           : a = b;");
8217   verifyFormat("return a != b\n"
8218                "           // comment\n"
8219                "           ? a = a != b\n"
8220                "                     // comment\n"
8221                "                     ? a = b\n"
8222                "                     : a\n"
8223                "           : a;\n");
8224   verifyFormat("return a != b\n"
8225                "           // comment\n"
8226                "           ? a\n"
8227                "           : a = a != b\n"
8228                "                     // comment\n"
8229                "                     ? a = b\n"
8230                "                     : a;");
8231 
8232   // Chained conditionals
8233   FormatStyle Style = getLLVMStyleWithColumns(70);
8234   Style.AlignOperands = FormatStyle::OAS_Align;
8235   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8236                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8237                "                        : 3333333333333333;",
8238                Style);
8239   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8240                "       : bbbbbbbbbb     ? 2222222222222222\n"
8241                "                        : 3333333333333333;",
8242                Style);
8243   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
8244                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
8245                "                          : 3333333333333333;",
8246                Style);
8247   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8248                "       : bbbbbbbbbbbbbb ? 222222\n"
8249                "                        : 333333;",
8250                Style);
8251   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8252                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8253                "       : cccccccccccccc ? 3333333333333333\n"
8254                "                        : 4444444444444444;",
8255                Style);
8256   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
8257                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8258                "                        : 3333333333333333;",
8259                Style);
8260   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8261                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8262                "                        : (aaa ? bbb : ccc);",
8263                Style);
8264   verifyFormat(
8265       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8266       "                                             : cccccccccccccccccc)\n"
8267       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8268       "                        : 3333333333333333;",
8269       Style);
8270   verifyFormat(
8271       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8272       "                                             : cccccccccccccccccc)\n"
8273       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8274       "                        : 3333333333333333;",
8275       Style);
8276   verifyFormat(
8277       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8278       "                                             : dddddddddddddddddd)\n"
8279       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8280       "                        : 3333333333333333;",
8281       Style);
8282   verifyFormat(
8283       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8284       "                                             : dddddddddddddddddd)\n"
8285       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8286       "                        : 3333333333333333;",
8287       Style);
8288   verifyFormat(
8289       "return aaaaaaaaa        ? 1111111111111111\n"
8290       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8291       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8292       "                                             : dddddddddddddddddd)\n",
8293       Style);
8294   verifyFormat(
8295       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8296       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8297       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8298       "                                             : cccccccccccccccccc);",
8299       Style);
8300   verifyFormat(
8301       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8302       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8303       "                                             : eeeeeeeeeeeeeeeeee)\n"
8304       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8305       "                        : 3333333333333333;",
8306       Style);
8307   verifyFormat(
8308       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
8309       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8310       "                                             : eeeeeeeeeeeeeeeeee)\n"
8311       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8312       "                        : 3333333333333333;",
8313       Style);
8314   verifyFormat(
8315       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8316       "                           : cccccccccccc    ? dddddddddddddddddd\n"
8317       "                                             : eeeeeeeeeeeeeeeeee)\n"
8318       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8319       "                        : 3333333333333333;",
8320       Style);
8321   verifyFormat(
8322       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8323       "                                             : cccccccccccccccccc\n"
8324       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8325       "                        : 3333333333333333;",
8326       Style);
8327   verifyFormat(
8328       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8329       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
8330       "                                             : eeeeeeeeeeeeeeeeee\n"
8331       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8332       "                        : 3333333333333333;",
8333       Style);
8334   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
8335                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
8336                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
8337                "                                   : eeeeeeeeeeeeeeeeee)\n"
8338                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8339                "                             : 3333333333333333;",
8340                Style);
8341   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
8342                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8343                "             : cccccccccccccccc ? dddddddddddddddddd\n"
8344                "                                : eeeeeeeeeeeeeeeeee\n"
8345                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8346                "                                 : 3333333333333333;",
8347                Style);
8348 
8349   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8350   Style.BreakBeforeTernaryOperators = false;
8351   // FIXME: Aligning the question marks is weird given DontAlign.
8352   // Consider disabling this alignment in this case. Also check whether this
8353   // will render the adjustment from https://reviews.llvm.org/D82199
8354   // unnecessary.
8355   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
8356                "    bbbb                ? cccccccccccccccccc :\n"
8357                "                          ddddd;\n",
8358                Style);
8359 
8360   EXPECT_EQ(
8361       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8362       "    /*\n"
8363       "     */\n"
8364       "    function() {\n"
8365       "      try {\n"
8366       "        return JJJJJJJJJJJJJJ(\n"
8367       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8368       "      }\n"
8369       "    } :\n"
8370       "    function() {};",
8371       format(
8372           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8373           "     /*\n"
8374           "      */\n"
8375           "     function() {\n"
8376           "      try {\n"
8377           "        return JJJJJJJJJJJJJJ(\n"
8378           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8379           "      }\n"
8380           "    } :\n"
8381           "    function() {};",
8382           getGoogleStyle(FormatStyle::LK_JavaScript)));
8383 }
8384 
8385 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
8386   FormatStyle Style = getLLVMStyleWithColumns(70);
8387   Style.BreakBeforeTernaryOperators = false;
8388   verifyFormat(
8389       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8390       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8391       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8392       Style);
8393   verifyFormat(
8394       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8395       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8396       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8397       Style);
8398   verifyFormat(
8399       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8400       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8401       Style);
8402   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
8403                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8404                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8405                Style);
8406   verifyFormat(
8407       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
8408       "                                                      aaaaaaaaaaaaa);",
8409       Style);
8410   verifyFormat(
8411       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8412       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8413       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8414       "                   aaaaaaaaaaaaa);",
8415       Style);
8416   verifyFormat(
8417       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8418       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8419       "                   aaaaaaaaaaaaa);",
8420       Style);
8421   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8422                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8423                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8424                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8425                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8426                Style);
8427   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8428                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8429                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8430                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8431                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8432                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8433                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8434                Style);
8435   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8436                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8437                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8438                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8439                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8440                Style);
8441   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8442                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8443                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8444                Style);
8445   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8446                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8447                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8448                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8449                Style);
8450   verifyFormat(
8451       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8452       "    aaaaaaaaaaaaaaa :\n"
8453       "    aaaaaaaaaaaaaaa;",
8454       Style);
8455   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8456                "          aaaaaaaaa ?\n"
8457                "      b :\n"
8458                "      c);",
8459                Style);
8460   verifyFormat("unsigned Indent =\n"
8461                "    format(TheLine.First,\n"
8462                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8463                "               IndentForLevel[TheLine.Level] :\n"
8464                "               TheLine * 2,\n"
8465                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8466                Style);
8467   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8468                "                  aaaaaaaaaaaaaaa :\n"
8469                "                  bbbbbbbbbbbbbbb ? //\n"
8470                "                      ccccccccccccccc :\n"
8471                "                      ddddddddddddddd;",
8472                Style);
8473   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8474                "                  aaaaaaaaaaaaaaa :\n"
8475                "                  (bbbbbbbbbbbbbbb ? //\n"
8476                "                       ccccccccccccccc :\n"
8477                "                       ddddddddddddddd);",
8478                Style);
8479   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8480                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8481                "            ccccccccccccccccccccccccccc;",
8482                Style);
8483   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8484                "           aaaaa :\n"
8485                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8486                Style);
8487 
8488   // Chained conditionals
8489   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8490                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8491                "                          3333333333333333;",
8492                Style);
8493   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8494                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8495                "                          3333333333333333;",
8496                Style);
8497   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8498                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8499                "                          3333333333333333;",
8500                Style);
8501   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8502                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8503                "                          333333;",
8504                Style);
8505   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8506                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8507                "       cccccccccccccccc ? 3333333333333333 :\n"
8508                "                          4444444444444444;",
8509                Style);
8510   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8511                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8512                "                          3333333333333333;",
8513                Style);
8514   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8515                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8516                "                          (aaa ? bbb : ccc);",
8517                Style);
8518   verifyFormat(
8519       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8520       "                                               cccccccccccccccccc) :\n"
8521       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8522       "                          3333333333333333;",
8523       Style);
8524   verifyFormat(
8525       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8526       "                                               cccccccccccccccccc) :\n"
8527       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8528       "                          3333333333333333;",
8529       Style);
8530   verifyFormat(
8531       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8532       "                                               dddddddddddddddddd) :\n"
8533       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8534       "                          3333333333333333;",
8535       Style);
8536   verifyFormat(
8537       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8538       "                                               dddddddddddddddddd) :\n"
8539       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8540       "                          3333333333333333;",
8541       Style);
8542   verifyFormat(
8543       "return aaaaaaaaa        ? 1111111111111111 :\n"
8544       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8545       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8546       "                                               dddddddddddddddddd)\n",
8547       Style);
8548   verifyFormat(
8549       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8550       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8551       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8552       "                                               cccccccccccccccccc);",
8553       Style);
8554   verifyFormat(
8555       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8556       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8557       "                                               eeeeeeeeeeeeeeeeee) :\n"
8558       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8559       "                          3333333333333333;",
8560       Style);
8561   verifyFormat(
8562       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8563       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8564       "                                               eeeeeeeeeeeeeeeeee) :\n"
8565       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8566       "                          3333333333333333;",
8567       Style);
8568   verifyFormat(
8569       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8570       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8571       "                                               eeeeeeeeeeeeeeeeee) :\n"
8572       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8573       "                          3333333333333333;",
8574       Style);
8575   verifyFormat(
8576       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8577       "                                               cccccccccccccccccc :\n"
8578       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8579       "                          3333333333333333;",
8580       Style);
8581   verifyFormat(
8582       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8583       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8584       "                                               eeeeeeeeeeeeeeeeee :\n"
8585       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8586       "                          3333333333333333;",
8587       Style);
8588   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8589                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8590                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8591                "                                 eeeeeeeeeeeeeeeeee) :\n"
8592                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8593                "                               3333333333333333;",
8594                Style);
8595   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8596                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8597                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8598                "                                  eeeeeeeeeeeeeeeeee :\n"
8599                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8600                "                               3333333333333333;",
8601                Style);
8602 }
8603 
8604 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8605   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8606                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8607   verifyFormat("bool a = true, b = false;");
8608 
8609   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8610                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8611                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8612                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8613   verifyFormat(
8614       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8615       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8616       "     d = e && f;");
8617   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8618                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8619   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8620                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8621   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8622                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8623 
8624   FormatStyle Style = getGoogleStyle();
8625   Style.PointerAlignment = FormatStyle::PAS_Left;
8626   Style.DerivePointerAlignment = false;
8627   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8628                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8629                "    *b = bbbbbbbbbbbbbbbbbbb;",
8630                Style);
8631   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8632                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8633                Style);
8634   verifyFormat("vector<int*> a, b;", Style);
8635   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8636   verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
8637   verifyFormat("if (int *p, *q; p != q) {\n  p = p->next;\n}", Style);
8638   verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n  p = p->next;\n}",
8639                Style);
8640   verifyFormat("switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8641                Style);
8642   verifyFormat(
8643       "/*comment*/ switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8644       Style);
8645 
8646   verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
8647   verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
8648   verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
8649   verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
8650   verifyFormat("switch ([](int* p, int* q) {}()) {\n  default:\n    break;\n}",
8651                Style);
8652 }
8653 
8654 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8655   verifyFormat("arr[foo ? bar : baz];");
8656   verifyFormat("f()[foo ? bar : baz];");
8657   verifyFormat("(a + b)[foo ? bar : baz];");
8658   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8659 }
8660 
8661 TEST_F(FormatTest, AlignsStringLiterals) {
8662   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8663                "                                      \"short literal\");");
8664   verifyFormat(
8665       "looooooooooooooooooooooooongFunction(\n"
8666       "    \"short literal\"\n"
8667       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8668   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8669                "             \" string literals\",\n"
8670                "             and, other, parameters);");
8671   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8672             "      \"5678\";",
8673             format("fun + \"1243\" /* comment */\n"
8674                    "    \"5678\";",
8675                    getLLVMStyleWithColumns(28)));
8676   EXPECT_EQ(
8677       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8678       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8679       "         \"aaaaaaaaaaaaaaaa\";",
8680       format("aaaaaa ="
8681              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8682              "aaaaaaaaaaaaaaaaaaaaa\" "
8683              "\"aaaaaaaaaaaaaaaa\";"));
8684   verifyFormat("a = a + \"a\"\n"
8685                "        \"a\"\n"
8686                "        \"a\";");
8687   verifyFormat("f(\"a\", \"b\"\n"
8688                "       \"c\");");
8689 
8690   verifyFormat(
8691       "#define LL_FORMAT \"ll\"\n"
8692       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8693       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8694 
8695   verifyFormat("#define A(X)          \\\n"
8696                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8697                "  \"ccccc\"",
8698                getLLVMStyleWithColumns(23));
8699   verifyFormat("#define A \"def\"\n"
8700                "f(\"abc\" A \"ghi\"\n"
8701                "  \"jkl\");");
8702 
8703   verifyFormat("f(L\"a\"\n"
8704                "  L\"b\");");
8705   verifyFormat("#define A(X)            \\\n"
8706                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8707                "  L\"ccccc\"",
8708                getLLVMStyleWithColumns(25));
8709 
8710   verifyFormat("f(@\"a\"\n"
8711                "  @\"b\");");
8712   verifyFormat("NSString s = @\"a\"\n"
8713                "             @\"b\"\n"
8714                "             @\"c\";");
8715   verifyFormat("NSString s = @\"a\"\n"
8716                "              \"b\"\n"
8717                "              \"c\";");
8718 }
8719 
8720 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8721   FormatStyle Style = getLLVMStyle();
8722   // No declarations or definitions should be moved to own line.
8723   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8724   verifyFormat("class A {\n"
8725                "  int f() { return 1; }\n"
8726                "  int g();\n"
8727                "};\n"
8728                "int f() { return 1; }\n"
8729                "int g();\n",
8730                Style);
8731 
8732   // All declarations and definitions should have the return type moved to its
8733   // own line.
8734   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8735   Style.TypenameMacros = {"LIST"};
8736   verifyFormat("SomeType\n"
8737                "funcdecl(LIST(uint64_t));",
8738                Style);
8739   verifyFormat("class E {\n"
8740                "  int\n"
8741                "  f() {\n"
8742                "    return 1;\n"
8743                "  }\n"
8744                "  int\n"
8745                "  g();\n"
8746                "};\n"
8747                "int\n"
8748                "f() {\n"
8749                "  return 1;\n"
8750                "}\n"
8751                "int\n"
8752                "g();\n",
8753                Style);
8754 
8755   // Top-level definitions, and no kinds of declarations should have the
8756   // return type moved to its own line.
8757   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8758   verifyFormat("class B {\n"
8759                "  int f() { return 1; }\n"
8760                "  int g();\n"
8761                "};\n"
8762                "int\n"
8763                "f() {\n"
8764                "  return 1;\n"
8765                "}\n"
8766                "int g();\n",
8767                Style);
8768 
8769   // Top-level definitions and declarations should have the return type moved
8770   // to its own line.
8771   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8772   verifyFormat("class C {\n"
8773                "  int f() { return 1; }\n"
8774                "  int g();\n"
8775                "};\n"
8776                "int\n"
8777                "f() {\n"
8778                "  return 1;\n"
8779                "}\n"
8780                "int\n"
8781                "g();\n",
8782                Style);
8783 
8784   // All definitions should have the return type moved to its own line, but no
8785   // kinds of declarations.
8786   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8787   verifyFormat("class D {\n"
8788                "  int\n"
8789                "  f() {\n"
8790                "    return 1;\n"
8791                "  }\n"
8792                "  int g();\n"
8793                "};\n"
8794                "int\n"
8795                "f() {\n"
8796                "  return 1;\n"
8797                "}\n"
8798                "int g();\n",
8799                Style);
8800   verifyFormat("const char *\n"
8801                "f(void) {\n" // Break here.
8802                "  return \"\";\n"
8803                "}\n"
8804                "const char *bar(void);\n", // No break here.
8805                Style);
8806   verifyFormat("template <class T>\n"
8807                "T *\n"
8808                "f(T &c) {\n" // Break here.
8809                "  return NULL;\n"
8810                "}\n"
8811                "template <class T> T *f(T &c);\n", // No break here.
8812                Style);
8813   verifyFormat("class C {\n"
8814                "  int\n"
8815                "  operator+() {\n"
8816                "    return 1;\n"
8817                "  }\n"
8818                "  int\n"
8819                "  operator()() {\n"
8820                "    return 1;\n"
8821                "  }\n"
8822                "};\n",
8823                Style);
8824   verifyFormat("void\n"
8825                "A::operator()() {}\n"
8826                "void\n"
8827                "A::operator>>() {}\n"
8828                "void\n"
8829                "A::operator+() {}\n"
8830                "void\n"
8831                "A::operator*() {}\n"
8832                "void\n"
8833                "A::operator->() {}\n"
8834                "void\n"
8835                "A::operator void *() {}\n"
8836                "void\n"
8837                "A::operator void &() {}\n"
8838                "void\n"
8839                "A::operator void &&() {}\n"
8840                "void\n"
8841                "A::operator char *() {}\n"
8842                "void\n"
8843                "A::operator[]() {}\n"
8844                "void\n"
8845                "A::operator!() {}\n"
8846                "void\n"
8847                "A::operator**() {}\n"
8848                "void\n"
8849                "A::operator<Foo> *() {}\n"
8850                "void\n"
8851                "A::operator<Foo> **() {}\n"
8852                "void\n"
8853                "A::operator<Foo> &() {}\n"
8854                "void\n"
8855                "A::operator void **() {}\n",
8856                Style);
8857   verifyFormat("constexpr auto\n"
8858                "operator()() const -> reference {}\n"
8859                "constexpr auto\n"
8860                "operator>>() const -> reference {}\n"
8861                "constexpr auto\n"
8862                "operator+() const -> reference {}\n"
8863                "constexpr auto\n"
8864                "operator*() const -> reference {}\n"
8865                "constexpr auto\n"
8866                "operator->() const -> reference {}\n"
8867                "constexpr auto\n"
8868                "operator++() const -> reference {}\n"
8869                "constexpr auto\n"
8870                "operator void *() const -> reference {}\n"
8871                "constexpr auto\n"
8872                "operator void **() const -> reference {}\n"
8873                "constexpr auto\n"
8874                "operator void *() const -> reference {}\n"
8875                "constexpr auto\n"
8876                "operator void &() const -> reference {}\n"
8877                "constexpr auto\n"
8878                "operator void &&() const -> reference {}\n"
8879                "constexpr auto\n"
8880                "operator char *() const -> reference {}\n"
8881                "constexpr auto\n"
8882                "operator!() const -> reference {}\n"
8883                "constexpr auto\n"
8884                "operator[]() const -> reference {}\n",
8885                Style);
8886   verifyFormat("void *operator new(std::size_t s);", // No break here.
8887                Style);
8888   verifyFormat("void *\n"
8889                "operator new(std::size_t s) {}",
8890                Style);
8891   verifyFormat("void *\n"
8892                "operator delete[](void *ptr) {}",
8893                Style);
8894   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8895   verifyFormat("const char *\n"
8896                "f(void)\n" // Break here.
8897                "{\n"
8898                "  return \"\";\n"
8899                "}\n"
8900                "const char *bar(void);\n", // No break here.
8901                Style);
8902   verifyFormat("template <class T>\n"
8903                "T *\n"     // Problem here: no line break
8904                "f(T &c)\n" // Break here.
8905                "{\n"
8906                "  return NULL;\n"
8907                "}\n"
8908                "template <class T> T *f(T &c);\n", // No break here.
8909                Style);
8910   verifyFormat("int\n"
8911                "foo(A<bool> a)\n"
8912                "{\n"
8913                "  return a;\n"
8914                "}\n",
8915                Style);
8916   verifyFormat("int\n"
8917                "foo(A<8> a)\n"
8918                "{\n"
8919                "  return a;\n"
8920                "}\n",
8921                Style);
8922   verifyFormat("int\n"
8923                "foo(A<B<bool>, 8> a)\n"
8924                "{\n"
8925                "  return a;\n"
8926                "}\n",
8927                Style);
8928   verifyFormat("int\n"
8929                "foo(A<B<8>, bool> a)\n"
8930                "{\n"
8931                "  return a;\n"
8932                "}\n",
8933                Style);
8934   verifyFormat("int\n"
8935                "foo(A<B<bool>, bool> a)\n"
8936                "{\n"
8937                "  return a;\n"
8938                "}\n",
8939                Style);
8940   verifyFormat("int\n"
8941                "foo(A<B<8>, 8> a)\n"
8942                "{\n"
8943                "  return a;\n"
8944                "}\n",
8945                Style);
8946 
8947   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8948   Style.BraceWrapping.AfterFunction = true;
8949   verifyFormat("int f(i);\n" // No break here.
8950                "int\n"       // Break here.
8951                "f(i)\n"
8952                "{\n"
8953                "  return i + 1;\n"
8954                "}\n"
8955                "int\n" // Break here.
8956                "f(i)\n"
8957                "{\n"
8958                "  return i + 1;\n"
8959                "};",
8960                Style);
8961   verifyFormat("int f(a, b, c);\n" // No break here.
8962                "int\n"             // Break here.
8963                "f(a, b, c)\n"      // Break here.
8964                "short a, b;\n"
8965                "float c;\n"
8966                "{\n"
8967                "  return a + b < c;\n"
8968                "}\n"
8969                "int\n"        // Break here.
8970                "f(a, b, c)\n" // Break here.
8971                "short a, b;\n"
8972                "float c;\n"
8973                "{\n"
8974                "  return a + b < c;\n"
8975                "};",
8976                Style);
8977   verifyFormat("byte *\n" // Break here.
8978                "f(a)\n"   // Break here.
8979                "byte a[];\n"
8980                "{\n"
8981                "  return a;\n"
8982                "}",
8983                Style);
8984   verifyFormat("bool f(int a, int) override;\n"
8985                "Bar g(int a, Bar) final;\n"
8986                "Bar h(a, Bar) final;",
8987                Style);
8988   verifyFormat("int\n"
8989                "f(a)",
8990                Style);
8991   verifyFormat("bool\n"
8992                "f(size_t = 0, bool b = false)\n"
8993                "{\n"
8994                "  return !b;\n"
8995                "}",
8996                Style);
8997 
8998   // The return breaking style doesn't affect:
8999   // * function and object definitions with attribute-like macros
9000   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9001                "    ABSL_GUARDED_BY(mutex) = {};",
9002                getGoogleStyleWithColumns(40));
9003   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9004                "    ABSL_GUARDED_BY(mutex);  // comment",
9005                getGoogleStyleWithColumns(40));
9006   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9007                "    ABSL_GUARDED_BY(mutex1)\n"
9008                "        ABSL_GUARDED_BY(mutex2);",
9009                getGoogleStyleWithColumns(40));
9010   verifyFormat("Tttttt f(int a, int b)\n"
9011                "    ABSL_GUARDED_BY(mutex1)\n"
9012                "        ABSL_GUARDED_BY(mutex2);",
9013                getGoogleStyleWithColumns(40));
9014   // * typedefs
9015   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
9016 
9017   Style = getGNUStyle();
9018 
9019   // Test for comments at the end of function declarations.
9020   verifyFormat("void\n"
9021                "foo (int a, /*abc*/ int b) // def\n"
9022                "{\n"
9023                "}\n",
9024                Style);
9025 
9026   verifyFormat("void\n"
9027                "foo (int a, /* abc */ int b) /* def */\n"
9028                "{\n"
9029                "}\n",
9030                Style);
9031 
9032   // Definitions that should not break after return type
9033   verifyFormat("void foo (int a, int b); // def\n", Style);
9034   verifyFormat("void foo (int a, int b); /* def */\n", Style);
9035   verifyFormat("void foo (int a, int b);\n", Style);
9036 }
9037 
9038 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
9039   FormatStyle NoBreak = getLLVMStyle();
9040   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
9041   FormatStyle Break = getLLVMStyle();
9042   Break.AlwaysBreakBeforeMultilineStrings = true;
9043   verifyFormat("aaaa = \"bbbb\"\n"
9044                "       \"cccc\";",
9045                NoBreak);
9046   verifyFormat("aaaa =\n"
9047                "    \"bbbb\"\n"
9048                "    \"cccc\";",
9049                Break);
9050   verifyFormat("aaaa(\"bbbb\"\n"
9051                "     \"cccc\");",
9052                NoBreak);
9053   verifyFormat("aaaa(\n"
9054                "    \"bbbb\"\n"
9055                "    \"cccc\");",
9056                Break);
9057   verifyFormat("aaaa(qqq, \"bbbb\"\n"
9058                "          \"cccc\");",
9059                NoBreak);
9060   verifyFormat("aaaa(qqq,\n"
9061                "     \"bbbb\"\n"
9062                "     \"cccc\");",
9063                Break);
9064   verifyFormat("aaaa(qqq,\n"
9065                "     L\"bbbb\"\n"
9066                "     L\"cccc\");",
9067                Break);
9068   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
9069                "                      \"bbbb\"));",
9070                Break);
9071   verifyFormat("string s = someFunction(\n"
9072                "    \"abc\"\n"
9073                "    \"abc\");",
9074                Break);
9075 
9076   // As we break before unary operators, breaking right after them is bad.
9077   verifyFormat("string foo = abc ? \"x\"\n"
9078                "                   \"blah blah blah blah blah blah\"\n"
9079                "                 : \"y\";",
9080                Break);
9081 
9082   // Don't break if there is no column gain.
9083   verifyFormat("f(\"aaaa\"\n"
9084                "  \"bbbb\");",
9085                Break);
9086 
9087   // Treat literals with escaped newlines like multi-line string literals.
9088   EXPECT_EQ("x = \"a\\\n"
9089             "b\\\n"
9090             "c\";",
9091             format("x = \"a\\\n"
9092                    "b\\\n"
9093                    "c\";",
9094                    NoBreak));
9095   EXPECT_EQ("xxxx =\n"
9096             "    \"a\\\n"
9097             "b\\\n"
9098             "c\";",
9099             format("xxxx = \"a\\\n"
9100                    "b\\\n"
9101                    "c\";",
9102                    Break));
9103 
9104   EXPECT_EQ("NSString *const kString =\n"
9105             "    @\"aaaa\"\n"
9106             "    @\"bbbb\";",
9107             format("NSString *const kString = @\"aaaa\"\n"
9108                    "@\"bbbb\";",
9109                    Break));
9110 
9111   Break.ColumnLimit = 0;
9112   verifyFormat("const char *hello = \"hello llvm\";", Break);
9113 }
9114 
9115 TEST_F(FormatTest, AlignsPipes) {
9116   verifyFormat(
9117       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9118       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9119       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9120   verifyFormat(
9121       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
9122       "                     << aaaaaaaaaaaaaaaaaaaa;");
9123   verifyFormat(
9124       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9125       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9126   verifyFormat(
9127       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
9128       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9129   verifyFormat(
9130       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
9131       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
9132       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
9133   verifyFormat(
9134       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9135       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9136       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9137   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9138                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9139                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9140                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9141   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
9142                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
9143   verifyFormat(
9144       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9145       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9146   verifyFormat(
9147       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
9148       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
9149 
9150   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
9151                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
9152   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9153                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9154                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
9155                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
9156   verifyFormat("LOG_IF(aaa == //\n"
9157                "       bbb)\n"
9158                "    << a << b;");
9159 
9160   // But sometimes, breaking before the first "<<" is desirable.
9161   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9162                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
9163   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
9164                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9165                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9166   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
9167                "    << BEF << IsTemplate << Description << E->getType();");
9168   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9169                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9170                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9171   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9172                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9173                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9174                "    << aaa;");
9175 
9176   verifyFormat(
9177       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9178       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9179 
9180   // Incomplete string literal.
9181   EXPECT_EQ("llvm::errs() << \"\n"
9182             "             << a;",
9183             format("llvm::errs() << \"\n<<a;"));
9184 
9185   verifyFormat("void f() {\n"
9186                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
9187                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
9188                "}");
9189 
9190   // Handle 'endl'.
9191   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
9192                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9193   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9194 
9195   // Handle '\n'.
9196   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
9197                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9198   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
9199                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
9200   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
9201                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
9202   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9203 }
9204 
9205 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
9206   verifyFormat("return out << \"somepacket = {\\n\"\n"
9207                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
9208                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
9209                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
9210                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
9211                "           << \"}\";");
9212 
9213   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9214                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9215                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
9216   verifyFormat(
9217       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
9218       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
9219       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
9220       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
9221       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
9222   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
9223                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9224   verifyFormat(
9225       "void f() {\n"
9226       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
9227       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
9228       "}");
9229 
9230   // Breaking before the first "<<" is generally not desirable.
9231   verifyFormat(
9232       "llvm::errs()\n"
9233       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9234       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9235       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9236       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9237       getLLVMStyleWithColumns(70));
9238   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9239                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9240                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9241                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9242                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9243                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9244                getLLVMStyleWithColumns(70));
9245 
9246   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9247                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9248                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
9249   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9250                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9251                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
9252   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
9253                "           (aaaa + aaaa);",
9254                getLLVMStyleWithColumns(40));
9255   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
9256                "                  (aaaaaaa + aaaaa));",
9257                getLLVMStyleWithColumns(40));
9258   verifyFormat(
9259       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
9260       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
9261       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
9262 }
9263 
9264 TEST_F(FormatTest, UnderstandsEquals) {
9265   verifyFormat(
9266       "aaaaaaaaaaaaaaaaa =\n"
9267       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9268   verifyFormat(
9269       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9270       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9271   verifyFormat(
9272       "if (a) {\n"
9273       "  f();\n"
9274       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9275       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
9276       "}");
9277 
9278   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9279                "        100000000 + 10000000) {\n}");
9280 }
9281 
9282 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
9283   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9284                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
9285 
9286   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9287                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
9288 
9289   verifyFormat(
9290       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
9291       "                                                          Parameter2);");
9292 
9293   verifyFormat(
9294       "ShortObject->shortFunction(\n"
9295       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
9296       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
9297 
9298   verifyFormat("loooooooooooooongFunction(\n"
9299                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
9300 
9301   verifyFormat(
9302       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
9303       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
9304 
9305   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9306                "    .WillRepeatedly(Return(SomeValue));");
9307   verifyFormat("void f() {\n"
9308                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9309                "      .Times(2)\n"
9310                "      .WillRepeatedly(Return(SomeValue));\n"
9311                "}");
9312   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
9313                "    ccccccccccccccccccccccc);");
9314   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9315                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9316                "          .aaaaa(aaaaa),\n"
9317                "      aaaaaaaaaaaaaaaaaaaaa);");
9318   verifyFormat("void f() {\n"
9319                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9320                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
9321                "}");
9322   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9323                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9324                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9325                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9326                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9327   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9328                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9329                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9330                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
9331                "}");
9332 
9333   // Here, it is not necessary to wrap at "." or "->".
9334   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
9335                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9336   verifyFormat(
9337       "aaaaaaaaaaa->aaaaaaaaa(\n"
9338       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9339       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
9340 
9341   verifyFormat(
9342       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9343       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
9344   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
9345                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9346   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
9347                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9348 
9349   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9350                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9351                "    .a();");
9352 
9353   FormatStyle NoBinPacking = getLLVMStyle();
9354   NoBinPacking.BinPackParameters = false;
9355   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9356                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9357                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
9358                "                         aaaaaaaaaaaaaaaaaaa,\n"
9359                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
9360                NoBinPacking);
9361 
9362   // If there is a subsequent call, change to hanging indentation.
9363   verifyFormat(
9364       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9365       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
9366       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9367   verifyFormat(
9368       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9369       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
9370   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9371                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9372                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9373   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9374                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9375                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9376 }
9377 
9378 TEST_F(FormatTest, WrapsTemplateDeclarations) {
9379   verifyFormat("template <typename T>\n"
9380                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9381   verifyFormat("template <typename T>\n"
9382                "// T should be one of {A, B}.\n"
9383                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9384   verifyFormat(
9385       "template <typename T>\n"
9386       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
9387   verifyFormat("template <typename T>\n"
9388                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
9389                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
9390   verifyFormat(
9391       "template <typename T>\n"
9392       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
9393       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
9394   verifyFormat(
9395       "template <typename T>\n"
9396       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
9397       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
9398       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9399   verifyFormat("template <typename T>\n"
9400                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9401                "    int aaaaaaaaaaaaaaaaaaaaaa);");
9402   verifyFormat(
9403       "template <typename T1, typename T2 = char, typename T3 = char,\n"
9404       "          typename T4 = char>\n"
9405       "void f();");
9406   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
9407                "          template <typename> class cccccccccccccccccccccc,\n"
9408                "          typename ddddddddddddd>\n"
9409                "class C {};");
9410   verifyFormat(
9411       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
9412       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9413 
9414   verifyFormat("void f() {\n"
9415                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
9416                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
9417                "}");
9418 
9419   verifyFormat("template <typename T> class C {};");
9420   verifyFormat("template <typename T> void f();");
9421   verifyFormat("template <typename T> void f() {}");
9422   verifyFormat(
9423       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9424       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9425       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
9426       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9427       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9428       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
9429       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
9430       getLLVMStyleWithColumns(72));
9431   EXPECT_EQ("static_cast<A< //\n"
9432             "    B> *>(\n"
9433             "\n"
9434             ");",
9435             format("static_cast<A<//\n"
9436                    "    B>*>(\n"
9437                    "\n"
9438                    "    );"));
9439   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9440                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
9441 
9442   FormatStyle AlwaysBreak = getLLVMStyle();
9443   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9444   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
9445   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
9446   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
9447   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9448                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9449                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9450   verifyFormat("template <template <typename> class Fooooooo,\n"
9451                "          template <typename> class Baaaaaaar>\n"
9452                "struct C {};",
9453                AlwaysBreak);
9454   verifyFormat("template <typename T> // T can be A, B or C.\n"
9455                "struct C {};",
9456                AlwaysBreak);
9457   verifyFormat("template <enum E> class A {\n"
9458                "public:\n"
9459                "  E *f();\n"
9460                "};");
9461 
9462   FormatStyle NeverBreak = getLLVMStyle();
9463   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9464   verifyFormat("template <typename T> class C {};", NeverBreak);
9465   verifyFormat("template <typename T> void f();", NeverBreak);
9466   verifyFormat("template <typename T> void f() {}", NeverBreak);
9467   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9468                "bbbbbbbbbbbbbbbbbbbb) {}",
9469                NeverBreak);
9470   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9471                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9472                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9473                NeverBreak);
9474   verifyFormat("template <template <typename> class Fooooooo,\n"
9475                "          template <typename> class Baaaaaaar>\n"
9476                "struct C {};",
9477                NeverBreak);
9478   verifyFormat("template <typename T> // T can be A, B or C.\n"
9479                "struct C {};",
9480                NeverBreak);
9481   verifyFormat("template <enum E> class A {\n"
9482                "public:\n"
9483                "  E *f();\n"
9484                "};",
9485                NeverBreak);
9486   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9487   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9488                "bbbbbbbbbbbbbbbbbbbb) {}",
9489                NeverBreak);
9490 }
9491 
9492 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9493   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9494   Style.ColumnLimit = 60;
9495   EXPECT_EQ("// Baseline - no comments.\n"
9496             "template <\n"
9497             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9498             "void f() {}",
9499             format("// Baseline - no comments.\n"
9500                    "template <\n"
9501                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9502                    "void f() {}",
9503                    Style));
9504 
9505   EXPECT_EQ("template <\n"
9506             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9507             "void f() {}",
9508             format("template <\n"
9509                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9510                    "void f() {}",
9511                    Style));
9512 
9513   EXPECT_EQ(
9514       "template <\n"
9515       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9516       "void f() {}",
9517       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9518              "void f() {}",
9519              Style));
9520 
9521   EXPECT_EQ(
9522       "template <\n"
9523       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9524       "                                               // multiline\n"
9525       "void f() {}",
9526       format("template <\n"
9527              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9528              "                                              // multiline\n"
9529              "void f() {}",
9530              Style));
9531 
9532   EXPECT_EQ(
9533       "template <typename aaaaaaaaaa<\n"
9534       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9535       "void f() {}",
9536       format(
9537           "template <\n"
9538           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9539           "void f() {}",
9540           Style));
9541 }
9542 
9543 TEST_F(FormatTest, WrapsTemplateParameters) {
9544   FormatStyle Style = getLLVMStyle();
9545   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9546   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9547   verifyFormat(
9548       "template <typename... a> struct q {};\n"
9549       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9550       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9551       "    y;",
9552       Style);
9553   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9554   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9555   verifyFormat(
9556       "template <typename... a> struct r {};\n"
9557       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9558       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9559       "    y;",
9560       Style);
9561   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9562   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9563   verifyFormat("template <typename... a> struct s {};\n"
9564                "extern s<\n"
9565                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9566                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9567                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9568                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9569                "    y;",
9570                Style);
9571   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9572   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9573   verifyFormat("template <typename... a> struct t {};\n"
9574                "extern t<\n"
9575                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9576                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9577                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9578                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9579                "    y;",
9580                Style);
9581 }
9582 
9583 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9584   verifyFormat(
9585       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9586       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9587   verifyFormat(
9588       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9589       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9590       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9591 
9592   // FIXME: Should we have the extra indent after the second break?
9593   verifyFormat(
9594       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9595       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9596       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9597 
9598   verifyFormat(
9599       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9600       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9601 
9602   // Breaking at nested name specifiers is generally not desirable.
9603   verifyFormat(
9604       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9605       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9606 
9607   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9608                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9609                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9610                "                   aaaaaaaaaaaaaaaaaaaaa);",
9611                getLLVMStyleWithColumns(74));
9612 
9613   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9614                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9615                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9616 }
9617 
9618 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9619   verifyFormat("A<int> a;");
9620   verifyFormat("A<A<A<int>>> a;");
9621   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9622   verifyFormat("bool x = a < 1 || 2 > a;");
9623   verifyFormat("bool x = 5 < f<int>();");
9624   verifyFormat("bool x = f<int>() > 5;");
9625   verifyFormat("bool x = 5 < a<int>::x;");
9626   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9627   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9628 
9629   verifyGoogleFormat("A<A<int>> a;");
9630   verifyGoogleFormat("A<A<A<int>>> a;");
9631   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9632   verifyGoogleFormat("A<A<int> > a;");
9633   verifyGoogleFormat("A<A<A<int> > > a;");
9634   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9635   verifyGoogleFormat("A<::A<int>> a;");
9636   verifyGoogleFormat("A<::A> a;");
9637   verifyGoogleFormat("A< ::A> a;");
9638   verifyGoogleFormat("A< ::A<int> > a;");
9639   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9640   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9641   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9642   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9643   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9644             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9645 
9646   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9647 
9648   // template closer followed by a token that starts with > or =
9649   verifyFormat("bool b = a<1> > 1;");
9650   verifyFormat("bool b = a<1> >= 1;");
9651   verifyFormat("int i = a<1> >> 1;");
9652   FormatStyle Style = getLLVMStyle();
9653   Style.SpaceBeforeAssignmentOperators = false;
9654   verifyFormat("bool b= a<1> == 1;", Style);
9655   verifyFormat("a<int> = 1;", Style);
9656   verifyFormat("a<int> >>= 1;", Style);
9657 
9658   verifyFormat("test < a | b >> c;");
9659   verifyFormat("test<test<a | b>> c;");
9660   verifyFormat("test >> a >> b;");
9661   verifyFormat("test << a >> b;");
9662 
9663   verifyFormat("f<int>();");
9664   verifyFormat("template <typename T> void f() {}");
9665   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9666   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9667                "sizeof(char)>::type>;");
9668   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9669   verifyFormat("f(a.operator()<A>());");
9670   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9671                "      .template operator()<A>());",
9672                getLLVMStyleWithColumns(35));
9673   verifyFormat("bool_constant<a && noexcept(f())>");
9674   verifyFormat("bool_constant<a || noexcept(f())>");
9675 
9676   // Not template parameters.
9677   verifyFormat("return a < b && c > d;");
9678   verifyFormat("void f() {\n"
9679                "  while (a < b && c > d) {\n"
9680                "  }\n"
9681                "}");
9682   verifyFormat("template <typename... Types>\n"
9683                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9684 
9685   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9686                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9687                getLLVMStyleWithColumns(60));
9688   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9689   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9690   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9691   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9692 }
9693 
9694 TEST_F(FormatTest, UnderstandsShiftOperators) {
9695   verifyFormat("if (i < x >> 1)");
9696   verifyFormat("while (i < x >> 1)");
9697   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9698   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9699   verifyFormat(
9700       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9701   verifyFormat("Foo.call<Bar<Function>>()");
9702   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9703   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9704                "++i, v = v >> 1)");
9705   verifyFormat("if (w<u<v<x>>, 1>::t)");
9706 }
9707 
9708 TEST_F(FormatTest, BitshiftOperatorWidth) {
9709   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9710             "                   bar */",
9711             format("int    a=1<<2;  /* foo\n"
9712                    "                   bar */"));
9713 
9714   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9715             "                     bar */",
9716             format("int  b  =256>>1 ;  /* foo\n"
9717                    "                      bar */"));
9718 }
9719 
9720 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9721   verifyFormat("COMPARE(a, ==, b);");
9722   verifyFormat("auto s = sizeof...(Ts) - 1;");
9723 }
9724 
9725 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9726   verifyFormat("int A::*x;");
9727   verifyFormat("int (S::*func)(void *);");
9728   verifyFormat("void f() { int (S::*func)(void *); }");
9729   verifyFormat("typedef bool *(Class::*Member)() const;");
9730   verifyFormat("void f() {\n"
9731                "  (a->*f)();\n"
9732                "  a->*x;\n"
9733                "  (a.*f)();\n"
9734                "  ((*a).*f)();\n"
9735                "  a.*x;\n"
9736                "}");
9737   verifyFormat("void f() {\n"
9738                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9739                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9740                "}");
9741   verifyFormat(
9742       "(aaaaaaaaaa->*bbbbbbb)(\n"
9743       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9744   FormatStyle Style = getLLVMStyle();
9745   Style.PointerAlignment = FormatStyle::PAS_Left;
9746   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9747 }
9748 
9749 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9750   verifyFormat("int a = -2;");
9751   verifyFormat("f(-1, -2, -3);");
9752   verifyFormat("a[-1] = 5;");
9753   verifyFormat("int a = 5 + -2;");
9754   verifyFormat("if (i == -1) {\n}");
9755   verifyFormat("if (i != -1) {\n}");
9756   verifyFormat("if (i > -1) {\n}");
9757   verifyFormat("if (i < -1) {\n}");
9758   verifyFormat("++(a->f());");
9759   verifyFormat("--(a->f());");
9760   verifyFormat("(a->f())++;");
9761   verifyFormat("a[42]++;");
9762   verifyFormat("if (!(a->f())) {\n}");
9763   verifyFormat("if (!+i) {\n}");
9764   verifyFormat("~&a;");
9765   verifyFormat("for (x = 0; -10 < x; --x) {\n}");
9766   verifyFormat("sizeof -x");
9767   verifyFormat("sizeof +x");
9768   verifyFormat("sizeof *x");
9769   verifyFormat("sizeof &x");
9770   verifyFormat("delete +x;");
9771   verifyFormat("co_await +x;");
9772   verifyFormat("case *x:");
9773   verifyFormat("case &x:");
9774 
9775   verifyFormat("a-- > b;");
9776   verifyFormat("b ? -a : c;");
9777   verifyFormat("n * sizeof char16;");
9778   verifyFormat("n * alignof char16;", getGoogleStyle());
9779   verifyFormat("sizeof(char);");
9780   verifyFormat("alignof(char);", getGoogleStyle());
9781 
9782   verifyFormat("return -1;");
9783   verifyFormat("throw -1;");
9784   verifyFormat("switch (a) {\n"
9785                "case -1:\n"
9786                "  break;\n"
9787                "}");
9788   verifyFormat("#define X -1");
9789   verifyFormat("#define X -kConstant");
9790 
9791   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9792   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9793 
9794   verifyFormat("int a = /* confusing comment */ -1;");
9795   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9796   verifyFormat("int a = i /* confusing comment */++;");
9797 
9798   verifyFormat("co_yield -1;");
9799   verifyFormat("co_return -1;");
9800 
9801   // Check that * is not treated as a binary operator when we set
9802   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9803   FormatStyle PASLeftStyle = getLLVMStyle();
9804   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9805   verifyFormat("co_return *a;", PASLeftStyle);
9806   verifyFormat("co_await *a;", PASLeftStyle);
9807   verifyFormat("co_yield *a", PASLeftStyle);
9808   verifyFormat("return *a;", PASLeftStyle);
9809 }
9810 
9811 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9812   verifyFormat("if (!aaaaaaaaaa( // break\n"
9813                "        aaaaa)) {\n"
9814                "}");
9815   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9816                "    aaaaa));");
9817   verifyFormat("*aaa = aaaaaaa( // break\n"
9818                "    bbbbbb);");
9819 }
9820 
9821 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9822   verifyFormat("bool operator<();");
9823   verifyFormat("bool operator>();");
9824   verifyFormat("bool operator=();");
9825   verifyFormat("bool operator==();");
9826   verifyFormat("bool operator!=();");
9827   verifyFormat("int operator+();");
9828   verifyFormat("int operator++();");
9829   verifyFormat("int operator++(int) volatile noexcept;");
9830   verifyFormat("bool operator,();");
9831   verifyFormat("bool operator();");
9832   verifyFormat("bool operator()();");
9833   verifyFormat("bool operator[]();");
9834   verifyFormat("operator bool();");
9835   verifyFormat("operator int();");
9836   verifyFormat("operator void *();");
9837   verifyFormat("operator SomeType<int>();");
9838   verifyFormat("operator SomeType<int, int>();");
9839   verifyFormat("operator SomeType<SomeType<int>>();");
9840   verifyFormat("operator< <>();");
9841   verifyFormat("operator<< <>();");
9842   verifyFormat("< <>");
9843 
9844   verifyFormat("void *operator new(std::size_t size);");
9845   verifyFormat("void *operator new[](std::size_t size);");
9846   verifyFormat("void operator delete(void *ptr);");
9847   verifyFormat("void operator delete[](void *ptr);");
9848   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9849                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9850   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9851                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9852 
9853   verifyFormat(
9854       "ostream &operator<<(ostream &OutputStream,\n"
9855       "                    SomeReallyLongType WithSomeReallyLongValue);");
9856   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9857                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9858                "  return left.group < right.group;\n"
9859                "}");
9860   verifyFormat("SomeType &operator=(const SomeType &S);");
9861   verifyFormat("f.template operator()<int>();");
9862 
9863   verifyGoogleFormat("operator void*();");
9864   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9865   verifyGoogleFormat("operator ::A();");
9866 
9867   verifyFormat("using A::operator+;");
9868   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9869                "int i;");
9870 
9871   // Calling an operator as a member function.
9872   verifyFormat("void f() { a.operator*(); }");
9873   verifyFormat("void f() { a.operator*(b & b); }");
9874   verifyFormat("void f() { a->operator&(a * b); }");
9875   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9876   // TODO: Calling an operator as a non-member function is hard to distinguish.
9877   // https://llvm.org/PR50629
9878   // verifyFormat("void f() { operator*(a & a); }");
9879   // verifyFormat("void f() { operator&(a, b * b); }");
9880 
9881   verifyFormat("::operator delete(foo);");
9882   verifyFormat("::operator new(n * sizeof(foo));");
9883   verifyFormat("foo() { ::operator delete(foo); }");
9884   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9885 }
9886 
9887 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9888   verifyFormat("void A::b() && {}");
9889   verifyFormat("void A::b() &&noexcept {}");
9890   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9891   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9892   verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
9893   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9894   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9895   verifyFormat("Deleted &operator=(const Deleted &) &;");
9896   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9897   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9898   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9899   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9900   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9901   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9902   verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
9903   verifyFormat("void Fn(T const &) const &;");
9904   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9905   verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
9906   verifyFormat("template <typename T>\n"
9907                "void F(T) && = delete;",
9908                getGoogleStyle());
9909   verifyFormat("template <typename T> void operator=(T) &;");
9910   verifyFormat("template <typename T> void operator=(T) const &;");
9911   verifyFormat("template <typename T> void operator=(T) &noexcept;");
9912   verifyFormat("template <typename T> void operator=(T) & = default;");
9913   verifyFormat("template <typename T> void operator=(T) &&;");
9914   verifyFormat("template <typename T> void operator=(T) && = delete;");
9915   verifyFormat("template <typename T> void operator=(T) & {}");
9916   verifyFormat("template <typename T> void operator=(T) && {}");
9917 
9918   FormatStyle AlignLeft = getLLVMStyle();
9919   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9920   verifyFormat("void A::b() && {}", AlignLeft);
9921   verifyFormat("void A::b() && noexcept {}", AlignLeft);
9922   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9923   verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
9924                AlignLeft);
9925   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9926                AlignLeft);
9927   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9928   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9929   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9930   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9931   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9932   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9933   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9934   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9935   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
9936                AlignLeft);
9937   verifyFormat("template <typename T> void operator=(T) &;", AlignLeft);
9938   verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft);
9939   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9940                AlignLeft);
9941   verifyFormat("template <typename T> void operator=(T) & = default;",
9942                AlignLeft);
9943   verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft);
9944   verifyFormat("template <typename T> void operator=(T) && = delete;",
9945                AlignLeft);
9946   verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft);
9947   verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft);
9948 
9949   FormatStyle AlignMiddle = getLLVMStyle();
9950   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9951   verifyFormat("void A::b() && {}", AlignMiddle);
9952   verifyFormat("void A::b() && noexcept {}", AlignMiddle);
9953   verifyFormat("Deleted & operator=(const Deleted &) & = default;",
9954                AlignMiddle);
9955   verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
9956                AlignMiddle);
9957   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
9958                AlignMiddle);
9959   verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
9960   verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
9961   verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
9962   verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
9963   verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
9964   verifyFormat("auto Function(T) & -> void;", AlignMiddle);
9965   verifyFormat("void Fn(T const &) const &;", AlignMiddle);
9966   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
9967   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
9968                AlignMiddle);
9969   verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle);
9970   verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle);
9971   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9972                AlignMiddle);
9973   verifyFormat("template <typename T> void operator=(T) & = default;",
9974                AlignMiddle);
9975   verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle);
9976   verifyFormat("template <typename T> void operator=(T) && = delete;",
9977                AlignMiddle);
9978   verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle);
9979   verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle);
9980 
9981   FormatStyle Spaces = getLLVMStyle();
9982   Spaces.SpacesInCStyleCastParentheses = true;
9983   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9984   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9985   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9986   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9987 
9988   Spaces.SpacesInCStyleCastParentheses = false;
9989   Spaces.SpacesInParentheses = true;
9990   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9991   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9992                Spaces);
9993   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9994   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9995 
9996   FormatStyle BreakTemplate = getLLVMStyle();
9997   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9998 
9999   verifyFormat("struct f {\n"
10000                "  template <class T>\n"
10001                "  int &foo(const std::string &str) &noexcept {}\n"
10002                "};",
10003                BreakTemplate);
10004 
10005   verifyFormat("struct f {\n"
10006                "  template <class T>\n"
10007                "  int &foo(const std::string &str) &&noexcept {}\n"
10008                "};",
10009                BreakTemplate);
10010 
10011   verifyFormat("struct f {\n"
10012                "  template <class T>\n"
10013                "  int &foo(const std::string &str) const &noexcept {}\n"
10014                "};",
10015                BreakTemplate);
10016 
10017   verifyFormat("struct f {\n"
10018                "  template <class T>\n"
10019                "  int &foo(const std::string &str) const &noexcept {}\n"
10020                "};",
10021                BreakTemplate);
10022 
10023   verifyFormat("struct f {\n"
10024                "  template <class T>\n"
10025                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
10026                "};",
10027                BreakTemplate);
10028 
10029   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
10030   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
10031       FormatStyle::BTDS_Yes;
10032   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
10033 
10034   verifyFormat("struct f {\n"
10035                "  template <class T>\n"
10036                "  int& foo(const std::string& str) & noexcept {}\n"
10037                "};",
10038                AlignLeftBreakTemplate);
10039 
10040   verifyFormat("struct f {\n"
10041                "  template <class T>\n"
10042                "  int& foo(const std::string& str) && noexcept {}\n"
10043                "};",
10044                AlignLeftBreakTemplate);
10045 
10046   verifyFormat("struct f {\n"
10047                "  template <class T>\n"
10048                "  int& foo(const std::string& str) const& noexcept {}\n"
10049                "};",
10050                AlignLeftBreakTemplate);
10051 
10052   verifyFormat("struct f {\n"
10053                "  template <class T>\n"
10054                "  int& foo(const std::string& str) const&& noexcept {}\n"
10055                "};",
10056                AlignLeftBreakTemplate);
10057 
10058   verifyFormat("struct f {\n"
10059                "  template <class T>\n"
10060                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
10061                "};",
10062                AlignLeftBreakTemplate);
10063 
10064   // The `&` in `Type&` should not be confused with a trailing `&` of
10065   // DEPRECATED(reason) member function.
10066   verifyFormat("struct f {\n"
10067                "  template <class T>\n"
10068                "  DEPRECATED(reason)\n"
10069                "  Type &foo(arguments) {}\n"
10070                "};",
10071                BreakTemplate);
10072 
10073   verifyFormat("struct f {\n"
10074                "  template <class T>\n"
10075                "  DEPRECATED(reason)\n"
10076                "  Type& foo(arguments) {}\n"
10077                "};",
10078                AlignLeftBreakTemplate);
10079 
10080   verifyFormat("void (*foopt)(int) = &func;");
10081 
10082   FormatStyle DerivePointerAlignment = getLLVMStyle();
10083   DerivePointerAlignment.DerivePointerAlignment = true;
10084   // There's always a space between the function and its trailing qualifiers.
10085   // This isn't evidence for PAS_Right (or for PAS_Left).
10086   std::string Prefix = "void a() &;\n"
10087                        "void b() &;\n";
10088   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10089   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10090   // Same if the function is an overloaded operator, and with &&.
10091   Prefix = "void operator()() &&;\n"
10092            "void operator()() &&;\n";
10093   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10094   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10095   // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
10096   Prefix = "void a() const &;\n"
10097            "void b() const &;\n";
10098   EXPECT_EQ(Prefix + "int *x;",
10099             format(Prefix + "int* x;", DerivePointerAlignment));
10100 }
10101 
10102 TEST_F(FormatTest, UnderstandsNewAndDelete) {
10103   verifyFormat("void f() {\n"
10104                "  A *a = new A;\n"
10105                "  A *a = new (placement) A;\n"
10106                "  delete a;\n"
10107                "  delete (A *)a;\n"
10108                "}");
10109   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10110                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10111   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10112                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10113                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10114   verifyFormat("delete[] h->p;");
10115   verifyFormat("delete[] (void *)p;");
10116 
10117   verifyFormat("void operator delete(void *foo) ATTRIB;");
10118   verifyFormat("void operator new(void *foo) ATTRIB;");
10119   verifyFormat("void operator delete[](void *foo) ATTRIB;");
10120   verifyFormat("void operator delete(void *ptr) noexcept;");
10121 
10122   EXPECT_EQ("void new(link p);\n"
10123             "void delete(link p);\n",
10124             format("void new (link p);\n"
10125                    "void delete (link p);\n"));
10126 }
10127 
10128 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
10129   verifyFormat("int *f(int *a) {}");
10130   verifyFormat("int main(int argc, char **argv) {}");
10131   verifyFormat("Test::Test(int b) : a(b * b) {}");
10132   verifyIndependentOfContext("f(a, *a);");
10133   verifyFormat("void g() { f(*a); }");
10134   verifyIndependentOfContext("int a = b * 10;");
10135   verifyIndependentOfContext("int a = 10 * b;");
10136   verifyIndependentOfContext("int a = b * c;");
10137   verifyIndependentOfContext("int a += b * c;");
10138   verifyIndependentOfContext("int a -= b * c;");
10139   verifyIndependentOfContext("int a *= b * c;");
10140   verifyIndependentOfContext("int a /= b * c;");
10141   verifyIndependentOfContext("int a = *b;");
10142   verifyIndependentOfContext("int a = *b * c;");
10143   verifyIndependentOfContext("int a = b * *c;");
10144   verifyIndependentOfContext("int a = b * (10);");
10145   verifyIndependentOfContext("S << b * (10);");
10146   verifyIndependentOfContext("return 10 * b;");
10147   verifyIndependentOfContext("return *b * *c;");
10148   verifyIndependentOfContext("return a & ~b;");
10149   verifyIndependentOfContext("f(b ? *c : *d);");
10150   verifyIndependentOfContext("int a = b ? *c : *d;");
10151   verifyIndependentOfContext("*b = a;");
10152   verifyIndependentOfContext("a * ~b;");
10153   verifyIndependentOfContext("a * !b;");
10154   verifyIndependentOfContext("a * +b;");
10155   verifyIndependentOfContext("a * -b;");
10156   verifyIndependentOfContext("a * ++b;");
10157   verifyIndependentOfContext("a * --b;");
10158   verifyIndependentOfContext("a[4] * b;");
10159   verifyIndependentOfContext("a[a * a] = 1;");
10160   verifyIndependentOfContext("f() * b;");
10161   verifyIndependentOfContext("a * [self dostuff];");
10162   verifyIndependentOfContext("int x = a * (a + b);");
10163   verifyIndependentOfContext("(a *)(a + b);");
10164   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
10165   verifyIndependentOfContext("int *pa = (int *)&a;");
10166   verifyIndependentOfContext("return sizeof(int **);");
10167   verifyIndependentOfContext("return sizeof(int ******);");
10168   verifyIndependentOfContext("return (int **&)a;");
10169   verifyIndependentOfContext("f((*PointerToArray)[10]);");
10170   verifyFormat("void f(Type (*parameter)[10]) {}");
10171   verifyFormat("void f(Type (&parameter)[10]) {}");
10172   verifyGoogleFormat("return sizeof(int**);");
10173   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
10174   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
10175   verifyFormat("auto a = [](int **&, int ***) {};");
10176   verifyFormat("auto PointerBinding = [](const char *S) {};");
10177   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
10178   verifyFormat("[](const decltype(*a) &value) {}");
10179   verifyFormat("[](const typeof(*a) &value) {}");
10180   verifyFormat("[](const _Atomic(a *) &value) {}");
10181   verifyFormat("[](const __underlying_type(a) &value) {}");
10182   verifyFormat("decltype(a * b) F();");
10183   verifyFormat("typeof(a * b) F();");
10184   verifyFormat("#define MACRO() [](A *a) { return 1; }");
10185   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
10186   verifyIndependentOfContext("typedef void (*f)(int *a);");
10187   verifyIndependentOfContext("int i{a * b};");
10188   verifyIndependentOfContext("aaa && aaa->f();");
10189   verifyIndependentOfContext("int x = ~*p;");
10190   verifyFormat("Constructor() : a(a), area(width * height) {}");
10191   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
10192   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
10193   verifyFormat("void f() { f(a, c * d); }");
10194   verifyFormat("void f() { f(new a(), c * d); }");
10195   verifyFormat("void f(const MyOverride &override);");
10196   verifyFormat("void f(const MyFinal &final);");
10197   verifyIndependentOfContext("bool a = f() && override.f();");
10198   verifyIndependentOfContext("bool a = f() && final.f();");
10199 
10200   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
10201 
10202   verifyIndependentOfContext("A<int *> a;");
10203   verifyIndependentOfContext("A<int **> a;");
10204   verifyIndependentOfContext("A<int *, int *> a;");
10205   verifyIndependentOfContext("A<int *[]> a;");
10206   verifyIndependentOfContext(
10207       "const char *const p = reinterpret_cast<const char *const>(q);");
10208   verifyIndependentOfContext("A<int **, int **> a;");
10209   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
10210   verifyFormat("for (char **a = b; *a; ++a) {\n}");
10211   verifyFormat("for (; a && b;) {\n}");
10212   verifyFormat("bool foo = true && [] { return false; }();");
10213 
10214   verifyFormat(
10215       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10216       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10217 
10218   verifyGoogleFormat("int const* a = &b;");
10219   verifyGoogleFormat("**outparam = 1;");
10220   verifyGoogleFormat("*outparam = a * b;");
10221   verifyGoogleFormat("int main(int argc, char** argv) {}");
10222   verifyGoogleFormat("A<int*> a;");
10223   verifyGoogleFormat("A<int**> a;");
10224   verifyGoogleFormat("A<int*, int*> a;");
10225   verifyGoogleFormat("A<int**, int**> a;");
10226   verifyGoogleFormat("f(b ? *c : *d);");
10227   verifyGoogleFormat("int a = b ? *c : *d;");
10228   verifyGoogleFormat("Type* t = **x;");
10229   verifyGoogleFormat("Type* t = *++*x;");
10230   verifyGoogleFormat("*++*x;");
10231   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
10232   verifyGoogleFormat("Type* t = x++ * y;");
10233   verifyGoogleFormat(
10234       "const char* const p = reinterpret_cast<const char* const>(q);");
10235   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
10236   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
10237   verifyGoogleFormat("template <typename T>\n"
10238                      "void f(int i = 0, SomeType** temps = NULL);");
10239 
10240   FormatStyle Left = getLLVMStyle();
10241   Left.PointerAlignment = FormatStyle::PAS_Left;
10242   verifyFormat("x = *a(x) = *a(y);", Left);
10243   verifyFormat("for (;; *a = b) {\n}", Left);
10244   verifyFormat("return *this += 1;", Left);
10245   verifyFormat("throw *x;", Left);
10246   verifyFormat("delete *x;", Left);
10247   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
10248   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
10249   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
10250   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
10251   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
10252   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
10253   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
10254   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
10255   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
10256 
10257   verifyIndependentOfContext("a = *(x + y);");
10258   verifyIndependentOfContext("a = &(x + y);");
10259   verifyIndependentOfContext("*(x + y).call();");
10260   verifyIndependentOfContext("&(x + y)->call();");
10261   verifyFormat("void f() { &(*I).first; }");
10262 
10263   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
10264   verifyFormat("f(* /* confusing comment */ foo);");
10265   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
10266   verifyFormat("void foo(int * // this is the first paramters\n"
10267                "         ,\n"
10268                "         int second);");
10269   verifyFormat("double term = a * // first\n"
10270                "              b;");
10271   verifyFormat(
10272       "int *MyValues = {\n"
10273       "    *A, // Operator detection might be confused by the '{'\n"
10274       "    *BB // Operator detection might be confused by previous comment\n"
10275       "};");
10276 
10277   verifyIndependentOfContext("if (int *a = &b)");
10278   verifyIndependentOfContext("if (int &a = *b)");
10279   verifyIndependentOfContext("if (a & b[i])");
10280   verifyIndependentOfContext("if constexpr (a & b[i])");
10281   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
10282   verifyIndependentOfContext("if (a * (b * c))");
10283   verifyIndependentOfContext("if constexpr (a * (b * c))");
10284   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
10285   verifyIndependentOfContext("if (a::b::c::d & b[i])");
10286   verifyIndependentOfContext("if (*b[i])");
10287   verifyIndependentOfContext("if (int *a = (&b))");
10288   verifyIndependentOfContext("while (int *a = &b)");
10289   verifyIndependentOfContext("while (a * (b * c))");
10290   verifyIndependentOfContext("size = sizeof *a;");
10291   verifyIndependentOfContext("if (a && (b = c))");
10292   verifyFormat("void f() {\n"
10293                "  for (const int &v : Values) {\n"
10294                "  }\n"
10295                "}");
10296   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
10297   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
10298   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
10299 
10300   verifyFormat("#define A (!a * b)");
10301   verifyFormat("#define MACRO     \\\n"
10302                "  int *i = a * b; \\\n"
10303                "  void f(a *b);",
10304                getLLVMStyleWithColumns(19));
10305 
10306   verifyIndependentOfContext("A = new SomeType *[Length];");
10307   verifyIndependentOfContext("A = new SomeType *[Length]();");
10308   verifyIndependentOfContext("T **t = new T *;");
10309   verifyIndependentOfContext("T **t = new T *();");
10310   verifyGoogleFormat("A = new SomeType*[Length]();");
10311   verifyGoogleFormat("A = new SomeType*[Length];");
10312   verifyGoogleFormat("T** t = new T*;");
10313   verifyGoogleFormat("T** t = new T*();");
10314 
10315   verifyFormat("STATIC_ASSERT((a & b) == 0);");
10316   verifyFormat("STATIC_ASSERT(0 == (a & b));");
10317   verifyFormat("template <bool a, bool b> "
10318                "typename t::if<x && y>::type f() {}");
10319   verifyFormat("template <int *y> f() {}");
10320   verifyFormat("vector<int *> v;");
10321   verifyFormat("vector<int *const> v;");
10322   verifyFormat("vector<int *const **const *> v;");
10323   verifyFormat("vector<int *volatile> v;");
10324   verifyFormat("vector<a *_Nonnull> v;");
10325   verifyFormat("vector<a *_Nullable> v;");
10326   verifyFormat("vector<a *_Null_unspecified> v;");
10327   verifyFormat("vector<a *__ptr32> v;");
10328   verifyFormat("vector<a *__ptr64> v;");
10329   verifyFormat("vector<a *__capability> v;");
10330   FormatStyle TypeMacros = getLLVMStyle();
10331   TypeMacros.TypenameMacros = {"LIST"};
10332   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
10333   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
10334   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
10335   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
10336   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
10337 
10338   FormatStyle CustomQualifier = getLLVMStyle();
10339   // Add identifiers that should not be parsed as a qualifier by default.
10340   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10341   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
10342   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
10343   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
10344   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
10345   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
10346   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
10347   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
10348   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
10349   verifyFormat("vector<a * _NotAQualifier> v;");
10350   verifyFormat("vector<a * __not_a_qualifier> v;");
10351   verifyFormat("vector<a * b> v;");
10352   verifyFormat("foo<b && false>();");
10353   verifyFormat("foo<b & 1>();");
10354   verifyFormat("foo<b & (1)>();");
10355   verifyFormat("foo<b & (~0)>();");
10356   verifyFormat("foo<b & (true)>();");
10357   verifyFormat("foo<b & ((1))>();");
10358   verifyFormat("foo<b & (/*comment*/ 1)>();");
10359   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
10360   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
10361   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
10362   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
10363   verifyFormat(
10364       "template <class T, class = typename std::enable_if<\n"
10365       "                       std::is_integral<T>::value &&\n"
10366       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
10367       "void F();",
10368       getLLVMStyleWithColumns(70));
10369   verifyFormat("template <class T,\n"
10370                "          class = typename std::enable_if<\n"
10371                "              std::is_integral<T>::value &&\n"
10372                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
10373                "          class U>\n"
10374                "void F();",
10375                getLLVMStyleWithColumns(70));
10376   verifyFormat(
10377       "template <class T,\n"
10378       "          class = typename ::std::enable_if<\n"
10379       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
10380       "void F();",
10381       getGoogleStyleWithColumns(68));
10382 
10383   verifyIndependentOfContext("MACRO(int *i);");
10384   verifyIndependentOfContext("MACRO(auto *a);");
10385   verifyIndependentOfContext("MACRO(const A *a);");
10386   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10387   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10388   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10389   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10390   verifyIndependentOfContext("MACRO(A *const a);");
10391   verifyIndependentOfContext("MACRO(A *restrict a);");
10392   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10393   verifyIndependentOfContext("MACRO(A *__restrict a);");
10394   verifyIndependentOfContext("MACRO(A *volatile a);");
10395   verifyIndependentOfContext("MACRO(A *__volatile a);");
10396   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10397   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10398   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10399   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10400   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10401   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10402   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10403   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10404   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10405   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10406   verifyIndependentOfContext("MACRO(A *__capability);");
10407   verifyIndependentOfContext("MACRO(A &__capability);");
10408   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10409   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10410   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10411   // a type declaration:
10412   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10413   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10414   // Also check that TypenameMacros prevents parsing it as multiplication:
10415   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10416   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10417 
10418   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10419   verifyFormat("void f() { f(float{1}, a * a); }");
10420   verifyFormat("void f() { f(float(1), a * a); }");
10421 
10422   verifyFormat("f((void (*)(int))g);");
10423   verifyFormat("f((void (&)(int))g);");
10424   verifyFormat("f((void (^)(int))g);");
10425 
10426   // FIXME: Is there a way to make this work?
10427   // verifyIndependentOfContext("MACRO(A *a);");
10428   verifyFormat("MACRO(A &B);");
10429   verifyFormat("MACRO(A *B);");
10430   verifyFormat("void f() { MACRO(A * B); }");
10431   verifyFormat("void f() { MACRO(A & B); }");
10432 
10433   // This lambda was mis-formatted after D88956 (treating it as a binop):
10434   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10435   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10436   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10437   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10438 
10439   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10440   verifyFormat("return options != nullptr && operator==(*options);");
10441 
10442   EXPECT_EQ("#define OP(x)                                    \\\n"
10443             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10444             "    return s << a.DebugString();                 \\\n"
10445             "  }",
10446             format("#define OP(x) \\\n"
10447                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10448                    "    return s << a.DebugString(); \\\n"
10449                    "  }",
10450                    getLLVMStyleWithColumns(50)));
10451 
10452   // FIXME: We cannot handle this case yet; we might be able to figure out that
10453   // foo<x> d > v; doesn't make sense.
10454   verifyFormat("foo<a<b && c> d> v;");
10455 
10456   FormatStyle PointerMiddle = getLLVMStyle();
10457   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10458   verifyFormat("delete *x;", PointerMiddle);
10459   verifyFormat("int * x;", PointerMiddle);
10460   verifyFormat("int *[] x;", PointerMiddle);
10461   verifyFormat("template <int * y> f() {}", PointerMiddle);
10462   verifyFormat("int * f(int * a) {}", PointerMiddle);
10463   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10464   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10465   verifyFormat("A<int *> a;", PointerMiddle);
10466   verifyFormat("A<int **> a;", PointerMiddle);
10467   verifyFormat("A<int *, int *> a;", PointerMiddle);
10468   verifyFormat("A<int *[]> a;", PointerMiddle);
10469   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10470   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10471   verifyFormat("T ** t = new T *;", PointerMiddle);
10472 
10473   // Member function reference qualifiers aren't binary operators.
10474   verifyFormat("string // break\n"
10475                "operator()() & {}");
10476   verifyFormat("string // break\n"
10477                "operator()() && {}");
10478   verifyGoogleFormat("template <typename T>\n"
10479                      "auto x() & -> int {}");
10480 
10481   // Should be binary operators when used as an argument expression (overloaded
10482   // operator invoked as a member function).
10483   verifyFormat("void f() { a.operator()(a * a); }");
10484   verifyFormat("void f() { a->operator()(a & a); }");
10485   verifyFormat("void f() { a.operator()(*a & *a); }");
10486   verifyFormat("void f() { a->operator()(*a * *a); }");
10487 
10488   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10489   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10490 }
10491 
10492 TEST_F(FormatTest, UnderstandsAttributes) {
10493   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10494   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10495                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10496   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10497   FormatStyle AfterType = getLLVMStyle();
10498   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10499   verifyFormat("__attribute__((nodebug)) void\n"
10500                "foo() {}\n",
10501                AfterType);
10502   verifyFormat("__unused void\n"
10503                "foo() {}",
10504                AfterType);
10505 
10506   FormatStyle CustomAttrs = getLLVMStyle();
10507   CustomAttrs.AttributeMacros.push_back("__unused");
10508   CustomAttrs.AttributeMacros.push_back("__attr1");
10509   CustomAttrs.AttributeMacros.push_back("__attr2");
10510   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10511   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10512   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10513   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10514   // Check that it is parsed as a multiplication without AttributeMacros and
10515   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10516   verifyFormat("vector<SomeType * __attr1> v;");
10517   verifyFormat("vector<SomeType __attr1 *> v;");
10518   verifyFormat("vector<SomeType __attr1 *const> v;");
10519   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10520   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10521   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10522   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10523   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10524   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10525   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10526   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10527 
10528   // Check that these are not parsed as function declarations:
10529   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10530   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10531   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10532   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10533   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10534   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10535   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10536   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10537   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10538   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10539 }
10540 
10541 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10542   // Check that qualifiers on pointers don't break parsing of casts.
10543   verifyFormat("x = (foo *const)*v;");
10544   verifyFormat("x = (foo *volatile)*v;");
10545   verifyFormat("x = (foo *restrict)*v;");
10546   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10547   verifyFormat("x = (foo *_Nonnull)*v;");
10548   verifyFormat("x = (foo *_Nullable)*v;");
10549   verifyFormat("x = (foo *_Null_unspecified)*v;");
10550   verifyFormat("x = (foo *_Nonnull)*v;");
10551   verifyFormat("x = (foo *[[clang::attr]])*v;");
10552   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10553   verifyFormat("x = (foo *__ptr32)*v;");
10554   verifyFormat("x = (foo *__ptr64)*v;");
10555   verifyFormat("x = (foo *__capability)*v;");
10556 
10557   // Check that we handle multiple trailing qualifiers and skip them all to
10558   // determine that the expression is a cast to a pointer type.
10559   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10560   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10561   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10562   StringRef AllQualifiers =
10563       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10564       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10565   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10566   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10567 
10568   // Also check that address-of is not parsed as a binary bitwise-and:
10569   verifyFormat("x = (foo *const)&v;");
10570   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10571   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10572 
10573   // Check custom qualifiers:
10574   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10575   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10576   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10577   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10578   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10579                CustomQualifier);
10580   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10581                CustomQualifier);
10582 
10583   // Check that unknown identifiers result in binary operator parsing:
10584   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10585   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10586 }
10587 
10588 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10589   verifyFormat("SomeType s [[unused]] (InitValue);");
10590   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10591   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10592   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10593   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10594   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10595                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10596   verifyFormat("[[nodiscard]] bool f() { return false; }");
10597   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10598   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10599   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10600   verifyFormat("[[nodiscard]] ::qualified_type f();");
10601 
10602   // Make sure we do not mistake attributes for array subscripts.
10603   verifyFormat("int a() {}\n"
10604                "[[unused]] int b() {}\n");
10605   verifyFormat("NSArray *arr;\n"
10606                "arr[[Foo() bar]];");
10607 
10608   // On the other hand, we still need to correctly find array subscripts.
10609   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10610 
10611   // Make sure that we do not mistake Objective-C method inside array literals
10612   // as attributes, even if those method names are also keywords.
10613   verifyFormat("@[ [foo bar] ];");
10614   verifyFormat("@[ [NSArray class] ];");
10615   verifyFormat("@[ [foo enum] ];");
10616 
10617   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10618 
10619   // Make sure we do not parse attributes as lambda introducers.
10620   FormatStyle MultiLineFunctions = getLLVMStyle();
10621   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10622   verifyFormat("[[unused]] int b() {\n"
10623                "  return 42;\n"
10624                "}\n",
10625                MultiLineFunctions);
10626 }
10627 
10628 TEST_F(FormatTest, AttributeClass) {
10629   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10630   verifyFormat("class S {\n"
10631                "  S(S&&) = default;\n"
10632                "};",
10633                Style);
10634   verifyFormat("class [[nodiscard]] S {\n"
10635                "  S(S&&) = default;\n"
10636                "};",
10637                Style);
10638   verifyFormat("class __attribute((maybeunused)) S {\n"
10639                "  S(S&&) = default;\n"
10640                "};",
10641                Style);
10642   verifyFormat("struct S {\n"
10643                "  S(S&&) = default;\n"
10644                "};",
10645                Style);
10646   verifyFormat("struct [[nodiscard]] S {\n"
10647                "  S(S&&) = default;\n"
10648                "};",
10649                Style);
10650 }
10651 
10652 TEST_F(FormatTest, AttributesAfterMacro) {
10653   FormatStyle Style = getLLVMStyle();
10654   verifyFormat("MACRO;\n"
10655                "__attribute__((maybe_unused)) int foo() {\n"
10656                "  //...\n"
10657                "}");
10658 
10659   verifyFormat("MACRO;\n"
10660                "[[nodiscard]] int foo() {\n"
10661                "  //...\n"
10662                "}");
10663 
10664   EXPECT_EQ("MACRO\n\n"
10665             "__attribute__((maybe_unused)) int foo() {\n"
10666             "  //...\n"
10667             "}",
10668             format("MACRO\n\n"
10669                    "__attribute__((maybe_unused)) int foo() {\n"
10670                    "  //...\n"
10671                    "}"));
10672 
10673   EXPECT_EQ("MACRO\n\n"
10674             "[[nodiscard]] int foo() {\n"
10675             "  //...\n"
10676             "}",
10677             format("MACRO\n\n"
10678                    "[[nodiscard]] int foo() {\n"
10679                    "  //...\n"
10680                    "}"));
10681 }
10682 
10683 TEST_F(FormatTest, AttributePenaltyBreaking) {
10684   FormatStyle Style = getLLVMStyle();
10685   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10686                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10687                Style);
10688   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10689                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10690                Style);
10691   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10692                "shared_ptr<ALongTypeName> &C d) {\n}",
10693                Style);
10694 }
10695 
10696 TEST_F(FormatTest, UnderstandsEllipsis) {
10697   FormatStyle Style = getLLVMStyle();
10698   verifyFormat("int printf(const char *fmt, ...);");
10699   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10700   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10701 
10702   verifyFormat("template <int *...PP> a;", Style);
10703 
10704   Style.PointerAlignment = FormatStyle::PAS_Left;
10705   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10706 
10707   verifyFormat("template <int*... PP> a;", Style);
10708 
10709   Style.PointerAlignment = FormatStyle::PAS_Middle;
10710   verifyFormat("template <int *... PP> a;", Style);
10711 }
10712 
10713 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10714   EXPECT_EQ("int *a;\n"
10715             "int *a;\n"
10716             "int *a;",
10717             format("int *a;\n"
10718                    "int* a;\n"
10719                    "int *a;",
10720                    getGoogleStyle()));
10721   EXPECT_EQ("int* a;\n"
10722             "int* a;\n"
10723             "int* a;",
10724             format("int* a;\n"
10725                    "int* a;\n"
10726                    "int *a;",
10727                    getGoogleStyle()));
10728   EXPECT_EQ("int *a;\n"
10729             "int *a;\n"
10730             "int *a;",
10731             format("int *a;\n"
10732                    "int * a;\n"
10733                    "int *  a;",
10734                    getGoogleStyle()));
10735   EXPECT_EQ("auto x = [] {\n"
10736             "  int *a;\n"
10737             "  int *a;\n"
10738             "  int *a;\n"
10739             "};",
10740             format("auto x=[]{int *a;\n"
10741                    "int * a;\n"
10742                    "int *  a;};",
10743                    getGoogleStyle()));
10744 }
10745 
10746 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10747   verifyFormat("int f(int &&a) {}");
10748   verifyFormat("int f(int a, char &&b) {}");
10749   verifyFormat("void f() { int &&a = b; }");
10750   verifyGoogleFormat("int f(int a, char&& b) {}");
10751   verifyGoogleFormat("void f() { int&& a = b; }");
10752 
10753   verifyIndependentOfContext("A<int &&> a;");
10754   verifyIndependentOfContext("A<int &&, int &&> a;");
10755   verifyGoogleFormat("A<int&&> a;");
10756   verifyGoogleFormat("A<int&&, int&&> a;");
10757 
10758   // Not rvalue references:
10759   verifyFormat("template <bool B, bool C> class A {\n"
10760                "  static_assert(B && C, \"Something is wrong\");\n"
10761                "};");
10762   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10763   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10764   verifyFormat("#define A(a, b) (a && b)");
10765 }
10766 
10767 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10768   verifyFormat("void f() {\n"
10769                "  x[aaaaaaaaa -\n"
10770                "    b] = 23;\n"
10771                "}",
10772                getLLVMStyleWithColumns(15));
10773 }
10774 
10775 TEST_F(FormatTest, FormatsCasts) {
10776   verifyFormat("Type *A = static_cast<Type *>(P);");
10777   verifyFormat("static_cast<Type *>(P);");
10778   verifyFormat("static_cast<Type &>(Fun)(Args);");
10779   verifyFormat("static_cast<Type &>(*Fun)(Args);");
10780   verifyFormat("if (static_cast<int>(A) + B >= 0)\n  ;");
10781   // Check that static_cast<...>(...) does not require the next token to be on
10782   // the same line.
10783   verifyFormat("some_loooong_output << something_something__ << "
10784                "static_cast<const void *>(R)\n"
10785                "                    << something;");
10786   verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
10787   verifyFormat("const_cast<Type &>(*Fun)(Args);");
10788   verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
10789   verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
10790   verifyFormat("Type *A = (Type *)P;");
10791   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10792   verifyFormat("int a = (int)(2.0f);");
10793   verifyFormat("int a = (int)2.0f;");
10794   verifyFormat("x[(int32)y];");
10795   verifyFormat("x = (int32)y;");
10796   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10797   verifyFormat("int a = (int)*b;");
10798   verifyFormat("int a = (int)2.0f;");
10799   verifyFormat("int a = (int)~0;");
10800   verifyFormat("int a = (int)++a;");
10801   verifyFormat("int a = (int)sizeof(int);");
10802   verifyFormat("int a = (int)+2;");
10803   verifyFormat("my_int a = (my_int)2.0f;");
10804   verifyFormat("my_int a = (my_int)sizeof(int);");
10805   verifyFormat("return (my_int)aaa;");
10806   verifyFormat("#define x ((int)-1)");
10807   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10808   verifyFormat("#define p(q) ((int *)&q)");
10809   verifyFormat("fn(a)(b) + 1;");
10810 
10811   verifyFormat("void f() { my_int a = (my_int)*b; }");
10812   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10813   verifyFormat("my_int a = (my_int)~0;");
10814   verifyFormat("my_int a = (my_int)++a;");
10815   verifyFormat("my_int a = (my_int)-2;");
10816   verifyFormat("my_int a = (my_int)1;");
10817   verifyFormat("my_int a = (my_int *)1;");
10818   verifyFormat("my_int a = (const my_int)-1;");
10819   verifyFormat("my_int a = (const my_int *)-1;");
10820   verifyFormat("my_int a = (my_int)(my_int)-1;");
10821   verifyFormat("my_int a = (ns::my_int)-2;");
10822   verifyFormat("case (my_int)ONE:");
10823   verifyFormat("auto x = (X)this;");
10824   // Casts in Obj-C style calls used to not be recognized as such.
10825   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10826 
10827   // FIXME: single value wrapped with paren will be treated as cast.
10828   verifyFormat("void f(int i = (kValue)*kMask) {}");
10829 
10830   verifyFormat("{ (void)F; }");
10831 
10832   // Don't break after a cast's
10833   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10834                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10835                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10836 
10837   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10838   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10839   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10840   verifyFormat("bool *y = (bool *)(void *)(x);");
10841   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10842   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10843   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10844   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10845 
10846   // These are not casts.
10847   verifyFormat("void f(int *) {}");
10848   verifyFormat("f(foo)->b;");
10849   verifyFormat("f(foo).b;");
10850   verifyFormat("f(foo)(b);");
10851   verifyFormat("f(foo)[b];");
10852   verifyFormat("[](foo) { return 4; }(bar);");
10853   verifyFormat("(*funptr)(foo)[4];");
10854   verifyFormat("funptrs[4](foo)[4];");
10855   verifyFormat("void f(int *);");
10856   verifyFormat("void f(int *) = 0;");
10857   verifyFormat("void f(SmallVector<int>) {}");
10858   verifyFormat("void f(SmallVector<int>);");
10859   verifyFormat("void f(SmallVector<int>) = 0;");
10860   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10861   verifyFormat("int a = sizeof(int) * b;");
10862   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10863   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10864   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10865   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10866 
10867   // These are not casts, but at some point were confused with casts.
10868   verifyFormat("virtual void foo(int *) override;");
10869   verifyFormat("virtual void foo(char &) const;");
10870   verifyFormat("virtual void foo(int *a, char *) const;");
10871   verifyFormat("int a = sizeof(int *) + b;");
10872   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10873   verifyFormat("bool b = f(g<int>) && c;");
10874   verifyFormat("typedef void (*f)(int i) func;");
10875   verifyFormat("void operator++(int) noexcept;");
10876   verifyFormat("void operator++(int &) noexcept;");
10877   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10878                "&) noexcept;");
10879   verifyFormat(
10880       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10881   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10882   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10883   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10884   verifyFormat("void operator delete(foo &) noexcept;");
10885   verifyFormat("void operator delete(foo) noexcept;");
10886   verifyFormat("void operator delete(int) noexcept;");
10887   verifyFormat("void operator delete(int &) noexcept;");
10888   verifyFormat("void operator delete(int &) volatile noexcept;");
10889   verifyFormat("void operator delete(int &) const");
10890   verifyFormat("void operator delete(int &) = default");
10891   verifyFormat("void operator delete(int &) = delete");
10892   verifyFormat("void operator delete(int &) [[noreturn]]");
10893   verifyFormat("void operator delete(int &) throw();");
10894   verifyFormat("void operator delete(int &) throw(int);");
10895   verifyFormat("auto operator delete(int &) -> int;");
10896   verifyFormat("auto operator delete(int &) override");
10897   verifyFormat("auto operator delete(int &) final");
10898 
10899   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10900                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10901   // FIXME: The indentation here is not ideal.
10902   verifyFormat(
10903       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10904       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10905       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10906 }
10907 
10908 TEST_F(FormatTest, FormatsFunctionTypes) {
10909   verifyFormat("A<bool()> a;");
10910   verifyFormat("A<SomeType()> a;");
10911   verifyFormat("A<void (*)(int, std::string)> a;");
10912   verifyFormat("A<void *(int)>;");
10913   verifyFormat("void *(*a)(int *, SomeType *);");
10914   verifyFormat("int (*func)(void *);");
10915   verifyFormat("void f() { int (*func)(void *); }");
10916   verifyFormat("template <class CallbackClass>\n"
10917                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10918 
10919   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10920   verifyGoogleFormat("void* (*a)(int);");
10921   verifyGoogleFormat(
10922       "template <class CallbackClass>\n"
10923       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10924 
10925   // Other constructs can look somewhat like function types:
10926   verifyFormat("A<sizeof(*x)> a;");
10927   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10928   verifyFormat("some_var = function(*some_pointer_var)[0];");
10929   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10930   verifyFormat("int x = f(&h)();");
10931   verifyFormat("returnsFunction(&param1, &param2)(param);");
10932   verifyFormat("std::function<\n"
10933                "    LooooooooooongTemplatedType<\n"
10934                "        SomeType>*(\n"
10935                "        LooooooooooooooooongType type)>\n"
10936                "    function;",
10937                getGoogleStyleWithColumns(40));
10938 }
10939 
10940 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10941   verifyFormat("A (*foo_)[6];");
10942   verifyFormat("vector<int> (*foo_)[6];");
10943 }
10944 
10945 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10946   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10947                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10948   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10949                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10950   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10951                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10952 
10953   // Different ways of ()-initializiation.
10954   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10955                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10956   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10957                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10958   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10959                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10960   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10961                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10962 
10963   // Lambdas should not confuse the variable declaration heuristic.
10964   verifyFormat("LooooooooooooooooongType\n"
10965                "    variable(nullptr, [](A *a) {});",
10966                getLLVMStyleWithColumns(40));
10967 }
10968 
10969 TEST_F(FormatTest, BreaksLongDeclarations) {
10970   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10971                "    AnotherNameForTheLongType;");
10972   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10973                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10974   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10975                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10976   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10977                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10978   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10979                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10980   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10981                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10982   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10983                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10984   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10985                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10986   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10987                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10988   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10989                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10990   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10991                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10992   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10993                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10994   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10995                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10996   FormatStyle Indented = getLLVMStyle();
10997   Indented.IndentWrappedFunctionNames = true;
10998   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10999                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
11000                Indented);
11001   verifyFormat(
11002       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11003       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11004       Indented);
11005   verifyFormat(
11006       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
11007       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11008       Indented);
11009   verifyFormat(
11010       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
11011       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11012       Indented);
11013 
11014   // FIXME: Without the comment, this breaks after "(".
11015   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
11016                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
11017                getGoogleStyle());
11018 
11019   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
11020                "                  int LoooooooooooooooooooongParam2) {}");
11021   verifyFormat(
11022       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
11023       "                                   SourceLocation L, IdentifierIn *II,\n"
11024       "                                   Type *T) {}");
11025   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
11026                "ReallyReaaallyLongFunctionName(\n"
11027                "    const std::string &SomeParameter,\n"
11028                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11029                "        &ReallyReallyLongParameterName,\n"
11030                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11031                "        &AnotherLongParameterName) {}");
11032   verifyFormat("template <typename A>\n"
11033                "SomeLoooooooooooooooooooooongType<\n"
11034                "    typename some_namespace::SomeOtherType<A>::Type>\n"
11035                "Function() {}");
11036 
11037   verifyGoogleFormat(
11038       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
11039       "    aaaaaaaaaaaaaaaaaaaaaaa;");
11040   verifyGoogleFormat(
11041       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
11042       "                                   SourceLocation L) {}");
11043   verifyGoogleFormat(
11044       "some_namespace::LongReturnType\n"
11045       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
11046       "    int first_long_parameter, int second_parameter) {}");
11047 
11048   verifyGoogleFormat("template <typename T>\n"
11049                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11050                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
11051   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11052                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
11053 
11054   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
11055                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11056                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11057   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11058                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11059                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
11060   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11061                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
11062                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
11063                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11064 
11065   verifyFormat("template <typename T> // Templates on own line.\n"
11066                "static int            // Some comment.\n"
11067                "MyFunction(int a);",
11068                getLLVMStyle());
11069 }
11070 
11071 TEST_F(FormatTest, FormatsAccessModifiers) {
11072   FormatStyle Style = getLLVMStyle();
11073   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
11074             FormatStyle::ELBAMS_LogicalBlock);
11075   verifyFormat("struct foo {\n"
11076                "private:\n"
11077                "  void f() {}\n"
11078                "\n"
11079                "private:\n"
11080                "  int i;\n"
11081                "\n"
11082                "protected:\n"
11083                "  int j;\n"
11084                "};\n",
11085                Style);
11086   verifyFormat("struct foo {\n"
11087                "private:\n"
11088                "  void f() {}\n"
11089                "\n"
11090                "private:\n"
11091                "  int i;\n"
11092                "\n"
11093                "protected:\n"
11094                "  int j;\n"
11095                "};\n",
11096                "struct foo {\n"
11097                "private:\n"
11098                "  void f() {}\n"
11099                "private:\n"
11100                "  int i;\n"
11101                "protected:\n"
11102                "  int j;\n"
11103                "};\n",
11104                Style);
11105   verifyFormat("struct foo { /* comment */\n"
11106                "private:\n"
11107                "  int i;\n"
11108                "  // comment\n"
11109                "private:\n"
11110                "  int j;\n"
11111                "};\n",
11112                Style);
11113   verifyFormat("struct foo {\n"
11114                "#ifdef FOO\n"
11115                "#endif\n"
11116                "private:\n"
11117                "  int i;\n"
11118                "#ifdef FOO\n"
11119                "private:\n"
11120                "#endif\n"
11121                "  int j;\n"
11122                "};\n",
11123                Style);
11124   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11125   verifyFormat("struct foo {\n"
11126                "private:\n"
11127                "  void f() {}\n"
11128                "private:\n"
11129                "  int i;\n"
11130                "protected:\n"
11131                "  int j;\n"
11132                "};\n",
11133                Style);
11134   verifyFormat("struct foo {\n"
11135                "private:\n"
11136                "  void f() {}\n"
11137                "private:\n"
11138                "  int i;\n"
11139                "protected:\n"
11140                "  int j;\n"
11141                "};\n",
11142                "struct foo {\n"
11143                "\n"
11144                "private:\n"
11145                "  void f() {}\n"
11146                "\n"
11147                "private:\n"
11148                "  int i;\n"
11149                "\n"
11150                "protected:\n"
11151                "  int j;\n"
11152                "};\n",
11153                Style);
11154   verifyFormat("struct foo { /* comment */\n"
11155                "private:\n"
11156                "  int i;\n"
11157                "  // comment\n"
11158                "private:\n"
11159                "  int j;\n"
11160                "};\n",
11161                "struct foo { /* comment */\n"
11162                "\n"
11163                "private:\n"
11164                "  int i;\n"
11165                "  // comment\n"
11166                "\n"
11167                "private:\n"
11168                "  int j;\n"
11169                "};\n",
11170                Style);
11171   verifyFormat("struct foo {\n"
11172                "#ifdef FOO\n"
11173                "#endif\n"
11174                "private:\n"
11175                "  int i;\n"
11176                "#ifdef FOO\n"
11177                "private:\n"
11178                "#endif\n"
11179                "  int j;\n"
11180                "};\n",
11181                "struct foo {\n"
11182                "#ifdef FOO\n"
11183                "#endif\n"
11184                "\n"
11185                "private:\n"
11186                "  int i;\n"
11187                "#ifdef FOO\n"
11188                "\n"
11189                "private:\n"
11190                "#endif\n"
11191                "  int j;\n"
11192                "};\n",
11193                Style);
11194   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11195   verifyFormat("struct foo {\n"
11196                "private:\n"
11197                "  void f() {}\n"
11198                "\n"
11199                "private:\n"
11200                "  int i;\n"
11201                "\n"
11202                "protected:\n"
11203                "  int j;\n"
11204                "};\n",
11205                Style);
11206   verifyFormat("struct foo {\n"
11207                "private:\n"
11208                "  void f() {}\n"
11209                "\n"
11210                "private:\n"
11211                "  int i;\n"
11212                "\n"
11213                "protected:\n"
11214                "  int j;\n"
11215                "};\n",
11216                "struct foo {\n"
11217                "private:\n"
11218                "  void f() {}\n"
11219                "private:\n"
11220                "  int i;\n"
11221                "protected:\n"
11222                "  int j;\n"
11223                "};\n",
11224                Style);
11225   verifyFormat("struct foo { /* comment */\n"
11226                "private:\n"
11227                "  int i;\n"
11228                "  // comment\n"
11229                "\n"
11230                "private:\n"
11231                "  int j;\n"
11232                "};\n",
11233                "struct foo { /* comment */\n"
11234                "private:\n"
11235                "  int i;\n"
11236                "  // comment\n"
11237                "\n"
11238                "private:\n"
11239                "  int j;\n"
11240                "};\n",
11241                Style);
11242   verifyFormat("struct foo {\n"
11243                "#ifdef FOO\n"
11244                "#endif\n"
11245                "\n"
11246                "private:\n"
11247                "  int i;\n"
11248                "#ifdef FOO\n"
11249                "\n"
11250                "private:\n"
11251                "#endif\n"
11252                "  int j;\n"
11253                "};\n",
11254                "struct foo {\n"
11255                "#ifdef FOO\n"
11256                "#endif\n"
11257                "private:\n"
11258                "  int i;\n"
11259                "#ifdef FOO\n"
11260                "private:\n"
11261                "#endif\n"
11262                "  int j;\n"
11263                "};\n",
11264                Style);
11265   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11266   EXPECT_EQ("struct foo {\n"
11267             "\n"
11268             "private:\n"
11269             "  void f() {}\n"
11270             "\n"
11271             "private:\n"
11272             "  int i;\n"
11273             "\n"
11274             "protected:\n"
11275             "  int j;\n"
11276             "};\n",
11277             format("struct foo {\n"
11278                    "\n"
11279                    "private:\n"
11280                    "  void f() {}\n"
11281                    "\n"
11282                    "private:\n"
11283                    "  int i;\n"
11284                    "\n"
11285                    "protected:\n"
11286                    "  int j;\n"
11287                    "};\n",
11288                    Style));
11289   verifyFormat("struct foo {\n"
11290                "private:\n"
11291                "  void f() {}\n"
11292                "private:\n"
11293                "  int i;\n"
11294                "protected:\n"
11295                "  int j;\n"
11296                "};\n",
11297                Style);
11298   EXPECT_EQ("struct foo { /* comment */\n"
11299             "\n"
11300             "private:\n"
11301             "  int i;\n"
11302             "  // comment\n"
11303             "\n"
11304             "private:\n"
11305             "  int j;\n"
11306             "};\n",
11307             format("struct foo { /* comment */\n"
11308                    "\n"
11309                    "private:\n"
11310                    "  int i;\n"
11311                    "  // comment\n"
11312                    "\n"
11313                    "private:\n"
11314                    "  int j;\n"
11315                    "};\n",
11316                    Style));
11317   verifyFormat("struct foo { /* comment */\n"
11318                "private:\n"
11319                "  int i;\n"
11320                "  // comment\n"
11321                "private:\n"
11322                "  int j;\n"
11323                "};\n",
11324                Style);
11325   EXPECT_EQ("struct foo {\n"
11326             "#ifdef FOO\n"
11327             "#endif\n"
11328             "\n"
11329             "private:\n"
11330             "  int i;\n"
11331             "#ifdef FOO\n"
11332             "\n"
11333             "private:\n"
11334             "#endif\n"
11335             "  int j;\n"
11336             "};\n",
11337             format("struct foo {\n"
11338                    "#ifdef FOO\n"
11339                    "#endif\n"
11340                    "\n"
11341                    "private:\n"
11342                    "  int i;\n"
11343                    "#ifdef FOO\n"
11344                    "\n"
11345                    "private:\n"
11346                    "#endif\n"
11347                    "  int j;\n"
11348                    "};\n",
11349                    Style));
11350   verifyFormat("struct foo {\n"
11351                "#ifdef FOO\n"
11352                "#endif\n"
11353                "private:\n"
11354                "  int i;\n"
11355                "#ifdef FOO\n"
11356                "private:\n"
11357                "#endif\n"
11358                "  int j;\n"
11359                "};\n",
11360                Style);
11361 
11362   FormatStyle NoEmptyLines = getLLVMStyle();
11363   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11364   verifyFormat("struct foo {\n"
11365                "private:\n"
11366                "  void f() {}\n"
11367                "\n"
11368                "private:\n"
11369                "  int i;\n"
11370                "\n"
11371                "public:\n"
11372                "protected:\n"
11373                "  int j;\n"
11374                "};\n",
11375                NoEmptyLines);
11376 
11377   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11378   verifyFormat("struct foo {\n"
11379                "private:\n"
11380                "  void f() {}\n"
11381                "private:\n"
11382                "  int i;\n"
11383                "public:\n"
11384                "protected:\n"
11385                "  int j;\n"
11386                "};\n",
11387                NoEmptyLines);
11388 
11389   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11390   verifyFormat("struct foo {\n"
11391                "private:\n"
11392                "  void f() {}\n"
11393                "\n"
11394                "private:\n"
11395                "  int i;\n"
11396                "\n"
11397                "public:\n"
11398                "\n"
11399                "protected:\n"
11400                "  int j;\n"
11401                "};\n",
11402                NoEmptyLines);
11403 }
11404 
11405 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11406 
11407   FormatStyle Style = getLLVMStyle();
11408   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11409   verifyFormat("struct foo {\n"
11410                "private:\n"
11411                "  void f() {}\n"
11412                "\n"
11413                "private:\n"
11414                "  int i;\n"
11415                "\n"
11416                "protected:\n"
11417                "  int j;\n"
11418                "};\n",
11419                Style);
11420 
11421   // Check if lines are removed.
11422   verifyFormat("struct foo {\n"
11423                "private:\n"
11424                "  void f() {}\n"
11425                "\n"
11426                "private:\n"
11427                "  int i;\n"
11428                "\n"
11429                "protected:\n"
11430                "  int j;\n"
11431                "};\n",
11432                "struct foo {\n"
11433                "private:\n"
11434                "\n"
11435                "  void f() {}\n"
11436                "\n"
11437                "private:\n"
11438                "\n"
11439                "  int i;\n"
11440                "\n"
11441                "protected:\n"
11442                "\n"
11443                "  int j;\n"
11444                "};\n",
11445                Style);
11446 
11447   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11448   verifyFormat("struct foo {\n"
11449                "private:\n"
11450                "\n"
11451                "  void f() {}\n"
11452                "\n"
11453                "private:\n"
11454                "\n"
11455                "  int i;\n"
11456                "\n"
11457                "protected:\n"
11458                "\n"
11459                "  int j;\n"
11460                "};\n",
11461                Style);
11462 
11463   // Check if lines are added.
11464   verifyFormat("struct foo {\n"
11465                "private:\n"
11466                "\n"
11467                "  void f() {}\n"
11468                "\n"
11469                "private:\n"
11470                "\n"
11471                "  int i;\n"
11472                "\n"
11473                "protected:\n"
11474                "\n"
11475                "  int j;\n"
11476                "};\n",
11477                "struct foo {\n"
11478                "private:\n"
11479                "  void f() {}\n"
11480                "\n"
11481                "private:\n"
11482                "  int i;\n"
11483                "\n"
11484                "protected:\n"
11485                "  int j;\n"
11486                "};\n",
11487                Style);
11488 
11489   // Leave tests rely on the code layout, test::messUp can not be used.
11490   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11491   Style.MaxEmptyLinesToKeep = 0u;
11492   verifyFormat("struct foo {\n"
11493                "private:\n"
11494                "  void f() {}\n"
11495                "\n"
11496                "private:\n"
11497                "  int i;\n"
11498                "\n"
11499                "protected:\n"
11500                "  int j;\n"
11501                "};\n",
11502                Style);
11503 
11504   // Check if MaxEmptyLinesToKeep is respected.
11505   EXPECT_EQ("struct foo {\n"
11506             "private:\n"
11507             "  void f() {}\n"
11508             "\n"
11509             "private:\n"
11510             "  int i;\n"
11511             "\n"
11512             "protected:\n"
11513             "  int j;\n"
11514             "};\n",
11515             format("struct foo {\n"
11516                    "private:\n"
11517                    "\n\n\n"
11518                    "  void f() {}\n"
11519                    "\n"
11520                    "private:\n"
11521                    "\n\n\n"
11522                    "  int i;\n"
11523                    "\n"
11524                    "protected:\n"
11525                    "\n\n\n"
11526                    "  int j;\n"
11527                    "};\n",
11528                    Style));
11529 
11530   Style.MaxEmptyLinesToKeep = 1u;
11531   EXPECT_EQ("struct foo {\n"
11532             "private:\n"
11533             "\n"
11534             "  void f() {}\n"
11535             "\n"
11536             "private:\n"
11537             "\n"
11538             "  int i;\n"
11539             "\n"
11540             "protected:\n"
11541             "\n"
11542             "  int j;\n"
11543             "};\n",
11544             format("struct foo {\n"
11545                    "private:\n"
11546                    "\n"
11547                    "  void f() {}\n"
11548                    "\n"
11549                    "private:\n"
11550                    "\n"
11551                    "  int i;\n"
11552                    "\n"
11553                    "protected:\n"
11554                    "\n"
11555                    "  int j;\n"
11556                    "};\n",
11557                    Style));
11558   // Check if no lines are kept.
11559   EXPECT_EQ("struct foo {\n"
11560             "private:\n"
11561             "  void f() {}\n"
11562             "\n"
11563             "private:\n"
11564             "  int i;\n"
11565             "\n"
11566             "protected:\n"
11567             "  int j;\n"
11568             "};\n",
11569             format("struct foo {\n"
11570                    "private:\n"
11571                    "  void f() {}\n"
11572                    "\n"
11573                    "private:\n"
11574                    "  int i;\n"
11575                    "\n"
11576                    "protected:\n"
11577                    "  int j;\n"
11578                    "};\n",
11579                    Style));
11580   // Check if MaxEmptyLinesToKeep is respected.
11581   EXPECT_EQ("struct foo {\n"
11582             "private:\n"
11583             "\n"
11584             "  void f() {}\n"
11585             "\n"
11586             "private:\n"
11587             "\n"
11588             "  int i;\n"
11589             "\n"
11590             "protected:\n"
11591             "\n"
11592             "  int j;\n"
11593             "};\n",
11594             format("struct foo {\n"
11595                    "private:\n"
11596                    "\n\n\n"
11597                    "  void f() {}\n"
11598                    "\n"
11599                    "private:\n"
11600                    "\n\n\n"
11601                    "  int i;\n"
11602                    "\n"
11603                    "protected:\n"
11604                    "\n\n\n"
11605                    "  int j;\n"
11606                    "};\n",
11607                    Style));
11608 
11609   Style.MaxEmptyLinesToKeep = 10u;
11610   EXPECT_EQ("struct foo {\n"
11611             "private:\n"
11612             "\n\n\n"
11613             "  void f() {}\n"
11614             "\n"
11615             "private:\n"
11616             "\n\n\n"
11617             "  int i;\n"
11618             "\n"
11619             "protected:\n"
11620             "\n\n\n"
11621             "  int j;\n"
11622             "};\n",
11623             format("struct foo {\n"
11624                    "private:\n"
11625                    "\n\n\n"
11626                    "  void f() {}\n"
11627                    "\n"
11628                    "private:\n"
11629                    "\n\n\n"
11630                    "  int i;\n"
11631                    "\n"
11632                    "protected:\n"
11633                    "\n\n\n"
11634                    "  int j;\n"
11635                    "};\n",
11636                    Style));
11637 
11638   // Test with comments.
11639   Style = getLLVMStyle();
11640   verifyFormat("struct foo {\n"
11641                "private:\n"
11642                "  // comment\n"
11643                "  void f() {}\n"
11644                "\n"
11645                "private: /* comment */\n"
11646                "  int i;\n"
11647                "};\n",
11648                Style);
11649   verifyFormat("struct foo {\n"
11650                "private:\n"
11651                "  // comment\n"
11652                "  void f() {}\n"
11653                "\n"
11654                "private: /* comment */\n"
11655                "  int i;\n"
11656                "};\n",
11657                "struct foo {\n"
11658                "private:\n"
11659                "\n"
11660                "  // comment\n"
11661                "  void f() {}\n"
11662                "\n"
11663                "private: /* comment */\n"
11664                "\n"
11665                "  int i;\n"
11666                "};\n",
11667                Style);
11668 
11669   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11670   verifyFormat("struct foo {\n"
11671                "private:\n"
11672                "\n"
11673                "  // comment\n"
11674                "  void f() {}\n"
11675                "\n"
11676                "private: /* comment */\n"
11677                "\n"
11678                "  int i;\n"
11679                "};\n",
11680                "struct foo {\n"
11681                "private:\n"
11682                "  // comment\n"
11683                "  void f() {}\n"
11684                "\n"
11685                "private: /* comment */\n"
11686                "  int i;\n"
11687                "};\n",
11688                Style);
11689   verifyFormat("struct foo {\n"
11690                "private:\n"
11691                "\n"
11692                "  // comment\n"
11693                "  void f() {}\n"
11694                "\n"
11695                "private: /* comment */\n"
11696                "\n"
11697                "  int i;\n"
11698                "};\n",
11699                Style);
11700 
11701   // Test with preprocessor defines.
11702   Style = getLLVMStyle();
11703   verifyFormat("struct foo {\n"
11704                "private:\n"
11705                "#ifdef FOO\n"
11706                "#endif\n"
11707                "  void f() {}\n"
11708                "};\n",
11709                Style);
11710   verifyFormat("struct foo {\n"
11711                "private:\n"
11712                "#ifdef FOO\n"
11713                "#endif\n"
11714                "  void f() {}\n"
11715                "};\n",
11716                "struct foo {\n"
11717                "private:\n"
11718                "\n"
11719                "#ifdef FOO\n"
11720                "#endif\n"
11721                "  void f() {}\n"
11722                "};\n",
11723                Style);
11724 
11725   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11726   verifyFormat("struct foo {\n"
11727                "private:\n"
11728                "\n"
11729                "#ifdef FOO\n"
11730                "#endif\n"
11731                "  void f() {}\n"
11732                "};\n",
11733                "struct foo {\n"
11734                "private:\n"
11735                "#ifdef FOO\n"
11736                "#endif\n"
11737                "  void f() {}\n"
11738                "};\n",
11739                Style);
11740   verifyFormat("struct foo {\n"
11741                "private:\n"
11742                "\n"
11743                "#ifdef FOO\n"
11744                "#endif\n"
11745                "  void f() {}\n"
11746                "};\n",
11747                Style);
11748 }
11749 
11750 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11751   // Combined tests of EmptyLineAfterAccessModifier and
11752   // EmptyLineBeforeAccessModifier.
11753   FormatStyle Style = getLLVMStyle();
11754   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11755   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11756   verifyFormat("struct foo {\n"
11757                "private:\n"
11758                "\n"
11759                "protected:\n"
11760                "};\n",
11761                Style);
11762 
11763   Style.MaxEmptyLinesToKeep = 10u;
11764   // Both remove all new lines.
11765   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11766   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11767   verifyFormat("struct foo {\n"
11768                "private:\n"
11769                "protected:\n"
11770                "};\n",
11771                "struct foo {\n"
11772                "private:\n"
11773                "\n\n\n"
11774                "protected:\n"
11775                "};\n",
11776                Style);
11777 
11778   // Leave tests rely on the code layout, test::messUp can not be used.
11779   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11780   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11781   Style.MaxEmptyLinesToKeep = 10u;
11782   EXPECT_EQ("struct foo {\n"
11783             "private:\n"
11784             "\n\n\n"
11785             "protected:\n"
11786             "};\n",
11787             format("struct foo {\n"
11788                    "private:\n"
11789                    "\n\n\n"
11790                    "protected:\n"
11791                    "};\n",
11792                    Style));
11793   Style.MaxEmptyLinesToKeep = 3u;
11794   EXPECT_EQ("struct foo {\n"
11795             "private:\n"
11796             "\n\n\n"
11797             "protected:\n"
11798             "};\n",
11799             format("struct foo {\n"
11800                    "private:\n"
11801                    "\n\n\n"
11802                    "protected:\n"
11803                    "};\n",
11804                    Style));
11805   Style.MaxEmptyLinesToKeep = 1u;
11806   EXPECT_EQ("struct foo {\n"
11807             "private:\n"
11808             "\n\n\n"
11809             "protected:\n"
11810             "};\n",
11811             format("struct foo {\n"
11812                    "private:\n"
11813                    "\n\n\n"
11814                    "protected:\n"
11815                    "};\n",
11816                    Style)); // Based on new lines in original document and not
11817                             // on the setting.
11818 
11819   Style.MaxEmptyLinesToKeep = 10u;
11820   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11821   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11822   // Newlines are kept if they are greater than zero,
11823   // test::messUp removes all new lines which changes the logic
11824   EXPECT_EQ("struct foo {\n"
11825             "private:\n"
11826             "\n\n\n"
11827             "protected:\n"
11828             "};\n",
11829             format("struct foo {\n"
11830                    "private:\n"
11831                    "\n\n\n"
11832                    "protected:\n"
11833                    "};\n",
11834                    Style));
11835 
11836   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11837   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11838   // test::messUp removes all new lines which changes the logic
11839   EXPECT_EQ("struct foo {\n"
11840             "private:\n"
11841             "\n\n\n"
11842             "protected:\n"
11843             "};\n",
11844             format("struct foo {\n"
11845                    "private:\n"
11846                    "\n\n\n"
11847                    "protected:\n"
11848                    "};\n",
11849                    Style));
11850 
11851   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11852   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11853   EXPECT_EQ("struct foo {\n"
11854             "private:\n"
11855             "\n\n\n"
11856             "protected:\n"
11857             "};\n",
11858             format("struct foo {\n"
11859                    "private:\n"
11860                    "\n\n\n"
11861                    "protected:\n"
11862                    "};\n",
11863                    Style)); // test::messUp removes all new lines which changes
11864                             // the logic.
11865 
11866   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11867   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11868   verifyFormat("struct foo {\n"
11869                "private:\n"
11870                "protected:\n"
11871                "};\n",
11872                "struct foo {\n"
11873                "private:\n"
11874                "\n\n\n"
11875                "protected:\n"
11876                "};\n",
11877                Style);
11878 
11879   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11880   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11881   EXPECT_EQ("struct foo {\n"
11882             "private:\n"
11883             "\n\n\n"
11884             "protected:\n"
11885             "};\n",
11886             format("struct foo {\n"
11887                    "private:\n"
11888                    "\n\n\n"
11889                    "protected:\n"
11890                    "};\n",
11891                    Style)); // test::messUp removes all new lines which changes
11892                             // the logic.
11893 
11894   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11895   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11896   verifyFormat("struct foo {\n"
11897                "private:\n"
11898                "protected:\n"
11899                "};\n",
11900                "struct foo {\n"
11901                "private:\n"
11902                "\n\n\n"
11903                "protected:\n"
11904                "};\n",
11905                Style);
11906 
11907   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11908   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11909   verifyFormat("struct foo {\n"
11910                "private:\n"
11911                "protected:\n"
11912                "};\n",
11913                "struct foo {\n"
11914                "private:\n"
11915                "\n\n\n"
11916                "protected:\n"
11917                "};\n",
11918                Style);
11919 
11920   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11921   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11922   verifyFormat("struct foo {\n"
11923                "private:\n"
11924                "protected:\n"
11925                "};\n",
11926                "struct foo {\n"
11927                "private:\n"
11928                "\n\n\n"
11929                "protected:\n"
11930                "};\n",
11931                Style);
11932 
11933   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11934   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11935   verifyFormat("struct foo {\n"
11936                "private:\n"
11937                "protected:\n"
11938                "};\n",
11939                "struct foo {\n"
11940                "private:\n"
11941                "\n\n\n"
11942                "protected:\n"
11943                "};\n",
11944                Style);
11945 }
11946 
11947 TEST_F(FormatTest, FormatsArrays) {
11948   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11949                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11950   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11951                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11952   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11953                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11954   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11955                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11956   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11957                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11958   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11959                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11960                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11961   verifyFormat(
11962       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11963       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11964       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11965   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11966                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11967 
11968   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11969                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11970   verifyFormat(
11971       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11972       "                                  .aaaaaaa[0]\n"
11973       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11974   verifyFormat("a[::b::c];");
11975 
11976   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11977 
11978   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11979   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11980 }
11981 
11982 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11983   verifyFormat("(a)->b();");
11984   verifyFormat("--a;");
11985 }
11986 
11987 TEST_F(FormatTest, HandlesIncludeDirectives) {
11988   verifyFormat("#include <string>\n"
11989                "#include <a/b/c.h>\n"
11990                "#include \"a/b/string\"\n"
11991                "#include \"string.h\"\n"
11992                "#include \"string.h\"\n"
11993                "#include <a-a>\n"
11994                "#include < path with space >\n"
11995                "#include_next <test.h>"
11996                "#include \"abc.h\" // this is included for ABC\n"
11997                "#include \"some long include\" // with a comment\n"
11998                "#include \"some very long include path\"\n"
11999                "#include <some/very/long/include/path>\n",
12000                getLLVMStyleWithColumns(35));
12001   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
12002   EXPECT_EQ("#include <a>", format("#include<a>"));
12003 
12004   verifyFormat("#import <string>");
12005   verifyFormat("#import <a/b/c.h>");
12006   verifyFormat("#import \"a/b/string\"");
12007   verifyFormat("#import \"string.h\"");
12008   verifyFormat("#import \"string.h\"");
12009   verifyFormat("#if __has_include(<strstream>)\n"
12010                "#include <strstream>\n"
12011                "#endif");
12012 
12013   verifyFormat("#define MY_IMPORT <a/b>");
12014 
12015   verifyFormat("#if __has_include(<a/b>)");
12016   verifyFormat("#if __has_include_next(<a/b>)");
12017   verifyFormat("#define F __has_include(<a/b>)");
12018   verifyFormat("#define F __has_include_next(<a/b>)");
12019 
12020   // Protocol buffer definition or missing "#".
12021   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
12022                getLLVMStyleWithColumns(30));
12023 
12024   FormatStyle Style = getLLVMStyle();
12025   Style.AlwaysBreakBeforeMultilineStrings = true;
12026   Style.ColumnLimit = 0;
12027   verifyFormat("#import \"abc.h\"", Style);
12028 
12029   // But 'import' might also be a regular C++ namespace.
12030   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12031                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
12032 }
12033 
12034 //===----------------------------------------------------------------------===//
12035 // Error recovery tests.
12036 //===----------------------------------------------------------------------===//
12037 
12038 TEST_F(FormatTest, IncompleteParameterLists) {
12039   FormatStyle NoBinPacking = getLLVMStyle();
12040   NoBinPacking.BinPackParameters = false;
12041   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
12042                "                        double *min_x,\n"
12043                "                        double *max_x,\n"
12044                "                        double *min_y,\n"
12045                "                        double *max_y,\n"
12046                "                        double *min_z,\n"
12047                "                        double *max_z, ) {}",
12048                NoBinPacking);
12049 }
12050 
12051 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
12052   verifyFormat("void f() { return; }\n42");
12053   verifyFormat("void f() {\n"
12054                "  if (0)\n"
12055                "    return;\n"
12056                "}\n"
12057                "42");
12058   verifyFormat("void f() { return }\n42");
12059   verifyFormat("void f() {\n"
12060                "  if (0)\n"
12061                "    return\n"
12062                "}\n"
12063                "42");
12064 }
12065 
12066 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
12067   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
12068   EXPECT_EQ("void f() {\n"
12069             "  if (a)\n"
12070             "    return\n"
12071             "}",
12072             format("void  f  (  )  {  if  ( a )  return  }"));
12073   EXPECT_EQ("namespace N {\n"
12074             "void f()\n"
12075             "}",
12076             format("namespace  N  {  void f()  }"));
12077   EXPECT_EQ("namespace N {\n"
12078             "void f() {}\n"
12079             "void g()\n"
12080             "} // namespace N",
12081             format("namespace N  { void f( ) { } void g( ) }"));
12082 }
12083 
12084 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
12085   verifyFormat("int aaaaaaaa =\n"
12086                "    // Overlylongcomment\n"
12087                "    b;",
12088                getLLVMStyleWithColumns(20));
12089   verifyFormat("function(\n"
12090                "    ShortArgument,\n"
12091                "    LoooooooooooongArgument);\n",
12092                getLLVMStyleWithColumns(20));
12093 }
12094 
12095 TEST_F(FormatTest, IncorrectAccessSpecifier) {
12096   verifyFormat("public:");
12097   verifyFormat("class A {\n"
12098                "public\n"
12099                "  void f() {}\n"
12100                "};");
12101   verifyFormat("public\n"
12102                "int qwerty;");
12103   verifyFormat("public\n"
12104                "B {}");
12105   verifyFormat("public\n"
12106                "{}");
12107   verifyFormat("public\n"
12108                "B { int x; }");
12109 }
12110 
12111 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
12112   verifyFormat("{");
12113   verifyFormat("#})");
12114   verifyNoCrash("(/**/[:!] ?[).");
12115 }
12116 
12117 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
12118   // Found by oss-fuzz:
12119   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
12120   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
12121   Style.ColumnLimit = 60;
12122   verifyNoCrash(
12123       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
12124       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
12125       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
12126       Style);
12127 }
12128 
12129 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
12130   verifyFormat("do {\n}");
12131   verifyFormat("do {\n}\n"
12132                "f();");
12133   verifyFormat("do {\n}\n"
12134                "wheeee(fun);");
12135   verifyFormat("do {\n"
12136                "  f();\n"
12137                "}");
12138 }
12139 
12140 TEST_F(FormatTest, IncorrectCodeMissingParens) {
12141   verifyFormat("if {\n  foo;\n  foo();\n}");
12142   verifyFormat("switch {\n  foo;\n  foo();\n}");
12143   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
12144   verifyIncompleteFormat("ERROR: for target;");
12145   verifyFormat("while {\n  foo;\n  foo();\n}");
12146   verifyFormat("do {\n  foo;\n  foo();\n} while;");
12147 }
12148 
12149 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
12150   verifyIncompleteFormat("namespace {\n"
12151                          "class Foo { Foo (\n"
12152                          "};\n"
12153                          "} // namespace");
12154 }
12155 
12156 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
12157   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
12158   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
12159   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
12160   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
12161 
12162   EXPECT_EQ("{\n"
12163             "  {\n"
12164             "    breakme(\n"
12165             "        qwe);\n"
12166             "  }\n",
12167             format("{\n"
12168                    "    {\n"
12169                    " breakme(qwe);\n"
12170                    "}\n",
12171                    getLLVMStyleWithColumns(10)));
12172 }
12173 
12174 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
12175   verifyFormat("int x = {\n"
12176                "    avariable,\n"
12177                "    b(alongervariable)};",
12178                getLLVMStyleWithColumns(25));
12179 }
12180 
12181 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
12182   verifyFormat("return (a)(b){1, 2, 3};");
12183 }
12184 
12185 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
12186   verifyFormat("vector<int> x{1, 2, 3, 4};");
12187   verifyFormat("vector<int> x{\n"
12188                "    1,\n"
12189                "    2,\n"
12190                "    3,\n"
12191                "    4,\n"
12192                "};");
12193   verifyFormat("vector<T> x{{}, {}, {}, {}};");
12194   verifyFormat("f({1, 2});");
12195   verifyFormat("auto v = Foo{-1};");
12196   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
12197   verifyFormat("Class::Class : member{1, 2, 3} {}");
12198   verifyFormat("new vector<int>{1, 2, 3};");
12199   verifyFormat("new int[3]{1, 2, 3};");
12200   verifyFormat("new int{1};");
12201   verifyFormat("return {arg1, arg2};");
12202   verifyFormat("return {arg1, SomeType{parameter}};");
12203   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
12204   verifyFormat("new T{arg1, arg2};");
12205   verifyFormat("f(MyMap[{composite, key}]);");
12206   verifyFormat("class Class {\n"
12207                "  T member = {arg1, arg2};\n"
12208                "};");
12209   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
12210   verifyFormat("const struct A a = {.a = 1, .b = 2};");
12211   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
12212   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
12213   verifyFormat("int a = std::is_integral<int>{} + 0;");
12214 
12215   verifyFormat("int foo(int i) { return fo1{}(i); }");
12216   verifyFormat("int foo(int i) { return fo1{}(i); }");
12217   verifyFormat("auto i = decltype(x){};");
12218   verifyFormat("auto i = typeof(x){};");
12219   verifyFormat("auto i = _Atomic(x){};");
12220   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
12221   verifyFormat("Node n{1, Node{1000}, //\n"
12222                "       2};");
12223   verifyFormat("Aaaa aaaaaaa{\n"
12224                "    {\n"
12225                "        aaaa,\n"
12226                "    },\n"
12227                "};");
12228   verifyFormat("class C : public D {\n"
12229                "  SomeClass SC{2};\n"
12230                "};");
12231   verifyFormat("class C : public A {\n"
12232                "  class D : public B {\n"
12233                "    void f() { int i{2}; }\n"
12234                "  };\n"
12235                "};");
12236   verifyFormat("#define A {a, a},");
12237   // Don't confuse braced list initializers with compound statements.
12238   verifyFormat(
12239       "class A {\n"
12240       "  A() : a{} {}\n"
12241       "  A(int b) : b(b) {}\n"
12242       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12243       "  int a, b;\n"
12244       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12245       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12246       "{}\n"
12247       "};");
12248 
12249   // Avoid breaking between equal sign and opening brace
12250   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12251   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12252   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12253                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12254                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12255                "     {\"ccccccccccccccccccccc\", 2}};",
12256                AvoidBreakingFirstArgument);
12257 
12258   // Binpacking only if there is no trailing comma
12259   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12260                "                      cccccccccc, dddddddddd};",
12261                getLLVMStyleWithColumns(50));
12262   verifyFormat("const Aaaaaa aaaaa = {\n"
12263                "    aaaaaaaaaaa,\n"
12264                "    bbbbbbbbbbb,\n"
12265                "    ccccccccccc,\n"
12266                "    ddddddddddd,\n"
12267                "};",
12268                getLLVMStyleWithColumns(50));
12269 
12270   // Cases where distinguising braced lists and blocks is hard.
12271   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12272   verifyFormat("void f() {\n"
12273                "  return; // comment\n"
12274                "}\n"
12275                "SomeType t;");
12276   verifyFormat("void f() {\n"
12277                "  if (a) {\n"
12278                "    f();\n"
12279                "  }\n"
12280                "}\n"
12281                "SomeType t;");
12282 
12283   // In combination with BinPackArguments = false.
12284   FormatStyle NoBinPacking = getLLVMStyle();
12285   NoBinPacking.BinPackArguments = false;
12286   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12287                "                      bbbbb,\n"
12288                "                      ccccc,\n"
12289                "                      ddddd,\n"
12290                "                      eeeee,\n"
12291                "                      ffffff,\n"
12292                "                      ggggg,\n"
12293                "                      hhhhhh,\n"
12294                "                      iiiiii,\n"
12295                "                      jjjjjj,\n"
12296                "                      kkkkkk};",
12297                NoBinPacking);
12298   verifyFormat("const Aaaaaa aaaaa = {\n"
12299                "    aaaaa,\n"
12300                "    bbbbb,\n"
12301                "    ccccc,\n"
12302                "    ddddd,\n"
12303                "    eeeee,\n"
12304                "    ffffff,\n"
12305                "    ggggg,\n"
12306                "    hhhhhh,\n"
12307                "    iiiiii,\n"
12308                "    jjjjjj,\n"
12309                "    kkkkkk,\n"
12310                "};",
12311                NoBinPacking);
12312   verifyFormat(
12313       "const Aaaaaa aaaaa = {\n"
12314       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12315       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12316       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12317       "};",
12318       NoBinPacking);
12319 
12320   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12321   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12322             "    CDDDP83848_BMCR_REGISTER,\n"
12323             "    CDDDP83848_BMSR_REGISTER,\n"
12324             "    CDDDP83848_RBR_REGISTER};",
12325             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12326                    "                                CDDDP83848_BMSR_REGISTER,\n"
12327                    "                                CDDDP83848_RBR_REGISTER};",
12328                    NoBinPacking));
12329 
12330   // FIXME: The alignment of these trailing comments might be bad. Then again,
12331   // this might be utterly useless in real code.
12332   verifyFormat("Constructor::Constructor()\n"
12333                "    : some_value{         //\n"
12334                "                 aaaaaaa, //\n"
12335                "                 bbbbbbb} {}");
12336 
12337   // In braced lists, the first comment is always assumed to belong to the
12338   // first element. Thus, it can be moved to the next or previous line as
12339   // appropriate.
12340   EXPECT_EQ("function({// First element:\n"
12341             "          1,\n"
12342             "          // Second element:\n"
12343             "          2});",
12344             format("function({\n"
12345                    "    // First element:\n"
12346                    "    1,\n"
12347                    "    // Second element:\n"
12348                    "    2});"));
12349   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12350             "    // First element:\n"
12351             "    1,\n"
12352             "    // Second element:\n"
12353             "    2};",
12354             format("std::vector<int> MyNumbers{// First element:\n"
12355                    "                           1,\n"
12356                    "                           // Second element:\n"
12357                    "                           2};",
12358                    getLLVMStyleWithColumns(30)));
12359   // A trailing comma should still lead to an enforced line break and no
12360   // binpacking.
12361   EXPECT_EQ("vector<int> SomeVector = {\n"
12362             "    // aaa\n"
12363             "    1,\n"
12364             "    2,\n"
12365             "};",
12366             format("vector<int> SomeVector = { // aaa\n"
12367                    "    1, 2, };"));
12368 
12369   // C++11 brace initializer list l-braces should not be treated any differently
12370   // when breaking before lambda bodies is enabled
12371   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12372   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12373   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12374   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12375   verifyFormat(
12376       "std::runtime_error{\n"
12377       "    \"Long string which will force a break onto the next line...\"};",
12378       BreakBeforeLambdaBody);
12379 
12380   FormatStyle ExtraSpaces = getLLVMStyle();
12381   ExtraSpaces.Cpp11BracedListStyle = false;
12382   ExtraSpaces.ColumnLimit = 75;
12383   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12384   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12385   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12386   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12387   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12388   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12389   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12390   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12391   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12392   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12393   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12394   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12395   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12396   verifyFormat("class Class {\n"
12397                "  T member = { arg1, arg2 };\n"
12398                "};",
12399                ExtraSpaces);
12400   verifyFormat(
12401       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12402       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12403       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12404       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12405       ExtraSpaces);
12406   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12407   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12408                ExtraSpaces);
12409   verifyFormat(
12410       "someFunction(OtherParam,\n"
12411       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12412       "                         param1, param2,\n"
12413       "                         // comment 2\n"
12414       "                         param3, param4 });",
12415       ExtraSpaces);
12416   verifyFormat(
12417       "std::this_thread::sleep_for(\n"
12418       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12419       ExtraSpaces);
12420   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12421                "    aaaaaaa,\n"
12422                "    aaaaaaaaaa,\n"
12423                "    aaaaa,\n"
12424                "    aaaaaaaaaaaaaaa,\n"
12425                "    aaa,\n"
12426                "    aaaaaaaaaa,\n"
12427                "    a,\n"
12428                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12429                "    aaaaaaaaaaaa,\n"
12430                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12431                "    aaaaaaa,\n"
12432                "    a};");
12433   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12434   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12435   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12436 
12437   // Avoid breaking between initializer/equal sign and opening brace
12438   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12439   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12440                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12441                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12442                "  { \"ccccccccccccccccccccc\", 2 }\n"
12443                "};",
12444                ExtraSpaces);
12445   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12446                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12447                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12448                "  { \"ccccccccccccccccccccc\", 2 }\n"
12449                "};",
12450                ExtraSpaces);
12451 
12452   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12453   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12454   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12455   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12456 
12457   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12458   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12459   SpaceBetweenBraces.SpacesInParentheses = true;
12460   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12461   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12462   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12463   verifyFormat("vector< int > x{ // comment 1\n"
12464                "                 1, 2, 3, 4 };",
12465                SpaceBetweenBraces);
12466   SpaceBetweenBraces.ColumnLimit = 20;
12467   EXPECT_EQ("vector< int > x{\n"
12468             "    1, 2, 3, 4 };",
12469             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12470   SpaceBetweenBraces.ColumnLimit = 24;
12471   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12472             "                 3, 4 };",
12473             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12474   EXPECT_EQ("vector< int > x{\n"
12475             "    1,\n"
12476             "    2,\n"
12477             "    3,\n"
12478             "    4,\n"
12479             "};",
12480             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12481   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12482   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12483   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12484 }
12485 
12486 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12487   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12488                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12489                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12490                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12491                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12492                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12493   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12494                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12495                "                 1, 22, 333, 4444, 55555, //\n"
12496                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12497                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12498   verifyFormat(
12499       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12500       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12501       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12502       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12503       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12504       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12505       "                 7777777};");
12506   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12507                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12508                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12509   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12510                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12511                "    // Separating comment.\n"
12512                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12513   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12514                "    // Leading comment\n"
12515                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12516                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12517   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12518                "                 1, 1, 1, 1};",
12519                getLLVMStyleWithColumns(39));
12520   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12521                "                 1, 1, 1, 1};",
12522                getLLVMStyleWithColumns(38));
12523   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12524                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12525                getLLVMStyleWithColumns(43));
12526   verifyFormat(
12527       "static unsigned SomeValues[10][3] = {\n"
12528       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12529       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12530   verifyFormat("static auto fields = new vector<string>{\n"
12531                "    \"aaaaaaaaaaaaa\",\n"
12532                "    \"aaaaaaaaaaaaa\",\n"
12533                "    \"aaaaaaaaaaaa\",\n"
12534                "    \"aaaaaaaaaaaaaa\",\n"
12535                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12536                "    \"aaaaaaaaaaaa\",\n"
12537                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12538                "};");
12539   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12540   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12541                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12542                "                 3, cccccccccccccccccccccc};",
12543                getLLVMStyleWithColumns(60));
12544 
12545   // Trailing commas.
12546   verifyFormat("vector<int> x = {\n"
12547                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12548                "};",
12549                getLLVMStyleWithColumns(39));
12550   verifyFormat("vector<int> x = {\n"
12551                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12552                "};",
12553                getLLVMStyleWithColumns(39));
12554   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12555                "                 1, 1, 1, 1,\n"
12556                "                 /**/ /**/};",
12557                getLLVMStyleWithColumns(39));
12558 
12559   // Trailing comment in the first line.
12560   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12561                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12562                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12563                "    11111111,   22222222,   333333333,   44444444};");
12564   // Trailing comment in the last line.
12565   verifyFormat("int aaaaa[] = {\n"
12566                "    1, 2, 3, // comment\n"
12567                "    4, 5, 6  // comment\n"
12568                "};");
12569 
12570   // With nested lists, we should either format one item per line or all nested
12571   // lists one on line.
12572   // FIXME: For some nested lists, we can do better.
12573   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12574                "        {aaaaaaaaaaaaaaaaaaa},\n"
12575                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12576                "        {aaaaaaaaaaaaaaaaa}};",
12577                getLLVMStyleWithColumns(60));
12578   verifyFormat(
12579       "SomeStruct my_struct_array = {\n"
12580       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12581       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12582       "    {aaa, aaa},\n"
12583       "    {aaa, aaa},\n"
12584       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12585       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12586       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12587 
12588   // No column layout should be used here.
12589   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12590                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12591 
12592   verifyNoCrash("a<,");
12593 
12594   // No braced initializer here.
12595   verifyFormat("void f() {\n"
12596                "  struct Dummy {};\n"
12597                "  f(v);\n"
12598                "}");
12599 
12600   // Long lists should be formatted in columns even if they are nested.
12601   verifyFormat(
12602       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12603       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12604       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12605       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12606       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12607       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12608 
12609   // Allow "single-column" layout even if that violates the column limit. There
12610   // isn't going to be a better way.
12611   verifyFormat("std::vector<int> a = {\n"
12612                "    aaaaaaaa,\n"
12613                "    aaaaaaaa,\n"
12614                "    aaaaaaaa,\n"
12615                "    aaaaaaaa,\n"
12616                "    aaaaaaaaaa,\n"
12617                "    aaaaaaaa,\n"
12618                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12619                getLLVMStyleWithColumns(30));
12620   verifyFormat("vector<int> aaaa = {\n"
12621                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12622                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12623                "    aaaaaa.aaaaaaa,\n"
12624                "    aaaaaa.aaaaaaa,\n"
12625                "    aaaaaa.aaaaaaa,\n"
12626                "    aaaaaa.aaaaaaa,\n"
12627                "};");
12628 
12629   // Don't create hanging lists.
12630   verifyFormat("someFunction(Param, {List1, List2,\n"
12631                "                     List3});",
12632                getLLVMStyleWithColumns(35));
12633   verifyFormat("someFunction(Param, Param,\n"
12634                "             {List1, List2,\n"
12635                "              List3});",
12636                getLLVMStyleWithColumns(35));
12637   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12638                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12639 }
12640 
12641 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12642   FormatStyle DoNotMerge = getLLVMStyle();
12643   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12644 
12645   verifyFormat("void f() { return 42; }");
12646   verifyFormat("void f() {\n"
12647                "  return 42;\n"
12648                "}",
12649                DoNotMerge);
12650   verifyFormat("void f() {\n"
12651                "  // Comment\n"
12652                "}");
12653   verifyFormat("{\n"
12654                "#error {\n"
12655                "  int a;\n"
12656                "}");
12657   verifyFormat("{\n"
12658                "  int a;\n"
12659                "#error {\n"
12660                "}");
12661   verifyFormat("void f() {} // comment");
12662   verifyFormat("void f() { int a; } // comment");
12663   verifyFormat("void f() {\n"
12664                "} // comment",
12665                DoNotMerge);
12666   verifyFormat("void f() {\n"
12667                "  int a;\n"
12668                "} // comment",
12669                DoNotMerge);
12670   verifyFormat("void f() {\n"
12671                "} // comment",
12672                getLLVMStyleWithColumns(15));
12673 
12674   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12675   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12676 
12677   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12678   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12679   verifyFormat("class C {\n"
12680                "  C()\n"
12681                "      : iiiiiiii(nullptr),\n"
12682                "        kkkkkkk(nullptr),\n"
12683                "        mmmmmmm(nullptr),\n"
12684                "        nnnnnnn(nullptr) {}\n"
12685                "};",
12686                getGoogleStyle());
12687 
12688   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12689   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12690   EXPECT_EQ("class C {\n"
12691             "  A() : b(0) {}\n"
12692             "};",
12693             format("class C{A():b(0){}};", NoColumnLimit));
12694   EXPECT_EQ("A()\n"
12695             "    : b(0) {\n"
12696             "}",
12697             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12698 
12699   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12700   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12701       FormatStyle::SFS_None;
12702   EXPECT_EQ("A()\n"
12703             "    : b(0) {\n"
12704             "}",
12705             format("A():b(0){}", DoNotMergeNoColumnLimit));
12706   EXPECT_EQ("A()\n"
12707             "    : b(0) {\n"
12708             "}",
12709             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12710 
12711   verifyFormat("#define A          \\\n"
12712                "  void f() {       \\\n"
12713                "    int i;         \\\n"
12714                "  }",
12715                getLLVMStyleWithColumns(20));
12716   verifyFormat("#define A           \\\n"
12717                "  void f() { int i; }",
12718                getLLVMStyleWithColumns(21));
12719   verifyFormat("#define A            \\\n"
12720                "  void f() {         \\\n"
12721                "    int i;           \\\n"
12722                "  }                  \\\n"
12723                "  int j;",
12724                getLLVMStyleWithColumns(22));
12725   verifyFormat("#define A             \\\n"
12726                "  void f() { int i; } \\\n"
12727                "  int j;",
12728                getLLVMStyleWithColumns(23));
12729 }
12730 
12731 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12732   FormatStyle MergeEmptyOnly = getLLVMStyle();
12733   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12734   verifyFormat("class C {\n"
12735                "  int f() {}\n"
12736                "};",
12737                MergeEmptyOnly);
12738   verifyFormat("class C {\n"
12739                "  int f() {\n"
12740                "    return 42;\n"
12741                "  }\n"
12742                "};",
12743                MergeEmptyOnly);
12744   verifyFormat("int f() {}", MergeEmptyOnly);
12745   verifyFormat("int f() {\n"
12746                "  return 42;\n"
12747                "}",
12748                MergeEmptyOnly);
12749 
12750   // Also verify behavior when BraceWrapping.AfterFunction = true
12751   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12752   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12753   verifyFormat("int f() {}", MergeEmptyOnly);
12754   verifyFormat("class C {\n"
12755                "  int f() {}\n"
12756                "};",
12757                MergeEmptyOnly);
12758 }
12759 
12760 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12761   FormatStyle MergeInlineOnly = getLLVMStyle();
12762   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12763   verifyFormat("class C {\n"
12764                "  int f() { return 42; }\n"
12765                "};",
12766                MergeInlineOnly);
12767   verifyFormat("int f() {\n"
12768                "  return 42;\n"
12769                "}",
12770                MergeInlineOnly);
12771 
12772   // SFS_Inline implies SFS_Empty
12773   verifyFormat("class C {\n"
12774                "  int f() {}\n"
12775                "};",
12776                MergeInlineOnly);
12777   verifyFormat("int f() {}", MergeInlineOnly);
12778   // https://llvm.org/PR54147
12779   verifyFormat("auto lambda = []() {\n"
12780                "  // comment\n"
12781                "  f();\n"
12782                "  g();\n"
12783                "};",
12784                MergeInlineOnly);
12785 
12786   verifyFormat("class C {\n"
12787                "#ifdef A\n"
12788                "  int f() { return 42; }\n"
12789                "#endif\n"
12790                "};",
12791                MergeInlineOnly);
12792 
12793   verifyFormat("struct S {\n"
12794                "// comment\n"
12795                "#ifdef FOO\n"
12796                "  int foo() { bar(); }\n"
12797                "#endif\n"
12798                "};",
12799                MergeInlineOnly);
12800 
12801   // Also verify behavior when BraceWrapping.AfterFunction = true
12802   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12803   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12804   verifyFormat("class C {\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 
12814   // SFS_Inline implies SFS_Empty
12815   verifyFormat("int f() {}", MergeInlineOnly);
12816   verifyFormat("class C {\n"
12817                "  int f() {}\n"
12818                "};",
12819                MergeInlineOnly);
12820 
12821   MergeInlineOnly.BraceWrapping.AfterClass = true;
12822   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12823   verifyFormat("class C\n"
12824                "{\n"
12825                "  int f() { return 42; }\n"
12826                "};",
12827                MergeInlineOnly);
12828   verifyFormat("struct C\n"
12829                "{\n"
12830                "  int f() { return 42; }\n"
12831                "};",
12832                MergeInlineOnly);
12833   verifyFormat("int f()\n"
12834                "{\n"
12835                "  return 42;\n"
12836                "}",
12837                MergeInlineOnly);
12838   verifyFormat("int f() {}", MergeInlineOnly);
12839   verifyFormat("class C\n"
12840                "{\n"
12841                "  int f() { return 42; }\n"
12842                "};",
12843                MergeInlineOnly);
12844   verifyFormat("struct C\n"
12845                "{\n"
12846                "  int f() { return 42; }\n"
12847                "};",
12848                MergeInlineOnly);
12849   verifyFormat("struct C\n"
12850                "// comment\n"
12851                "/* comment */\n"
12852                "// comment\n"
12853                "{\n"
12854                "  int f() { return 42; }\n"
12855                "};",
12856                MergeInlineOnly);
12857   verifyFormat("/* comment */ struct C\n"
12858                "{\n"
12859                "  int f() { return 42; }\n"
12860                "};",
12861                MergeInlineOnly);
12862 }
12863 
12864 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12865   FormatStyle MergeInlineOnly = getLLVMStyle();
12866   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12867       FormatStyle::SFS_InlineOnly;
12868   verifyFormat("class C {\n"
12869                "  int f() { return 42; }\n"
12870                "};",
12871                MergeInlineOnly);
12872   verifyFormat("int f() {\n"
12873                "  return 42;\n"
12874                "}",
12875                MergeInlineOnly);
12876 
12877   // SFS_InlineOnly does not imply SFS_Empty
12878   verifyFormat("class C {\n"
12879                "  int f() {}\n"
12880                "};",
12881                MergeInlineOnly);
12882   verifyFormat("int f() {\n"
12883                "}",
12884                MergeInlineOnly);
12885 
12886   // Also verify behavior when BraceWrapping.AfterFunction = true
12887   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12888   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12889   verifyFormat("class C {\n"
12890                "  int f() { return 42; }\n"
12891                "};",
12892                MergeInlineOnly);
12893   verifyFormat("int f()\n"
12894                "{\n"
12895                "  return 42;\n"
12896                "}",
12897                MergeInlineOnly);
12898 
12899   // SFS_InlineOnly does not imply SFS_Empty
12900   verifyFormat("int f()\n"
12901                "{\n"
12902                "}",
12903                MergeInlineOnly);
12904   verifyFormat("class C {\n"
12905                "  int f() {}\n"
12906                "};",
12907                MergeInlineOnly);
12908 }
12909 
12910 TEST_F(FormatTest, SplitEmptyFunction) {
12911   FormatStyle Style = getLLVMStyleWithColumns(40);
12912   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12913   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12914   Style.BraceWrapping.AfterFunction = true;
12915   Style.BraceWrapping.SplitEmptyFunction = false;
12916 
12917   verifyFormat("int f()\n"
12918                "{}",
12919                Style);
12920   verifyFormat("int f()\n"
12921                "{\n"
12922                "  return 42;\n"
12923                "}",
12924                Style);
12925   verifyFormat("int f()\n"
12926                "{\n"
12927                "  // some comment\n"
12928                "}",
12929                Style);
12930 
12931   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12932   verifyFormat("int f() {}", Style);
12933   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12934                "{}",
12935                Style);
12936   verifyFormat("int f()\n"
12937                "{\n"
12938                "  return 0;\n"
12939                "}",
12940                Style);
12941 
12942   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12943   verifyFormat("class Foo {\n"
12944                "  int f() {}\n"
12945                "};\n",
12946                Style);
12947   verifyFormat("class Foo {\n"
12948                "  int f() { return 0; }\n"
12949                "};\n",
12950                Style);
12951   verifyFormat("class Foo {\n"
12952                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12953                "  {}\n"
12954                "};\n",
12955                Style);
12956   verifyFormat("class Foo {\n"
12957                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12958                "  {\n"
12959                "    return 0;\n"
12960                "  }\n"
12961                "};\n",
12962                Style);
12963 
12964   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12965   verifyFormat("int f() {}", Style);
12966   verifyFormat("int f() { return 0; }", Style);
12967   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12968                "{}",
12969                Style);
12970   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12971                "{\n"
12972                "  return 0;\n"
12973                "}",
12974                Style);
12975 }
12976 
12977 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12978   FormatStyle Style = getLLVMStyleWithColumns(40);
12979   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12980   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12981   Style.BraceWrapping.AfterFunction = true;
12982   Style.BraceWrapping.SplitEmptyFunction = true;
12983   Style.BraceWrapping.SplitEmptyRecord = false;
12984 
12985   verifyFormat("class C {};", Style);
12986   verifyFormat("struct C {};", Style);
12987   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12988                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12989                "{\n"
12990                "}",
12991                Style);
12992   verifyFormat("class C {\n"
12993                "  C()\n"
12994                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12995                "        bbbbbbbbbbbbbbbbbbb()\n"
12996                "  {\n"
12997                "  }\n"
12998                "  void\n"
12999                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
13000                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
13001                "  {\n"
13002                "  }\n"
13003                "};",
13004                Style);
13005 }
13006 
13007 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
13008   FormatStyle Style = getLLVMStyle();
13009   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13010   verifyFormat("#ifdef A\n"
13011                "int f() {}\n"
13012                "#else\n"
13013                "int g() {}\n"
13014                "#endif",
13015                Style);
13016 }
13017 
13018 TEST_F(FormatTest, SplitEmptyClass) {
13019   FormatStyle Style = getLLVMStyle();
13020   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13021   Style.BraceWrapping.AfterClass = true;
13022   Style.BraceWrapping.SplitEmptyRecord = false;
13023 
13024   verifyFormat("class Foo\n"
13025                "{};",
13026                Style);
13027   verifyFormat("/* something */ class Foo\n"
13028                "{};",
13029                Style);
13030   verifyFormat("template <typename X> class Foo\n"
13031                "{};",
13032                Style);
13033   verifyFormat("class Foo\n"
13034                "{\n"
13035                "  Foo();\n"
13036                "};",
13037                Style);
13038   verifyFormat("typedef class Foo\n"
13039                "{\n"
13040                "} Foo_t;",
13041                Style);
13042 
13043   Style.BraceWrapping.SplitEmptyRecord = true;
13044   Style.BraceWrapping.AfterStruct = true;
13045   verifyFormat("class rep\n"
13046                "{\n"
13047                "};",
13048                Style);
13049   verifyFormat("struct rep\n"
13050                "{\n"
13051                "};",
13052                Style);
13053   verifyFormat("template <typename T> class rep\n"
13054                "{\n"
13055                "};",
13056                Style);
13057   verifyFormat("template <typename T> struct rep\n"
13058                "{\n"
13059                "};",
13060                Style);
13061   verifyFormat("class rep\n"
13062                "{\n"
13063                "  int x;\n"
13064                "};",
13065                Style);
13066   verifyFormat("struct rep\n"
13067                "{\n"
13068                "  int x;\n"
13069                "};",
13070                Style);
13071   verifyFormat("template <typename T> class rep\n"
13072                "{\n"
13073                "  int x;\n"
13074                "};",
13075                Style);
13076   verifyFormat("template <typename T> struct rep\n"
13077                "{\n"
13078                "  int x;\n"
13079                "};",
13080                Style);
13081   verifyFormat("template <typename T> class rep // Foo\n"
13082                "{\n"
13083                "  int x;\n"
13084                "};",
13085                Style);
13086   verifyFormat("template <typename T> struct rep // Bar\n"
13087                "{\n"
13088                "  int x;\n"
13089                "};",
13090                Style);
13091 
13092   verifyFormat("template <typename T> class rep<T>\n"
13093                "{\n"
13094                "  int x;\n"
13095                "};",
13096                Style);
13097 
13098   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13099                "{\n"
13100                "  int x;\n"
13101                "};",
13102                Style);
13103   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13104                "{\n"
13105                "};",
13106                Style);
13107 
13108   verifyFormat("#include \"stdint.h\"\n"
13109                "namespace rep {}",
13110                Style);
13111   verifyFormat("#include <stdint.h>\n"
13112                "namespace rep {}",
13113                Style);
13114   verifyFormat("#include <stdint.h>\n"
13115                "namespace rep {}",
13116                "#include <stdint.h>\n"
13117                "namespace rep {\n"
13118                "\n"
13119                "\n"
13120                "}",
13121                Style);
13122 }
13123 
13124 TEST_F(FormatTest, SplitEmptyStruct) {
13125   FormatStyle Style = getLLVMStyle();
13126   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13127   Style.BraceWrapping.AfterStruct = true;
13128   Style.BraceWrapping.SplitEmptyRecord = false;
13129 
13130   verifyFormat("struct Foo\n"
13131                "{};",
13132                Style);
13133   verifyFormat("/* something */ struct Foo\n"
13134                "{};",
13135                Style);
13136   verifyFormat("template <typename X> struct Foo\n"
13137                "{};",
13138                Style);
13139   verifyFormat("struct Foo\n"
13140                "{\n"
13141                "  Foo();\n"
13142                "};",
13143                Style);
13144   verifyFormat("typedef struct Foo\n"
13145                "{\n"
13146                "} Foo_t;",
13147                Style);
13148   // typedef struct Bar {} Bar_t;
13149 }
13150 
13151 TEST_F(FormatTest, SplitEmptyUnion) {
13152   FormatStyle Style = getLLVMStyle();
13153   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13154   Style.BraceWrapping.AfterUnion = true;
13155   Style.BraceWrapping.SplitEmptyRecord = false;
13156 
13157   verifyFormat("union Foo\n"
13158                "{};",
13159                Style);
13160   verifyFormat("/* something */ union Foo\n"
13161                "{};",
13162                Style);
13163   verifyFormat("union Foo\n"
13164                "{\n"
13165                "  A,\n"
13166                "};",
13167                Style);
13168   verifyFormat("typedef union Foo\n"
13169                "{\n"
13170                "} Foo_t;",
13171                Style);
13172 }
13173 
13174 TEST_F(FormatTest, SplitEmptyNamespace) {
13175   FormatStyle Style = getLLVMStyle();
13176   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13177   Style.BraceWrapping.AfterNamespace = true;
13178   Style.BraceWrapping.SplitEmptyNamespace = false;
13179 
13180   verifyFormat("namespace Foo\n"
13181                "{};",
13182                Style);
13183   verifyFormat("/* something */ namespace Foo\n"
13184                "{};",
13185                Style);
13186   verifyFormat("inline namespace Foo\n"
13187                "{};",
13188                Style);
13189   verifyFormat("/* something */ inline namespace Foo\n"
13190                "{};",
13191                Style);
13192   verifyFormat("export namespace Foo\n"
13193                "{};",
13194                Style);
13195   verifyFormat("namespace Foo\n"
13196                "{\n"
13197                "void Bar();\n"
13198                "};",
13199                Style);
13200 }
13201 
13202 TEST_F(FormatTest, NeverMergeShortRecords) {
13203   FormatStyle Style = getLLVMStyle();
13204 
13205   verifyFormat("class Foo {\n"
13206                "  Foo();\n"
13207                "};",
13208                Style);
13209   verifyFormat("typedef class Foo {\n"
13210                "  Foo();\n"
13211                "} Foo_t;",
13212                Style);
13213   verifyFormat("struct Foo {\n"
13214                "  Foo();\n"
13215                "};",
13216                Style);
13217   verifyFormat("typedef struct Foo {\n"
13218                "  Foo();\n"
13219                "} Foo_t;",
13220                Style);
13221   verifyFormat("union Foo {\n"
13222                "  A,\n"
13223                "};",
13224                Style);
13225   verifyFormat("typedef union Foo {\n"
13226                "  A,\n"
13227                "} Foo_t;",
13228                Style);
13229   verifyFormat("namespace Foo {\n"
13230                "void Bar();\n"
13231                "};",
13232                Style);
13233 
13234   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13235   Style.BraceWrapping.AfterClass = true;
13236   Style.BraceWrapping.AfterStruct = true;
13237   Style.BraceWrapping.AfterUnion = true;
13238   Style.BraceWrapping.AfterNamespace = true;
13239   verifyFormat("class Foo\n"
13240                "{\n"
13241                "  Foo();\n"
13242                "};",
13243                Style);
13244   verifyFormat("typedef class Foo\n"
13245                "{\n"
13246                "  Foo();\n"
13247                "} Foo_t;",
13248                Style);
13249   verifyFormat("struct Foo\n"
13250                "{\n"
13251                "  Foo();\n"
13252                "};",
13253                Style);
13254   verifyFormat("typedef struct Foo\n"
13255                "{\n"
13256                "  Foo();\n"
13257                "} Foo_t;",
13258                Style);
13259   verifyFormat("union Foo\n"
13260                "{\n"
13261                "  A,\n"
13262                "};",
13263                Style);
13264   verifyFormat("typedef union Foo\n"
13265                "{\n"
13266                "  A,\n"
13267                "} Foo_t;",
13268                Style);
13269   verifyFormat("namespace Foo\n"
13270                "{\n"
13271                "void Bar();\n"
13272                "};",
13273                Style);
13274 }
13275 
13276 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13277   // Elaborate type variable declarations.
13278   verifyFormat("struct foo a = {bar};\nint n;");
13279   verifyFormat("class foo a = {bar};\nint n;");
13280   verifyFormat("union foo a = {bar};\nint n;");
13281 
13282   // Elaborate types inside function definitions.
13283   verifyFormat("struct foo f() {}\nint n;");
13284   verifyFormat("class foo f() {}\nint n;");
13285   verifyFormat("union foo f() {}\nint n;");
13286 
13287   // Templates.
13288   verifyFormat("template <class X> void f() {}\nint n;");
13289   verifyFormat("template <struct X> void f() {}\nint n;");
13290   verifyFormat("template <union X> void f() {}\nint n;");
13291 
13292   // Actual definitions...
13293   verifyFormat("struct {\n} n;");
13294   verifyFormat(
13295       "template <template <class T, class Y>, class Z> class X {\n} n;");
13296   verifyFormat("union Z {\n  int n;\n} x;");
13297   verifyFormat("class MACRO Z {\n} n;");
13298   verifyFormat("class MACRO(X) Z {\n} n;");
13299   verifyFormat("class __attribute__(X) Z {\n} n;");
13300   verifyFormat("class __declspec(X) Z {\n} n;");
13301   verifyFormat("class A##B##C {\n} n;");
13302   verifyFormat("class alignas(16) Z {\n} n;");
13303   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13304   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13305 
13306   // Redefinition from nested context:
13307   verifyFormat("class A::B::C {\n} n;");
13308 
13309   // Template definitions.
13310   verifyFormat(
13311       "template <typename F>\n"
13312       "Matcher(const Matcher<F> &Other,\n"
13313       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13314       "                             !is_same<F, T>::value>::type * = 0)\n"
13315       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13316 
13317   // FIXME: This is still incorrectly handled at the formatter side.
13318   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13319   verifyFormat("int i = SomeFunction(a<b, a> b);");
13320 
13321   // FIXME:
13322   // This now gets parsed incorrectly as class definition.
13323   // verifyFormat("class A<int> f() {\n}\nint n;");
13324 
13325   // Elaborate types where incorrectly parsing the structural element would
13326   // break the indent.
13327   verifyFormat("if (true)\n"
13328                "  class X x;\n"
13329                "else\n"
13330                "  f();\n");
13331 
13332   // This is simply incomplete. Formatting is not important, but must not crash.
13333   verifyFormat("class A:");
13334 }
13335 
13336 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13337   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13338             format("#error Leave     all         white!!!!! space* alone!\n"));
13339   EXPECT_EQ(
13340       "#warning Leave     all         white!!!!! space* alone!\n",
13341       format("#warning Leave     all         white!!!!! space* alone!\n"));
13342   EXPECT_EQ("#error 1", format("  #  error   1"));
13343   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13344 }
13345 
13346 TEST_F(FormatTest, FormatHashIfExpressions) {
13347   verifyFormat("#if AAAA && BBBB");
13348   verifyFormat("#if (AAAA && BBBB)");
13349   verifyFormat("#elif (AAAA && BBBB)");
13350   // FIXME: Come up with a better indentation for #elif.
13351   verifyFormat(
13352       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13353       "    defined(BBBBBBBB)\n"
13354       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13355       "    defined(BBBBBBBB)\n"
13356       "#endif",
13357       getLLVMStyleWithColumns(65));
13358 }
13359 
13360 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13361   FormatStyle AllowsMergedIf = getGoogleStyle();
13362   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13363       FormatStyle::SIS_WithoutElse;
13364   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13365   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13366   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13367   EXPECT_EQ("if (true) return 42;",
13368             format("if (true)\nreturn 42;", AllowsMergedIf));
13369   FormatStyle ShortMergedIf = AllowsMergedIf;
13370   ShortMergedIf.ColumnLimit = 25;
13371   verifyFormat("#define A \\\n"
13372                "  if (true) return 42;",
13373                ShortMergedIf);
13374   verifyFormat("#define A \\\n"
13375                "  f();    \\\n"
13376                "  if (true)\n"
13377                "#define B",
13378                ShortMergedIf);
13379   verifyFormat("#define A \\\n"
13380                "  f();    \\\n"
13381                "  if (true)\n"
13382                "g();",
13383                ShortMergedIf);
13384   verifyFormat("{\n"
13385                "#ifdef A\n"
13386                "  // Comment\n"
13387                "  if (true) continue;\n"
13388                "#endif\n"
13389                "  // Comment\n"
13390                "  if (true) continue;\n"
13391                "}",
13392                ShortMergedIf);
13393   ShortMergedIf.ColumnLimit = 33;
13394   verifyFormat("#define A \\\n"
13395                "  if constexpr (true) return 42;",
13396                ShortMergedIf);
13397   verifyFormat("#define A \\\n"
13398                "  if CONSTEXPR (true) return 42;",
13399                ShortMergedIf);
13400   ShortMergedIf.ColumnLimit = 29;
13401   verifyFormat("#define A                   \\\n"
13402                "  if (aaaaaaaaaa) return 1; \\\n"
13403                "  return 2;",
13404                ShortMergedIf);
13405   ShortMergedIf.ColumnLimit = 28;
13406   verifyFormat("#define A         \\\n"
13407                "  if (aaaaaaaaaa) \\\n"
13408                "    return 1;     \\\n"
13409                "  return 2;",
13410                ShortMergedIf);
13411   verifyFormat("#define A                \\\n"
13412                "  if constexpr (aaaaaaa) \\\n"
13413                "    return 1;            \\\n"
13414                "  return 2;",
13415                ShortMergedIf);
13416   verifyFormat("#define A                \\\n"
13417                "  if CONSTEXPR (aaaaaaa) \\\n"
13418                "    return 1;            \\\n"
13419                "  return 2;",
13420                ShortMergedIf);
13421 
13422   verifyFormat("//\n"
13423                "#define a \\\n"
13424                "  if      \\\n"
13425                "  0",
13426                getChromiumStyle(FormatStyle::LK_Cpp));
13427 }
13428 
13429 TEST_F(FormatTest, FormatStarDependingOnContext) {
13430   verifyFormat("void f(int *a);");
13431   verifyFormat("void f() { f(fint * b); }");
13432   verifyFormat("class A {\n  void f(int *a);\n};");
13433   verifyFormat("class A {\n  int *a;\n};");
13434   verifyFormat("namespace a {\n"
13435                "namespace b {\n"
13436                "class A {\n"
13437                "  void f() {}\n"
13438                "  int *a;\n"
13439                "};\n"
13440                "} // namespace b\n"
13441                "} // namespace a");
13442 }
13443 
13444 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13445   verifyFormat("while");
13446   verifyFormat("operator");
13447 }
13448 
13449 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13450   // This code would be painfully slow to format if we didn't skip it.
13451   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
13452                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13453                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13454                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13455                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13456                    "A(1, 1)\n"
13457                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13458                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13459                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13460                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13461                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13462                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13463                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13464                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13465                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13466                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13467   // Deeply nested part is untouched, rest is formatted.
13468   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13469             format(std::string("int    i;\n") + Code + "int    j;\n",
13470                    getLLVMStyle(), SC_ExpectIncomplete));
13471 }
13472 
13473 //===----------------------------------------------------------------------===//
13474 // Objective-C tests.
13475 //===----------------------------------------------------------------------===//
13476 
13477 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13478   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13479   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13480             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13481   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13482   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13483   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13484             format("-(NSInteger)Method3:(id)anObject;"));
13485   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13486             format("-(NSInteger)Method4:(id)anObject;"));
13487   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13488             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13489   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13490             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13491   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13492             "forAllCells:(BOOL)flag;",
13493             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13494                    "forAllCells:(BOOL)flag;"));
13495 
13496   // Very long objectiveC method declaration.
13497   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13498                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13499   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13500                "                    inRange:(NSRange)range\n"
13501                "                   outRange:(NSRange)out_range\n"
13502                "                  outRange1:(NSRange)out_range1\n"
13503                "                  outRange2:(NSRange)out_range2\n"
13504                "                  outRange3:(NSRange)out_range3\n"
13505                "                  outRange4:(NSRange)out_range4\n"
13506                "                  outRange5:(NSRange)out_range5\n"
13507                "                  outRange6:(NSRange)out_range6\n"
13508                "                  outRange7:(NSRange)out_range7\n"
13509                "                  outRange8:(NSRange)out_range8\n"
13510                "                  outRange9:(NSRange)out_range9;");
13511 
13512   // When the function name has to be wrapped.
13513   FormatStyle Style = getLLVMStyle();
13514   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13515   // and always indents instead.
13516   Style.IndentWrappedFunctionNames = false;
13517   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13518                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13519                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13520                "}",
13521                Style);
13522   Style.IndentWrappedFunctionNames = true;
13523   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13524                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13525                "               anotherName:(NSString)dddddddddddddd {\n"
13526                "}",
13527                Style);
13528 
13529   verifyFormat("- (int)sum:(vector<int>)numbers;");
13530   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13531   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13532   // protocol lists (but not for template classes):
13533   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13534 
13535   verifyFormat("- (int (*)())foo:(int (*)())f;");
13536   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13537 
13538   // If there's no return type (very rare in practice!), LLVM and Google style
13539   // agree.
13540   verifyFormat("- foo;");
13541   verifyFormat("- foo:(int)f;");
13542   verifyGoogleFormat("- foo:(int)foo;");
13543 }
13544 
13545 TEST_F(FormatTest, BreaksStringLiterals) {
13546   EXPECT_EQ("\"some text \"\n"
13547             "\"other\";",
13548             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13549   EXPECT_EQ("\"some text \"\n"
13550             "\"other\";",
13551             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13552   EXPECT_EQ(
13553       "#define A  \\\n"
13554       "  \"some \"  \\\n"
13555       "  \"text \"  \\\n"
13556       "  \"other\";",
13557       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13558   EXPECT_EQ(
13559       "#define A  \\\n"
13560       "  \"so \"    \\\n"
13561       "  \"text \"  \\\n"
13562       "  \"other\";",
13563       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13564 
13565   EXPECT_EQ("\"some text\"",
13566             format("\"some text\"", getLLVMStyleWithColumns(1)));
13567   EXPECT_EQ("\"some text\"",
13568             format("\"some text\"", getLLVMStyleWithColumns(11)));
13569   EXPECT_EQ("\"some \"\n"
13570             "\"text\"",
13571             format("\"some text\"", getLLVMStyleWithColumns(10)));
13572   EXPECT_EQ("\"some \"\n"
13573             "\"text\"",
13574             format("\"some text\"", getLLVMStyleWithColumns(7)));
13575   EXPECT_EQ("\"some\"\n"
13576             "\" tex\"\n"
13577             "\"t\"",
13578             format("\"some text\"", getLLVMStyleWithColumns(6)));
13579   EXPECT_EQ("\"some\"\n"
13580             "\" tex\"\n"
13581             "\" and\"",
13582             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13583   EXPECT_EQ("\"some\"\n"
13584             "\"/tex\"\n"
13585             "\"/and\"",
13586             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13587 
13588   EXPECT_EQ("variable =\n"
13589             "    \"long string \"\n"
13590             "    \"literal\";",
13591             format("variable = \"long string literal\";",
13592                    getLLVMStyleWithColumns(20)));
13593 
13594   EXPECT_EQ("variable = f(\n"
13595             "    \"long string \"\n"
13596             "    \"literal\",\n"
13597             "    short,\n"
13598             "    loooooooooooooooooooong);",
13599             format("variable = f(\"long string literal\", short, "
13600                    "loooooooooooooooooooong);",
13601                    getLLVMStyleWithColumns(20)));
13602 
13603   EXPECT_EQ(
13604       "f(g(\"long string \"\n"
13605       "    \"literal\"),\n"
13606       "  b);",
13607       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13608   EXPECT_EQ("f(g(\"long string \"\n"
13609             "    \"literal\",\n"
13610             "    a),\n"
13611             "  b);",
13612             format("f(g(\"long string literal\", a), b);",
13613                    getLLVMStyleWithColumns(20)));
13614   EXPECT_EQ(
13615       "f(\"one two\".split(\n"
13616       "    variable));",
13617       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13618   EXPECT_EQ("f(\"one two three four five six \"\n"
13619             "  \"seven\".split(\n"
13620             "      really_looooong_variable));",
13621             format("f(\"one two three four five six seven\"."
13622                    "split(really_looooong_variable));",
13623                    getLLVMStyleWithColumns(33)));
13624 
13625   EXPECT_EQ("f(\"some \"\n"
13626             "  \"text\",\n"
13627             "  other);",
13628             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13629 
13630   // Only break as a last resort.
13631   verifyFormat(
13632       "aaaaaaaaaaaaaaaaaaaa(\n"
13633       "    aaaaaaaaaaaaaaaaaaaa,\n"
13634       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13635 
13636   EXPECT_EQ("\"splitmea\"\n"
13637             "\"trandomp\"\n"
13638             "\"oint\"",
13639             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13640 
13641   EXPECT_EQ("\"split/\"\n"
13642             "\"pathat/\"\n"
13643             "\"slashes\"",
13644             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13645 
13646   EXPECT_EQ("\"split/\"\n"
13647             "\"pathat/\"\n"
13648             "\"slashes\"",
13649             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13650   EXPECT_EQ("\"split at \"\n"
13651             "\"spaces/at/\"\n"
13652             "\"slashes.at.any$\"\n"
13653             "\"non-alphanumeric%\"\n"
13654             "\"1111111111characte\"\n"
13655             "\"rs\"",
13656             format("\"split at "
13657                    "spaces/at/"
13658                    "slashes.at."
13659                    "any$non-"
13660                    "alphanumeric%"
13661                    "1111111111characte"
13662                    "rs\"",
13663                    getLLVMStyleWithColumns(20)));
13664 
13665   // Verify that splitting the strings understands
13666   // Style::AlwaysBreakBeforeMultilineStrings.
13667   EXPECT_EQ("aaaaaaaaaaaa(\n"
13668             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13669             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13670             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13671                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13672                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13673                    getGoogleStyle()));
13674   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13675             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13676             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13677                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13678                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13679                    getGoogleStyle()));
13680   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13681             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13682             format("llvm::outs() << "
13683                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13684                    "aaaaaaaaaaaaaaaaaaa\";"));
13685   EXPECT_EQ("ffff(\n"
13686             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13687             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13688             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13689                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13690                    getGoogleStyle()));
13691 
13692   FormatStyle Style = getLLVMStyleWithColumns(12);
13693   Style.BreakStringLiterals = false;
13694   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13695 
13696   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13697   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13698   EXPECT_EQ("#define A \\\n"
13699             "  \"some \" \\\n"
13700             "  \"text \" \\\n"
13701             "  \"other\";",
13702             format("#define A \"some text other\";", AlignLeft));
13703 }
13704 
13705 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13706   EXPECT_EQ("C a = \"some more \"\n"
13707             "      \"text\";",
13708             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13709 }
13710 
13711 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13712   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13713   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13714   EXPECT_EQ("int i = a(b());",
13715             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13716 }
13717 
13718 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13719   EXPECT_EQ(
13720       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13721       "(\n"
13722       "    \"x\t\");",
13723       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13724              "aaaaaaa("
13725              "\"x\t\");"));
13726 }
13727 
13728 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13729   EXPECT_EQ(
13730       "u8\"utf8 string \"\n"
13731       "u8\"literal\";",
13732       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13733   EXPECT_EQ(
13734       "u\"utf16 string \"\n"
13735       "u\"literal\";",
13736       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13737   EXPECT_EQ(
13738       "U\"utf32 string \"\n"
13739       "U\"literal\";",
13740       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13741   EXPECT_EQ("L\"wide string \"\n"
13742             "L\"literal\";",
13743             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13744   EXPECT_EQ("@\"NSString \"\n"
13745             "@\"literal\";",
13746             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13747   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13748 
13749   // This input makes clang-format try to split the incomplete unicode escape
13750   // sequence, which used to lead to a crasher.
13751   verifyNoCrash(
13752       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13753       getLLVMStyleWithColumns(60));
13754 }
13755 
13756 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13757   FormatStyle Style = getGoogleStyleWithColumns(15);
13758   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13759   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13760   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13761   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13762   EXPECT_EQ("u8R\"x(raw literal)x\";",
13763             format("u8R\"x(raw literal)x\";", Style));
13764 }
13765 
13766 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13767   FormatStyle Style = getLLVMStyleWithColumns(20);
13768   EXPECT_EQ(
13769       "_T(\"aaaaaaaaaaaaaa\")\n"
13770       "_T(\"aaaaaaaaaaaaaa\")\n"
13771       "_T(\"aaaaaaaaaaaa\")",
13772       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13773   EXPECT_EQ("f(x,\n"
13774             "  _T(\"aaaaaaaaaaaa\")\n"
13775             "  _T(\"aaa\"),\n"
13776             "  z);",
13777             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13778 
13779   // FIXME: Handle embedded spaces in one iteration.
13780   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13781   //            "_T(\"aaaaaaaaaaaaa\")\n"
13782   //            "_T(\"aaaaaaaaaaaaa\")\n"
13783   //            "_T(\"a\")",
13784   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13785   //                   getLLVMStyleWithColumns(20)));
13786   EXPECT_EQ(
13787       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13788       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13789   EXPECT_EQ("f(\n"
13790             "#if !TEST\n"
13791             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13792             "#endif\n"
13793             ");",
13794             format("f(\n"
13795                    "#if !TEST\n"
13796                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13797                    "#endif\n"
13798                    ");"));
13799   EXPECT_EQ("f(\n"
13800             "\n"
13801             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13802             format("f(\n"
13803                    "\n"
13804                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13805   // Regression test for accessing tokens past the end of a vector in the
13806   // TokenLexer.
13807   verifyNoCrash(R"(_T(
13808 "
13809 )
13810 )");
13811 }
13812 
13813 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13814   // In a function call with two operands, the second can be broken with no line
13815   // break before it.
13816   EXPECT_EQ(
13817       "func(a, \"long long \"\n"
13818       "        \"long long\");",
13819       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13820   // In a function call with three operands, the second must be broken with a
13821   // line break before it.
13822   EXPECT_EQ("func(a,\n"
13823             "     \"long long long \"\n"
13824             "     \"long\",\n"
13825             "     c);",
13826             format("func(a, \"long long long long\", c);",
13827                    getLLVMStyleWithColumns(24)));
13828   // In a function call with three operands, the third must be broken with a
13829   // line break before it.
13830   EXPECT_EQ("func(a, b,\n"
13831             "     \"long long long \"\n"
13832             "     \"long\");",
13833             format("func(a, b, \"long long long long\");",
13834                    getLLVMStyleWithColumns(24)));
13835   // In a function call with three operands, both the second and the third must
13836   // be broken with a line break before them.
13837   EXPECT_EQ("func(a,\n"
13838             "     \"long long long \"\n"
13839             "     \"long\",\n"
13840             "     \"long long long \"\n"
13841             "     \"long\");",
13842             format("func(a, \"long long long long\", \"long long long long\");",
13843                    getLLVMStyleWithColumns(24)));
13844   // In a chain of << with two operands, the second can be broken with no line
13845   // break before it.
13846   EXPECT_EQ("a << \"line line \"\n"
13847             "     \"line\";",
13848             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13849   // In a chain of << with three operands, the second can be broken with no line
13850   // break before it.
13851   EXPECT_EQ(
13852       "abcde << \"line \"\n"
13853       "         \"line line\"\n"
13854       "      << c;",
13855       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13856   // In a chain of << with three operands, the third must be broken with a line
13857   // break before it.
13858   EXPECT_EQ(
13859       "a << b\n"
13860       "  << \"line line \"\n"
13861       "     \"line\";",
13862       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13863   // In a chain of << with three operands, the second can be broken with no line
13864   // break before it and the third must be broken with a line break before it.
13865   EXPECT_EQ("abcd << \"line line \"\n"
13866             "        \"line\"\n"
13867             "     << \"line line \"\n"
13868             "        \"line\";",
13869             format("abcd << \"line line line\" << \"line line line\";",
13870                    getLLVMStyleWithColumns(20)));
13871   // In a chain of binary operators with two operands, the second can be broken
13872   // with no line break before it.
13873   EXPECT_EQ(
13874       "abcd + \"line line \"\n"
13875       "       \"line line\";",
13876       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13877   // In a chain of binary operators with three operands, the second must be
13878   // broken with a line break before it.
13879   EXPECT_EQ("abcd +\n"
13880             "    \"line line \"\n"
13881             "    \"line line\" +\n"
13882             "    e;",
13883             format("abcd + \"line line line line\" + e;",
13884                    getLLVMStyleWithColumns(20)));
13885   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13886   // the first must be broken with a line break before it.
13887   FormatStyle Style = getLLVMStyleWithColumns(25);
13888   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13889   EXPECT_EQ("someFunction(\n"
13890             "    \"long long long \"\n"
13891             "    \"long\",\n"
13892             "    a);",
13893             format("someFunction(\"long long long long\", a);", Style));
13894 }
13895 
13896 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13897   EXPECT_EQ(
13898       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13899       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13900       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13901       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13902              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13903              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13904 }
13905 
13906 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13907   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13908             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13909   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13910             "multiline raw string literal xxxxxxxxxxxxxx\n"
13911             ")x\",\n"
13912             "              a),\n"
13913             "            b);",
13914             format("fffffffffff(g(R\"x(\n"
13915                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13916                    ")x\", a), b);",
13917                    getGoogleStyleWithColumns(20)));
13918   EXPECT_EQ("fffffffffff(\n"
13919             "    g(R\"x(qqq\n"
13920             "multiline raw string literal xxxxxxxxxxxxxx\n"
13921             ")x\",\n"
13922             "      a),\n"
13923             "    b);",
13924             format("fffffffffff(g(R\"x(qqq\n"
13925                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13926                    ")x\", a), b);",
13927                    getGoogleStyleWithColumns(20)));
13928 
13929   EXPECT_EQ("fffffffffff(R\"x(\n"
13930             "multiline raw string literal xxxxxxxxxxxxxx\n"
13931             ")x\");",
13932             format("fffffffffff(R\"x(\n"
13933                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13934                    ")x\");",
13935                    getGoogleStyleWithColumns(20)));
13936   EXPECT_EQ("fffffffffff(R\"x(\n"
13937             "multiline raw string literal xxxxxxxxxxxxxx\n"
13938             ")x\" + bbbbbb);",
13939             format("fffffffffff(R\"x(\n"
13940                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13941                    ")x\" +   bbbbbb);",
13942                    getGoogleStyleWithColumns(20)));
13943   EXPECT_EQ("fffffffffff(\n"
13944             "    R\"x(\n"
13945             "multiline raw string literal xxxxxxxxxxxxxx\n"
13946             ")x\" +\n"
13947             "    bbbbbb);",
13948             format("fffffffffff(\n"
13949                    " R\"x(\n"
13950                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13951                    ")x\" + bbbbbb);",
13952                    getGoogleStyleWithColumns(20)));
13953   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13954             format("fffffffffff(\n"
13955                    " R\"(single line raw string)\" + bbbbbb);"));
13956 }
13957 
13958 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13959   verifyFormat("string a = \"unterminated;");
13960   EXPECT_EQ("function(\"unterminated,\n"
13961             "         OtherParameter);",
13962             format("function(  \"unterminated,\n"
13963                    "    OtherParameter);"));
13964 }
13965 
13966 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13967   FormatStyle Style = getLLVMStyle();
13968   Style.Standard = FormatStyle::LS_Cpp03;
13969   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13970             format("#define x(_a) printf(\"foo\"_a);", Style));
13971 }
13972 
13973 TEST_F(FormatTest, CppLexVersion) {
13974   FormatStyle Style = getLLVMStyle();
13975   // Formatting of x * y differs if x is a type.
13976   verifyFormat("void foo() { MACRO(a * b); }", Style);
13977   verifyFormat("void foo() { MACRO(int *b); }", Style);
13978 
13979   // LLVM style uses latest lexer.
13980   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13981   Style.Standard = FormatStyle::LS_Cpp17;
13982   // But in c++17, char8_t isn't a keyword.
13983   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13984 }
13985 
13986 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13987 
13988 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13989   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13990             "             \"ddeeefff\");",
13991             format("someFunction(\"aaabbbcccdddeeefff\");",
13992                    getLLVMStyleWithColumns(25)));
13993   EXPECT_EQ("someFunction1234567890(\n"
13994             "    \"aaabbbcccdddeeefff\");",
13995             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13996                    getLLVMStyleWithColumns(26)));
13997   EXPECT_EQ("someFunction1234567890(\n"
13998             "    \"aaabbbcccdddeeeff\"\n"
13999             "    \"f\");",
14000             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14001                    getLLVMStyleWithColumns(25)));
14002   EXPECT_EQ("someFunction1234567890(\n"
14003             "    \"aaabbbcccdddeeeff\"\n"
14004             "    \"f\");",
14005             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14006                    getLLVMStyleWithColumns(24)));
14007   EXPECT_EQ("someFunction(\n"
14008             "    \"aaabbbcc ddde \"\n"
14009             "    \"efff\");",
14010             format("someFunction(\"aaabbbcc ddde efff\");",
14011                    getLLVMStyleWithColumns(25)));
14012   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
14013             "             \"ddeeefff\");",
14014             format("someFunction(\"aaabbbccc ddeeefff\");",
14015                    getLLVMStyleWithColumns(25)));
14016   EXPECT_EQ("someFunction1234567890(\n"
14017             "    \"aaabb \"\n"
14018             "    \"cccdddeeefff\");",
14019             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
14020                    getLLVMStyleWithColumns(25)));
14021   EXPECT_EQ("#define A          \\\n"
14022             "  string s =       \\\n"
14023             "      \"123456789\"  \\\n"
14024             "      \"0\";         \\\n"
14025             "  int i;",
14026             format("#define A string s = \"1234567890\"; int i;",
14027                    getLLVMStyleWithColumns(20)));
14028   EXPECT_EQ("someFunction(\n"
14029             "    \"aaabbbcc \"\n"
14030             "    \"dddeeefff\");",
14031             format("someFunction(\"aaabbbcc dddeeefff\");",
14032                    getLLVMStyleWithColumns(25)));
14033 }
14034 
14035 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
14036   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
14037   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
14038   EXPECT_EQ("\"test\"\n"
14039             "\"\\n\"",
14040             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
14041   EXPECT_EQ("\"tes\\\\\"\n"
14042             "\"n\"",
14043             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
14044   EXPECT_EQ("\"\\\\\\\\\"\n"
14045             "\"\\n\"",
14046             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
14047   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
14048   EXPECT_EQ("\"\\uff01\"\n"
14049             "\"test\"",
14050             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
14051   EXPECT_EQ("\"\\Uff01ff02\"",
14052             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
14053   EXPECT_EQ("\"\\x000000000001\"\n"
14054             "\"next\"",
14055             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
14056   EXPECT_EQ("\"\\x000000000001next\"",
14057             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
14058   EXPECT_EQ("\"\\x000000000001\"",
14059             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
14060   EXPECT_EQ("\"test\"\n"
14061             "\"\\000000\"\n"
14062             "\"000001\"",
14063             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
14064   EXPECT_EQ("\"test\\000\"\n"
14065             "\"00000000\"\n"
14066             "\"1\"",
14067             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
14068 }
14069 
14070 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
14071   verifyFormat("void f() {\n"
14072                "  return g() {}\n"
14073                "  void h() {}");
14074   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
14075                "g();\n"
14076                "}");
14077 }
14078 
14079 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
14080   verifyFormat(
14081       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
14082 }
14083 
14084 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
14085   verifyFormat("class X {\n"
14086                "  void f() {\n"
14087                "  }\n"
14088                "};",
14089                getLLVMStyleWithColumns(12));
14090 }
14091 
14092 TEST_F(FormatTest, ConfigurableIndentWidth) {
14093   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
14094   EightIndent.IndentWidth = 8;
14095   EightIndent.ContinuationIndentWidth = 8;
14096   verifyFormat("void f() {\n"
14097                "        someFunction();\n"
14098                "        if (true) {\n"
14099                "                f();\n"
14100                "        }\n"
14101                "}",
14102                EightIndent);
14103   verifyFormat("class X {\n"
14104                "        void f() {\n"
14105                "        }\n"
14106                "};",
14107                EightIndent);
14108   verifyFormat("int x[] = {\n"
14109                "        call(),\n"
14110                "        call()};",
14111                EightIndent);
14112 }
14113 
14114 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
14115   verifyFormat("double\n"
14116                "f();",
14117                getLLVMStyleWithColumns(8));
14118 }
14119 
14120 TEST_F(FormatTest, ConfigurableUseOfTab) {
14121   FormatStyle Tab = getLLVMStyleWithColumns(42);
14122   Tab.IndentWidth = 8;
14123   Tab.UseTab = FormatStyle::UT_Always;
14124   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14125 
14126   EXPECT_EQ("if (aaaaaaaa && // q\n"
14127             "    bb)\t\t// w\n"
14128             "\t;",
14129             format("if (aaaaaaaa &&// q\n"
14130                    "bb)// w\n"
14131                    ";",
14132                    Tab));
14133   EXPECT_EQ("if (aaa && bbb) // w\n"
14134             "\t;",
14135             format("if(aaa&&bbb)// w\n"
14136                    ";",
14137                    Tab));
14138 
14139   verifyFormat("class X {\n"
14140                "\tvoid f() {\n"
14141                "\t\tsomeFunction(parameter1,\n"
14142                "\t\t\t     parameter2);\n"
14143                "\t}\n"
14144                "};",
14145                Tab);
14146   verifyFormat("#define A                        \\\n"
14147                "\tvoid f() {               \\\n"
14148                "\t\tsomeFunction(    \\\n"
14149                "\t\t    parameter1,  \\\n"
14150                "\t\t    parameter2); \\\n"
14151                "\t}",
14152                Tab);
14153   verifyFormat("int a;\t      // x\n"
14154                "int bbbbbbbb; // x\n",
14155                Tab);
14156 
14157   Tab.TabWidth = 4;
14158   Tab.IndentWidth = 8;
14159   verifyFormat("class TabWidth4Indent8 {\n"
14160                "\t\tvoid f() {\n"
14161                "\t\t\t\tsomeFunction(parameter1,\n"
14162                "\t\t\t\t\t\t\t parameter2);\n"
14163                "\t\t}\n"
14164                "};",
14165                Tab);
14166 
14167   Tab.TabWidth = 4;
14168   Tab.IndentWidth = 4;
14169   verifyFormat("class TabWidth4Indent4 {\n"
14170                "\tvoid f() {\n"
14171                "\t\tsomeFunction(parameter1,\n"
14172                "\t\t\t\t\t parameter2);\n"
14173                "\t}\n"
14174                "};",
14175                Tab);
14176 
14177   Tab.TabWidth = 8;
14178   Tab.IndentWidth = 4;
14179   verifyFormat("class TabWidth8Indent4 {\n"
14180                "    void f() {\n"
14181                "\tsomeFunction(parameter1,\n"
14182                "\t\t     parameter2);\n"
14183                "    }\n"
14184                "};",
14185                Tab);
14186 
14187   Tab.TabWidth = 8;
14188   Tab.IndentWidth = 8;
14189   EXPECT_EQ("/*\n"
14190             "\t      a\t\tcomment\n"
14191             "\t      in multiple lines\n"
14192             "       */",
14193             format("   /*\t \t \n"
14194                    " \t \t a\t\tcomment\t \t\n"
14195                    " \t \t in multiple lines\t\n"
14196                    " \t  */",
14197                    Tab));
14198 
14199   Tab.UseTab = FormatStyle::UT_ForIndentation;
14200   verifyFormat("{\n"
14201                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14202                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14203                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14204                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14205                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14206                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14207                "};",
14208                Tab);
14209   verifyFormat("enum AA {\n"
14210                "\ta1, // Force multiple lines\n"
14211                "\ta2,\n"
14212                "\ta3\n"
14213                "};",
14214                Tab);
14215   EXPECT_EQ("if (aaaaaaaa && // q\n"
14216             "    bb)         // w\n"
14217             "\t;",
14218             format("if (aaaaaaaa &&// q\n"
14219                    "bb)// w\n"
14220                    ";",
14221                    Tab));
14222   verifyFormat("class X {\n"
14223                "\tvoid f() {\n"
14224                "\t\tsomeFunction(parameter1,\n"
14225                "\t\t             parameter2);\n"
14226                "\t}\n"
14227                "};",
14228                Tab);
14229   verifyFormat("{\n"
14230                "\tQ(\n"
14231                "\t    {\n"
14232                "\t\t    int a;\n"
14233                "\t\t    someFunction(aaaaaaaa,\n"
14234                "\t\t                 bbbbbbb);\n"
14235                "\t    },\n"
14236                "\t    p);\n"
14237                "}",
14238                Tab);
14239   EXPECT_EQ("{\n"
14240             "\t/* aaaa\n"
14241             "\t   bbbb */\n"
14242             "}",
14243             format("{\n"
14244                    "/* aaaa\n"
14245                    "   bbbb */\n"
14246                    "}",
14247                    Tab));
14248   EXPECT_EQ("{\n"
14249             "\t/*\n"
14250             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14251             "\t  bbbbbbbbbbbbb\n"
14252             "\t*/\n"
14253             "}",
14254             format("{\n"
14255                    "/*\n"
14256                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14257                    "*/\n"
14258                    "}",
14259                    Tab));
14260   EXPECT_EQ("{\n"
14261             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14262             "\t// bbbbbbbbbbbbb\n"
14263             "}",
14264             format("{\n"
14265                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14266                    "}",
14267                    Tab));
14268   EXPECT_EQ("{\n"
14269             "\t/*\n"
14270             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14271             "\t  bbbbbbbbbbbbb\n"
14272             "\t*/\n"
14273             "}",
14274             format("{\n"
14275                    "\t/*\n"
14276                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14277                    "\t*/\n"
14278                    "}",
14279                    Tab));
14280   EXPECT_EQ("{\n"
14281             "\t/*\n"
14282             "\n"
14283             "\t*/\n"
14284             "}",
14285             format("{\n"
14286                    "\t/*\n"
14287                    "\n"
14288                    "\t*/\n"
14289                    "}",
14290                    Tab));
14291   EXPECT_EQ("{\n"
14292             "\t/*\n"
14293             " asdf\n"
14294             "\t*/\n"
14295             "}",
14296             format("{\n"
14297                    "\t/*\n"
14298                    " asdf\n"
14299                    "\t*/\n"
14300                    "}",
14301                    Tab));
14302 
14303   verifyFormat("void f() {\n"
14304                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14305                "\t            : bbbbbbbbbbbbbbbbbb\n"
14306                "}",
14307                Tab);
14308   FormatStyle TabNoBreak = Tab;
14309   TabNoBreak.BreakBeforeTernaryOperators = false;
14310   verifyFormat("void f() {\n"
14311                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14312                "\t              bbbbbbbbbbbbbbbbbb\n"
14313                "}",
14314                TabNoBreak);
14315   verifyFormat("void f() {\n"
14316                "\treturn true ?\n"
14317                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14318                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14319                "}",
14320                TabNoBreak);
14321 
14322   Tab.UseTab = FormatStyle::UT_Never;
14323   EXPECT_EQ("/*\n"
14324             "              a\t\tcomment\n"
14325             "              in multiple lines\n"
14326             "       */",
14327             format("   /*\t \t \n"
14328                    " \t \t a\t\tcomment\t \t\n"
14329                    " \t \t in multiple lines\t\n"
14330                    " \t  */",
14331                    Tab));
14332   EXPECT_EQ("/* some\n"
14333             "   comment */",
14334             format(" \t \t /* some\n"
14335                    " \t \t    comment */",
14336                    Tab));
14337   EXPECT_EQ("int a; /* some\n"
14338             "   comment */",
14339             format(" \t \t int a; /* some\n"
14340                    " \t \t    comment */",
14341                    Tab));
14342 
14343   EXPECT_EQ("int a; /* some\n"
14344             "comment */",
14345             format(" \t \t int\ta; /* some\n"
14346                    " \t \t    comment */",
14347                    Tab));
14348   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14349             "    comment */",
14350             format(" \t \t f(\"\t\t\"); /* some\n"
14351                    " \t \t    comment */",
14352                    Tab));
14353   EXPECT_EQ("{\n"
14354             "        /*\n"
14355             "         * Comment\n"
14356             "         */\n"
14357             "        int i;\n"
14358             "}",
14359             format("{\n"
14360                    "\t/*\n"
14361                    "\t * Comment\n"
14362                    "\t */\n"
14363                    "\t int i;\n"
14364                    "}",
14365                    Tab));
14366 
14367   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14368   Tab.TabWidth = 8;
14369   Tab.IndentWidth = 8;
14370   EXPECT_EQ("if (aaaaaaaa && // q\n"
14371             "    bb)         // w\n"
14372             "\t;",
14373             format("if (aaaaaaaa &&// q\n"
14374                    "bb)// w\n"
14375                    ";",
14376                    Tab));
14377   EXPECT_EQ("if (aaa && bbb) // w\n"
14378             "\t;",
14379             format("if(aaa&&bbb)// w\n"
14380                    ";",
14381                    Tab));
14382   verifyFormat("class X {\n"
14383                "\tvoid f() {\n"
14384                "\t\tsomeFunction(parameter1,\n"
14385                "\t\t\t     parameter2);\n"
14386                "\t}\n"
14387                "};",
14388                Tab);
14389   verifyFormat("#define A                        \\\n"
14390                "\tvoid f() {               \\\n"
14391                "\t\tsomeFunction(    \\\n"
14392                "\t\t    parameter1,  \\\n"
14393                "\t\t    parameter2); \\\n"
14394                "\t}",
14395                Tab);
14396   Tab.TabWidth = 4;
14397   Tab.IndentWidth = 8;
14398   verifyFormat("class TabWidth4Indent8 {\n"
14399                "\t\tvoid f() {\n"
14400                "\t\t\t\tsomeFunction(parameter1,\n"
14401                "\t\t\t\t\t\t\t parameter2);\n"
14402                "\t\t}\n"
14403                "};",
14404                Tab);
14405   Tab.TabWidth = 4;
14406   Tab.IndentWidth = 4;
14407   verifyFormat("class TabWidth4Indent4 {\n"
14408                "\tvoid f() {\n"
14409                "\t\tsomeFunction(parameter1,\n"
14410                "\t\t\t\t\t parameter2);\n"
14411                "\t}\n"
14412                "};",
14413                Tab);
14414   Tab.TabWidth = 8;
14415   Tab.IndentWidth = 4;
14416   verifyFormat("class TabWidth8Indent4 {\n"
14417                "    void f() {\n"
14418                "\tsomeFunction(parameter1,\n"
14419                "\t\t     parameter2);\n"
14420                "    }\n"
14421                "};",
14422                Tab);
14423   Tab.TabWidth = 8;
14424   Tab.IndentWidth = 8;
14425   EXPECT_EQ("/*\n"
14426             "\t      a\t\tcomment\n"
14427             "\t      in multiple lines\n"
14428             "       */",
14429             format("   /*\t \t \n"
14430                    " \t \t a\t\tcomment\t \t\n"
14431                    " \t \t in multiple lines\t\n"
14432                    " \t  */",
14433                    Tab));
14434   verifyFormat("{\n"
14435                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14436                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14437                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14438                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14439                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14440                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14441                "};",
14442                Tab);
14443   verifyFormat("enum AA {\n"
14444                "\ta1, // Force multiple lines\n"
14445                "\ta2,\n"
14446                "\ta3\n"
14447                "};",
14448                Tab);
14449   EXPECT_EQ("if (aaaaaaaa && // q\n"
14450             "    bb)         // w\n"
14451             "\t;",
14452             format("if (aaaaaaaa &&// q\n"
14453                    "bb)// w\n"
14454                    ";",
14455                    Tab));
14456   verifyFormat("class X {\n"
14457                "\tvoid f() {\n"
14458                "\t\tsomeFunction(parameter1,\n"
14459                "\t\t\t     parameter2);\n"
14460                "\t}\n"
14461                "};",
14462                Tab);
14463   verifyFormat("{\n"
14464                "\tQ(\n"
14465                "\t    {\n"
14466                "\t\t    int a;\n"
14467                "\t\t    someFunction(aaaaaaaa,\n"
14468                "\t\t\t\t bbbbbbb);\n"
14469                "\t    },\n"
14470                "\t    p);\n"
14471                "}",
14472                Tab);
14473   EXPECT_EQ("{\n"
14474             "\t/* aaaa\n"
14475             "\t   bbbb */\n"
14476             "}",
14477             format("{\n"
14478                    "/* aaaa\n"
14479                    "   bbbb */\n"
14480                    "}",
14481                    Tab));
14482   EXPECT_EQ("{\n"
14483             "\t/*\n"
14484             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14485             "\t  bbbbbbbbbbbbb\n"
14486             "\t*/\n"
14487             "}",
14488             format("{\n"
14489                    "/*\n"
14490                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14491                    "*/\n"
14492                    "}",
14493                    Tab));
14494   EXPECT_EQ("{\n"
14495             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14496             "\t// bbbbbbbbbbbbb\n"
14497             "}",
14498             format("{\n"
14499                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14500                    "}",
14501                    Tab));
14502   EXPECT_EQ("{\n"
14503             "\t/*\n"
14504             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14505             "\t  bbbbbbbbbbbbb\n"
14506             "\t*/\n"
14507             "}",
14508             format("{\n"
14509                    "\t/*\n"
14510                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14511                    "\t*/\n"
14512                    "}",
14513                    Tab));
14514   EXPECT_EQ("{\n"
14515             "\t/*\n"
14516             "\n"
14517             "\t*/\n"
14518             "}",
14519             format("{\n"
14520                    "\t/*\n"
14521                    "\n"
14522                    "\t*/\n"
14523                    "}",
14524                    Tab));
14525   EXPECT_EQ("{\n"
14526             "\t/*\n"
14527             " asdf\n"
14528             "\t*/\n"
14529             "}",
14530             format("{\n"
14531                    "\t/*\n"
14532                    " asdf\n"
14533                    "\t*/\n"
14534                    "}",
14535                    Tab));
14536   EXPECT_EQ("/* some\n"
14537             "   comment */",
14538             format(" \t \t /* some\n"
14539                    " \t \t    comment */",
14540                    Tab));
14541   EXPECT_EQ("int a; /* some\n"
14542             "   comment */",
14543             format(" \t \t int a; /* some\n"
14544                    " \t \t    comment */",
14545                    Tab));
14546   EXPECT_EQ("int a; /* some\n"
14547             "comment */",
14548             format(" \t \t int\ta; /* some\n"
14549                    " \t \t    comment */",
14550                    Tab));
14551   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14552             "    comment */",
14553             format(" \t \t f(\"\t\t\"); /* some\n"
14554                    " \t \t    comment */",
14555                    Tab));
14556   EXPECT_EQ("{\n"
14557             "\t/*\n"
14558             "\t * Comment\n"
14559             "\t */\n"
14560             "\tint i;\n"
14561             "}",
14562             format("{\n"
14563                    "\t/*\n"
14564                    "\t * Comment\n"
14565                    "\t */\n"
14566                    "\t int i;\n"
14567                    "}",
14568                    Tab));
14569   Tab.TabWidth = 2;
14570   Tab.IndentWidth = 2;
14571   EXPECT_EQ("{\n"
14572             "\t/* aaaa\n"
14573             "\t\t bbbb */\n"
14574             "}",
14575             format("{\n"
14576                    "/* aaaa\n"
14577                    "\t bbbb */\n"
14578                    "}",
14579                    Tab));
14580   EXPECT_EQ("{\n"
14581             "\t/*\n"
14582             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14583             "\t\tbbbbbbbbbbbbb\n"
14584             "\t*/\n"
14585             "}",
14586             format("{\n"
14587                    "/*\n"
14588                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14589                    "*/\n"
14590                    "}",
14591                    Tab));
14592   Tab.AlignConsecutiveAssignments.Enabled = true;
14593   Tab.AlignConsecutiveDeclarations.Enabled = true;
14594   Tab.TabWidth = 4;
14595   Tab.IndentWidth = 4;
14596   verifyFormat("class Assign {\n"
14597                "\tvoid f() {\n"
14598                "\t\tint         x      = 123;\n"
14599                "\t\tint         random = 4;\n"
14600                "\t\tstd::string alphabet =\n"
14601                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14602                "\t}\n"
14603                "};",
14604                Tab);
14605 
14606   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14607   Tab.TabWidth = 8;
14608   Tab.IndentWidth = 8;
14609   EXPECT_EQ("if (aaaaaaaa && // q\n"
14610             "    bb)         // w\n"
14611             "\t;",
14612             format("if (aaaaaaaa &&// q\n"
14613                    "bb)// w\n"
14614                    ";",
14615                    Tab));
14616   EXPECT_EQ("if (aaa && bbb) // w\n"
14617             "\t;",
14618             format("if(aaa&&bbb)// w\n"
14619                    ";",
14620                    Tab));
14621   verifyFormat("class X {\n"
14622                "\tvoid f() {\n"
14623                "\t\tsomeFunction(parameter1,\n"
14624                "\t\t             parameter2);\n"
14625                "\t}\n"
14626                "};",
14627                Tab);
14628   verifyFormat("#define A                        \\\n"
14629                "\tvoid f() {               \\\n"
14630                "\t\tsomeFunction(    \\\n"
14631                "\t\t    parameter1,  \\\n"
14632                "\t\t    parameter2); \\\n"
14633                "\t}",
14634                Tab);
14635   Tab.TabWidth = 4;
14636   Tab.IndentWidth = 8;
14637   verifyFormat("class TabWidth4Indent8 {\n"
14638                "\t\tvoid f() {\n"
14639                "\t\t\t\tsomeFunction(parameter1,\n"
14640                "\t\t\t\t             parameter2);\n"
14641                "\t\t}\n"
14642                "};",
14643                Tab);
14644   Tab.TabWidth = 4;
14645   Tab.IndentWidth = 4;
14646   verifyFormat("class TabWidth4Indent4 {\n"
14647                "\tvoid f() {\n"
14648                "\t\tsomeFunction(parameter1,\n"
14649                "\t\t             parameter2);\n"
14650                "\t}\n"
14651                "};",
14652                Tab);
14653   Tab.TabWidth = 8;
14654   Tab.IndentWidth = 4;
14655   verifyFormat("class TabWidth8Indent4 {\n"
14656                "    void f() {\n"
14657                "\tsomeFunction(parameter1,\n"
14658                "\t             parameter2);\n"
14659                "    }\n"
14660                "};",
14661                Tab);
14662   Tab.TabWidth = 8;
14663   Tab.IndentWidth = 8;
14664   EXPECT_EQ("/*\n"
14665             "              a\t\tcomment\n"
14666             "              in multiple lines\n"
14667             "       */",
14668             format("   /*\t \t \n"
14669                    " \t \t a\t\tcomment\t \t\n"
14670                    " \t \t in multiple lines\t\n"
14671                    " \t  */",
14672                    Tab));
14673   verifyFormat("{\n"
14674                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14675                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14676                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14677                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14678                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14679                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14680                "};",
14681                Tab);
14682   verifyFormat("enum AA {\n"
14683                "\ta1, // Force multiple lines\n"
14684                "\ta2,\n"
14685                "\ta3\n"
14686                "};",
14687                Tab);
14688   EXPECT_EQ("if (aaaaaaaa && // q\n"
14689             "    bb)         // w\n"
14690             "\t;",
14691             format("if (aaaaaaaa &&// q\n"
14692                    "bb)// w\n"
14693                    ";",
14694                    Tab));
14695   verifyFormat("class X {\n"
14696                "\tvoid f() {\n"
14697                "\t\tsomeFunction(parameter1,\n"
14698                "\t\t             parameter2);\n"
14699                "\t}\n"
14700                "};",
14701                Tab);
14702   verifyFormat("{\n"
14703                "\tQ(\n"
14704                "\t    {\n"
14705                "\t\t    int a;\n"
14706                "\t\t    someFunction(aaaaaaaa,\n"
14707                "\t\t                 bbbbbbb);\n"
14708                "\t    },\n"
14709                "\t    p);\n"
14710                "}",
14711                Tab);
14712   EXPECT_EQ("{\n"
14713             "\t/* aaaa\n"
14714             "\t   bbbb */\n"
14715             "}",
14716             format("{\n"
14717                    "/* aaaa\n"
14718                    "   bbbb */\n"
14719                    "}",
14720                    Tab));
14721   EXPECT_EQ("{\n"
14722             "\t/*\n"
14723             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14724             "\t  bbbbbbbbbbbbb\n"
14725             "\t*/\n"
14726             "}",
14727             format("{\n"
14728                    "/*\n"
14729                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14730                    "*/\n"
14731                    "}",
14732                    Tab));
14733   EXPECT_EQ("{\n"
14734             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14735             "\t// bbbbbbbbbbbbb\n"
14736             "}",
14737             format("{\n"
14738                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14739                    "}",
14740                    Tab));
14741   EXPECT_EQ("{\n"
14742             "\t/*\n"
14743             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14744             "\t  bbbbbbbbbbbbb\n"
14745             "\t*/\n"
14746             "}",
14747             format("{\n"
14748                    "\t/*\n"
14749                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14750                    "\t*/\n"
14751                    "}",
14752                    Tab));
14753   EXPECT_EQ("{\n"
14754             "\t/*\n"
14755             "\n"
14756             "\t*/\n"
14757             "}",
14758             format("{\n"
14759                    "\t/*\n"
14760                    "\n"
14761                    "\t*/\n"
14762                    "}",
14763                    Tab));
14764   EXPECT_EQ("{\n"
14765             "\t/*\n"
14766             " asdf\n"
14767             "\t*/\n"
14768             "}",
14769             format("{\n"
14770                    "\t/*\n"
14771                    " asdf\n"
14772                    "\t*/\n"
14773                    "}",
14774                    Tab));
14775   EXPECT_EQ("/* some\n"
14776             "   comment */",
14777             format(" \t \t /* some\n"
14778                    " \t \t    comment */",
14779                    Tab));
14780   EXPECT_EQ("int a; /* some\n"
14781             "   comment */",
14782             format(" \t \t int a; /* some\n"
14783                    " \t \t    comment */",
14784                    Tab));
14785   EXPECT_EQ("int a; /* some\n"
14786             "comment */",
14787             format(" \t \t int\ta; /* some\n"
14788                    " \t \t    comment */",
14789                    Tab));
14790   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14791             "    comment */",
14792             format(" \t \t f(\"\t\t\"); /* some\n"
14793                    " \t \t    comment */",
14794                    Tab));
14795   EXPECT_EQ("{\n"
14796             "\t/*\n"
14797             "\t * Comment\n"
14798             "\t */\n"
14799             "\tint i;\n"
14800             "}",
14801             format("{\n"
14802                    "\t/*\n"
14803                    "\t * Comment\n"
14804                    "\t */\n"
14805                    "\t int i;\n"
14806                    "}",
14807                    Tab));
14808   Tab.TabWidth = 2;
14809   Tab.IndentWidth = 2;
14810   EXPECT_EQ("{\n"
14811             "\t/* aaaa\n"
14812             "\t   bbbb */\n"
14813             "}",
14814             format("{\n"
14815                    "/* aaaa\n"
14816                    "   bbbb */\n"
14817                    "}",
14818                    Tab));
14819   EXPECT_EQ("{\n"
14820             "\t/*\n"
14821             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14822             "\t  bbbbbbbbbbbbb\n"
14823             "\t*/\n"
14824             "}",
14825             format("{\n"
14826                    "/*\n"
14827                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14828                    "*/\n"
14829                    "}",
14830                    Tab));
14831   Tab.AlignConsecutiveAssignments.Enabled = true;
14832   Tab.AlignConsecutiveDeclarations.Enabled = true;
14833   Tab.TabWidth = 4;
14834   Tab.IndentWidth = 4;
14835   verifyFormat("class Assign {\n"
14836                "\tvoid f() {\n"
14837                "\t\tint         x      = 123;\n"
14838                "\t\tint         random = 4;\n"
14839                "\t\tstd::string alphabet =\n"
14840                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14841                "\t}\n"
14842                "};",
14843                Tab);
14844   Tab.AlignOperands = FormatStyle::OAS_Align;
14845   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14846                "                 cccccccccccccccccccc;",
14847                Tab);
14848   // no alignment
14849   verifyFormat("int aaaaaaaaaa =\n"
14850                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14851                Tab);
14852   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14853                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14854                "                        : 333333333333333;",
14855                Tab);
14856   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14857   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14858   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14859                "               + cccccccccccccccccccc;",
14860                Tab);
14861 }
14862 
14863 TEST_F(FormatTest, ZeroTabWidth) {
14864   FormatStyle Tab = getLLVMStyleWithColumns(42);
14865   Tab.IndentWidth = 8;
14866   Tab.UseTab = FormatStyle::UT_Never;
14867   Tab.TabWidth = 0;
14868   EXPECT_EQ("void a(){\n"
14869             "    // line starts with '\t'\n"
14870             "};",
14871             format("void a(){\n"
14872                    "\t// line starts with '\t'\n"
14873                    "};",
14874                    Tab));
14875 
14876   EXPECT_EQ("void a(){\n"
14877             "    // line starts with '\t'\n"
14878             "};",
14879             format("void a(){\n"
14880                    "\t\t// line starts with '\t'\n"
14881                    "};",
14882                    Tab));
14883 
14884   Tab.UseTab = FormatStyle::UT_ForIndentation;
14885   EXPECT_EQ("void a(){\n"
14886             "    // line starts with '\t'\n"
14887             "};",
14888             format("void a(){\n"
14889                    "\t// line starts with '\t'\n"
14890                    "};",
14891                    Tab));
14892 
14893   EXPECT_EQ("void a(){\n"
14894             "    // line starts with '\t'\n"
14895             "};",
14896             format("void a(){\n"
14897                    "\t\t// line starts with '\t'\n"
14898                    "};",
14899                    Tab));
14900 
14901   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14902   EXPECT_EQ("void a(){\n"
14903             "    // line starts with '\t'\n"
14904             "};",
14905             format("void a(){\n"
14906                    "\t// line starts with '\t'\n"
14907                    "};",
14908                    Tab));
14909 
14910   EXPECT_EQ("void a(){\n"
14911             "    // line starts with '\t'\n"
14912             "};",
14913             format("void a(){\n"
14914                    "\t\t// line starts with '\t'\n"
14915                    "};",
14916                    Tab));
14917 
14918   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14919   EXPECT_EQ("void a(){\n"
14920             "    // line starts with '\t'\n"
14921             "};",
14922             format("void a(){\n"
14923                    "\t// line starts with '\t'\n"
14924                    "};",
14925                    Tab));
14926 
14927   EXPECT_EQ("void a(){\n"
14928             "    // line starts with '\t'\n"
14929             "};",
14930             format("void a(){\n"
14931                    "\t\t// line starts with '\t'\n"
14932                    "};",
14933                    Tab));
14934 
14935   Tab.UseTab = FormatStyle::UT_Always;
14936   EXPECT_EQ("void a(){\n"
14937             "// line starts with '\t'\n"
14938             "};",
14939             format("void a(){\n"
14940                    "\t// line starts with '\t'\n"
14941                    "};",
14942                    Tab));
14943 
14944   EXPECT_EQ("void a(){\n"
14945             "// line starts with '\t'\n"
14946             "};",
14947             format("void a(){\n"
14948                    "\t\t// line starts with '\t'\n"
14949                    "};",
14950                    Tab));
14951 }
14952 
14953 TEST_F(FormatTest, CalculatesOriginalColumn) {
14954   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14955             "q\"; /* some\n"
14956             "       comment */",
14957             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14958                    "q\"; /* some\n"
14959                    "       comment */",
14960                    getLLVMStyle()));
14961   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14962             "/* some\n"
14963             "   comment */",
14964             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14965                    " /* some\n"
14966                    "    comment */",
14967                    getLLVMStyle()));
14968   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14969             "qqq\n"
14970             "/* some\n"
14971             "   comment */",
14972             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14973                    "qqq\n"
14974                    " /* some\n"
14975                    "    comment */",
14976                    getLLVMStyle()));
14977   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14978             "wwww; /* some\n"
14979             "         comment */",
14980             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14981                    "wwww; /* some\n"
14982                    "         comment */",
14983                    getLLVMStyle()));
14984 }
14985 
14986 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14987   FormatStyle NoSpace = getLLVMStyle();
14988   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14989 
14990   verifyFormat("while(true)\n"
14991                "  continue;",
14992                NoSpace);
14993   verifyFormat("for(;;)\n"
14994                "  continue;",
14995                NoSpace);
14996   verifyFormat("if(true)\n"
14997                "  f();\n"
14998                "else if(true)\n"
14999                "  f();",
15000                NoSpace);
15001   verifyFormat("do {\n"
15002                "  do_something();\n"
15003                "} while(something());",
15004                NoSpace);
15005   verifyFormat("switch(x) {\n"
15006                "default:\n"
15007                "  break;\n"
15008                "}",
15009                NoSpace);
15010   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
15011   verifyFormat("size_t x = sizeof(x);", NoSpace);
15012   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
15013   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
15014   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
15015   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
15016   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
15017   verifyFormat("alignas(128) char a[128];", NoSpace);
15018   verifyFormat("size_t x = alignof(MyType);", NoSpace);
15019   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
15020   verifyFormat("int f() throw(Deprecated);", NoSpace);
15021   verifyFormat("typedef void (*cb)(int);", NoSpace);
15022   verifyFormat("T A::operator()();", NoSpace);
15023   verifyFormat("X A::operator++(T);", NoSpace);
15024   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
15025 
15026   FormatStyle Space = getLLVMStyle();
15027   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
15028 
15029   verifyFormat("int f ();", Space);
15030   verifyFormat("void f (int a, T b) {\n"
15031                "  while (true)\n"
15032                "    continue;\n"
15033                "}",
15034                Space);
15035   verifyFormat("if (true)\n"
15036                "  f ();\n"
15037                "else if (true)\n"
15038                "  f ();",
15039                Space);
15040   verifyFormat("do {\n"
15041                "  do_something ();\n"
15042                "} while (something ());",
15043                Space);
15044   verifyFormat("switch (x) {\n"
15045                "default:\n"
15046                "  break;\n"
15047                "}",
15048                Space);
15049   verifyFormat("A::A () : a (1) {}", Space);
15050   verifyFormat("void f () __attribute__ ((asdf));", Space);
15051   verifyFormat("*(&a + 1);\n"
15052                "&((&a)[1]);\n"
15053                "a[(b + c) * d];\n"
15054                "(((a + 1) * 2) + 3) * 4;",
15055                Space);
15056   verifyFormat("#define A(x) x", Space);
15057   verifyFormat("#define A (x) x", Space);
15058   verifyFormat("#if defined(x)\n"
15059                "#endif",
15060                Space);
15061   verifyFormat("auto i = std::make_unique<int> (5);", Space);
15062   verifyFormat("size_t x = sizeof (x);", Space);
15063   verifyFormat("auto f (int x) -> decltype (x);", Space);
15064   verifyFormat("auto f (int x) -> typeof (x);", Space);
15065   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
15066   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
15067   verifyFormat("int f (T x) noexcept (x.create ());", Space);
15068   verifyFormat("alignas (128) char a[128];", Space);
15069   verifyFormat("size_t x = alignof (MyType);", Space);
15070   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
15071   verifyFormat("int f () throw (Deprecated);", Space);
15072   verifyFormat("typedef void (*cb) (int);", Space);
15073   // FIXME these tests regressed behaviour.
15074   // verifyFormat("T A::operator() ();", Space);
15075   // verifyFormat("X A::operator++ (T);", Space);
15076   verifyFormat("auto lambda = [] () { return 0; };", Space);
15077   verifyFormat("int x = int (y);", Space);
15078 
15079   FormatStyle SomeSpace = getLLVMStyle();
15080   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
15081 
15082   verifyFormat("[]() -> float {}", SomeSpace);
15083   verifyFormat("[] (auto foo) {}", SomeSpace);
15084   verifyFormat("[foo]() -> int {}", SomeSpace);
15085   verifyFormat("int f();", SomeSpace);
15086   verifyFormat("void f (int a, T b) {\n"
15087                "  while (true)\n"
15088                "    continue;\n"
15089                "}",
15090                SomeSpace);
15091   verifyFormat("if (true)\n"
15092                "  f();\n"
15093                "else if (true)\n"
15094                "  f();",
15095                SomeSpace);
15096   verifyFormat("do {\n"
15097                "  do_something();\n"
15098                "} while (something());",
15099                SomeSpace);
15100   verifyFormat("switch (x) {\n"
15101                "default:\n"
15102                "  break;\n"
15103                "}",
15104                SomeSpace);
15105   verifyFormat("A::A() : a (1) {}", SomeSpace);
15106   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
15107   verifyFormat("*(&a + 1);\n"
15108                "&((&a)[1]);\n"
15109                "a[(b + c) * d];\n"
15110                "(((a + 1) * 2) + 3) * 4;",
15111                SomeSpace);
15112   verifyFormat("#define A(x) x", SomeSpace);
15113   verifyFormat("#define A (x) x", SomeSpace);
15114   verifyFormat("#if defined(x)\n"
15115                "#endif",
15116                SomeSpace);
15117   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
15118   verifyFormat("size_t x = sizeof (x);", SomeSpace);
15119   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
15120   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
15121   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
15122   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
15123   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
15124   verifyFormat("alignas (128) char a[128];", SomeSpace);
15125   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
15126   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15127                SomeSpace);
15128   verifyFormat("int f() throw (Deprecated);", SomeSpace);
15129   verifyFormat("typedef void (*cb) (int);", SomeSpace);
15130   verifyFormat("T A::operator()();", SomeSpace);
15131   // FIXME these tests regressed behaviour.
15132   // verifyFormat("X A::operator++ (T);", SomeSpace);
15133   verifyFormat("int x = int (y);", SomeSpace);
15134   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
15135 
15136   FormatStyle SpaceControlStatements = getLLVMStyle();
15137   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15138   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
15139 
15140   verifyFormat("while (true)\n"
15141                "  continue;",
15142                SpaceControlStatements);
15143   verifyFormat("if (true)\n"
15144                "  f();\n"
15145                "else if (true)\n"
15146                "  f();",
15147                SpaceControlStatements);
15148   verifyFormat("for (;;) {\n"
15149                "  do_something();\n"
15150                "}",
15151                SpaceControlStatements);
15152   verifyFormat("do {\n"
15153                "  do_something();\n"
15154                "} while (something());",
15155                SpaceControlStatements);
15156   verifyFormat("switch (x) {\n"
15157                "default:\n"
15158                "  break;\n"
15159                "}",
15160                SpaceControlStatements);
15161 
15162   FormatStyle SpaceFuncDecl = getLLVMStyle();
15163   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15164   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
15165 
15166   verifyFormat("int f ();", SpaceFuncDecl);
15167   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
15168   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
15169   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
15170   verifyFormat("#define A(x) x", SpaceFuncDecl);
15171   verifyFormat("#define A (x) x", SpaceFuncDecl);
15172   verifyFormat("#if defined(x)\n"
15173                "#endif",
15174                SpaceFuncDecl);
15175   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
15176   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
15177   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
15178   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
15179   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
15180   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
15181   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
15182   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
15183   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
15184   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15185                SpaceFuncDecl);
15186   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
15187   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
15188   // FIXME these tests regressed behaviour.
15189   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
15190   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
15191   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
15192   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
15193   verifyFormat("int x = int(y);", SpaceFuncDecl);
15194   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15195                SpaceFuncDecl);
15196 
15197   FormatStyle SpaceFuncDef = getLLVMStyle();
15198   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15199   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
15200 
15201   verifyFormat("int f();", SpaceFuncDef);
15202   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
15203   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
15204   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
15205   verifyFormat("#define A(x) x", SpaceFuncDef);
15206   verifyFormat("#define A (x) x", SpaceFuncDef);
15207   verifyFormat("#if defined(x)\n"
15208                "#endif",
15209                SpaceFuncDef);
15210   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
15211   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
15212   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
15213   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
15214   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
15215   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
15216   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
15217   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
15218   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
15219   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15220                SpaceFuncDef);
15221   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
15222   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
15223   verifyFormat("T A::operator()();", SpaceFuncDef);
15224   verifyFormat("X A::operator++(T);", SpaceFuncDef);
15225   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
15226   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
15227   verifyFormat("int x = int(y);", SpaceFuncDef);
15228   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15229                SpaceFuncDef);
15230 
15231   FormatStyle SpaceIfMacros = getLLVMStyle();
15232   SpaceIfMacros.IfMacros.clear();
15233   SpaceIfMacros.IfMacros.push_back("MYIF");
15234   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15235   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15236   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15237   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15238   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15239 
15240   FormatStyle SpaceForeachMacros = getLLVMStyle();
15241   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15242             FormatStyle::SBS_Never);
15243   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15244   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15245   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15246   verifyFormat("for (;;) {\n"
15247                "}",
15248                SpaceForeachMacros);
15249   verifyFormat("foreach (Item *item, itemlist) {\n"
15250                "}",
15251                SpaceForeachMacros);
15252   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15253                "}",
15254                SpaceForeachMacros);
15255   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15256                "}",
15257                SpaceForeachMacros);
15258   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15259 
15260   FormatStyle SomeSpace2 = getLLVMStyle();
15261   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15262   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15263   verifyFormat("[]() -> float {}", SomeSpace2);
15264   verifyFormat("[] (auto foo) {}", SomeSpace2);
15265   verifyFormat("[foo]() -> int {}", SomeSpace2);
15266   verifyFormat("int f();", SomeSpace2);
15267   verifyFormat("void f (int a, T b) {\n"
15268                "  while (true)\n"
15269                "    continue;\n"
15270                "}",
15271                SomeSpace2);
15272   verifyFormat("if (true)\n"
15273                "  f();\n"
15274                "else if (true)\n"
15275                "  f();",
15276                SomeSpace2);
15277   verifyFormat("do {\n"
15278                "  do_something();\n"
15279                "} while (something());",
15280                SomeSpace2);
15281   verifyFormat("switch (x) {\n"
15282                "default:\n"
15283                "  break;\n"
15284                "}",
15285                SomeSpace2);
15286   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15287   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15288   verifyFormat("*(&a + 1);\n"
15289                "&((&a)[1]);\n"
15290                "a[(b + c) * d];\n"
15291                "(((a + 1) * 2) + 3) * 4;",
15292                SomeSpace2);
15293   verifyFormat("#define A(x) x", SomeSpace2);
15294   verifyFormat("#define A (x) x", SomeSpace2);
15295   verifyFormat("#if defined(x)\n"
15296                "#endif",
15297                SomeSpace2);
15298   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15299   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15300   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15301   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15302   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15303   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15304   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15305   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15306   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15307   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15308                SomeSpace2);
15309   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15310   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15311   verifyFormat("T A::operator()();", SomeSpace2);
15312   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15313   verifyFormat("int x = int (y);", SomeSpace2);
15314   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15315 
15316   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15317   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15318   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15319       .AfterOverloadedOperator = true;
15320 
15321   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15322   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15323   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15324   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15325 
15326   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15327       .AfterOverloadedOperator = false;
15328 
15329   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15330   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15331   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15332   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15333 
15334   auto SpaceAfterRequires = getLLVMStyle();
15335   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15336   EXPECT_FALSE(
15337       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15338   EXPECT_FALSE(
15339       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15340   verifyFormat("void f(auto x)\n"
15341                "  requires requires(int i) { x + i; }\n"
15342                "{}",
15343                SpaceAfterRequires);
15344   verifyFormat("void f(auto x)\n"
15345                "  requires(requires(int i) { x + i; })\n"
15346                "{}",
15347                SpaceAfterRequires);
15348   verifyFormat("if (requires(int i) { x + i; })\n"
15349                "  return;",
15350                SpaceAfterRequires);
15351   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15352   verifyFormat("template <typename T>\n"
15353                "  requires(Foo<T>)\n"
15354                "class Bar;",
15355                SpaceAfterRequires);
15356 
15357   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15358   verifyFormat("void f(auto x)\n"
15359                "  requires requires(int i) { x + i; }\n"
15360                "{}",
15361                SpaceAfterRequires);
15362   verifyFormat("void f(auto x)\n"
15363                "  requires (requires(int i) { x + i; })\n"
15364                "{}",
15365                SpaceAfterRequires);
15366   verifyFormat("if (requires(int i) { x + i; })\n"
15367                "  return;",
15368                SpaceAfterRequires);
15369   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15370   verifyFormat("template <typename T>\n"
15371                "  requires (Foo<T>)\n"
15372                "class Bar;",
15373                SpaceAfterRequires);
15374 
15375   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15376   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15377   verifyFormat("void f(auto x)\n"
15378                "  requires requires (int i) { x + i; }\n"
15379                "{}",
15380                SpaceAfterRequires);
15381   verifyFormat("void f(auto x)\n"
15382                "  requires(requires (int i) { x + i; })\n"
15383                "{}",
15384                SpaceAfterRequires);
15385   verifyFormat("if (requires (int i) { x + i; })\n"
15386                "  return;",
15387                SpaceAfterRequires);
15388   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15389   verifyFormat("template <typename T>\n"
15390                "  requires(Foo<T>)\n"
15391                "class Bar;",
15392                SpaceAfterRequires);
15393 
15394   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15395   verifyFormat("void f(auto x)\n"
15396                "  requires requires (int i) { x + i; }\n"
15397                "{}",
15398                SpaceAfterRequires);
15399   verifyFormat("void f(auto x)\n"
15400                "  requires (requires (int i) { x + i; })\n"
15401                "{}",
15402                SpaceAfterRequires);
15403   verifyFormat("if (requires (int i) { x + i; })\n"
15404                "  return;",
15405                SpaceAfterRequires);
15406   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15407   verifyFormat("template <typename T>\n"
15408                "  requires (Foo<T>)\n"
15409                "class Bar;",
15410                SpaceAfterRequires);
15411 }
15412 
15413 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15414   FormatStyle Spaces = getLLVMStyle();
15415   Spaces.SpaceAfterLogicalNot = true;
15416 
15417   verifyFormat("bool x = ! y", Spaces);
15418   verifyFormat("if (! isFailure())", Spaces);
15419   verifyFormat("if (! (a && b))", Spaces);
15420   verifyFormat("\"Error!\"", Spaces);
15421   verifyFormat("! ! x", Spaces);
15422 }
15423 
15424 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15425   FormatStyle Spaces = getLLVMStyle();
15426 
15427   Spaces.SpacesInParentheses = true;
15428   verifyFormat("do_something( ::globalVar );", Spaces);
15429   verifyFormat("call( x, y, z );", Spaces);
15430   verifyFormat("call();", Spaces);
15431   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15432   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15433                Spaces);
15434   verifyFormat("while ( (bool)1 )\n"
15435                "  continue;",
15436                Spaces);
15437   verifyFormat("for ( ;; )\n"
15438                "  continue;",
15439                Spaces);
15440   verifyFormat("if ( true )\n"
15441                "  f();\n"
15442                "else if ( true )\n"
15443                "  f();",
15444                Spaces);
15445   verifyFormat("do {\n"
15446                "  do_something( (int)i );\n"
15447                "} while ( something() );",
15448                Spaces);
15449   verifyFormat("switch ( x ) {\n"
15450                "default:\n"
15451                "  break;\n"
15452                "}",
15453                Spaces);
15454 
15455   Spaces.SpacesInParentheses = false;
15456   Spaces.SpacesInCStyleCastParentheses = true;
15457   verifyFormat("Type *A = ( Type * )P;", Spaces);
15458   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15459   verifyFormat("x = ( int32 )y;", Spaces);
15460   verifyFormat("int a = ( int )(2.0f);", Spaces);
15461   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15462   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15463   verifyFormat("#define x (( int )-1)", Spaces);
15464 
15465   // Run the first set of tests again with:
15466   Spaces.SpacesInParentheses = false;
15467   Spaces.SpaceInEmptyParentheses = true;
15468   Spaces.SpacesInCStyleCastParentheses = true;
15469   verifyFormat("call(x, y, z);", Spaces);
15470   verifyFormat("call( );", Spaces);
15471   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15472   verifyFormat("while (( bool )1)\n"
15473                "  continue;",
15474                Spaces);
15475   verifyFormat("for (;;)\n"
15476                "  continue;",
15477                Spaces);
15478   verifyFormat("if (true)\n"
15479                "  f( );\n"
15480                "else if (true)\n"
15481                "  f( );",
15482                Spaces);
15483   verifyFormat("do {\n"
15484                "  do_something(( int )i);\n"
15485                "} while (something( ));",
15486                Spaces);
15487   verifyFormat("switch (x) {\n"
15488                "default:\n"
15489                "  break;\n"
15490                "}",
15491                Spaces);
15492 
15493   // Run the first set of tests again with:
15494   Spaces.SpaceAfterCStyleCast = true;
15495   verifyFormat("call(x, y, z);", Spaces);
15496   verifyFormat("call( );", Spaces);
15497   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15498   verifyFormat("while (( bool ) 1)\n"
15499                "  continue;",
15500                Spaces);
15501   verifyFormat("for (;;)\n"
15502                "  continue;",
15503                Spaces);
15504   verifyFormat("if (true)\n"
15505                "  f( );\n"
15506                "else if (true)\n"
15507                "  f( );",
15508                Spaces);
15509   verifyFormat("do {\n"
15510                "  do_something(( int ) i);\n"
15511                "} while (something( ));",
15512                Spaces);
15513   verifyFormat("switch (x) {\n"
15514                "default:\n"
15515                "  break;\n"
15516                "}",
15517                Spaces);
15518   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15519   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15520   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15521   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15522   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15523 
15524   // Run subset of tests again with:
15525   Spaces.SpacesInCStyleCastParentheses = false;
15526   Spaces.SpaceAfterCStyleCast = true;
15527   verifyFormat("while ((bool) 1)\n"
15528                "  continue;",
15529                Spaces);
15530   verifyFormat("do {\n"
15531                "  do_something((int) i);\n"
15532                "} while (something( ));",
15533                Spaces);
15534 
15535   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15536   verifyFormat("size_t idx = (size_t) a;", Spaces);
15537   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15538   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15539   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15540   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15541   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15542   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15543   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15544   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15545   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15546   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15547   Spaces.ColumnLimit = 80;
15548   Spaces.IndentWidth = 4;
15549   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15550   verifyFormat("void foo( ) {\n"
15551                "    size_t foo = (*(function))(\n"
15552                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15553                "BarrrrrrrrrrrrLong,\n"
15554                "        FoooooooooLooooong);\n"
15555                "}",
15556                Spaces);
15557   Spaces.SpaceAfterCStyleCast = false;
15558   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15559   verifyFormat("size_t idx = (size_t)a;", Spaces);
15560   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15561   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15562   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15563   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15564   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15565 
15566   verifyFormat("void foo( ) {\n"
15567                "    size_t foo = (*(function))(\n"
15568                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15569                "BarrrrrrrrrrrrLong,\n"
15570                "        FoooooooooLooooong);\n"
15571                "}",
15572                Spaces);
15573 }
15574 
15575 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15576   verifyFormat("int a[5];");
15577   verifyFormat("a[3] += 42;");
15578 
15579   FormatStyle Spaces = getLLVMStyle();
15580   Spaces.SpacesInSquareBrackets = true;
15581   // Not lambdas.
15582   verifyFormat("int a[ 5 ];", Spaces);
15583   verifyFormat("a[ 3 ] += 42;", Spaces);
15584   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15585   verifyFormat("double &operator[](int i) { return 0; }\n"
15586                "int i;",
15587                Spaces);
15588   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15589   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15590   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15591   // Lambdas.
15592   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15593   verifyFormat("return [ i, args... ] {};", Spaces);
15594   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15595   verifyFormat("int foo = [ = ]() {};", Spaces);
15596   verifyFormat("int foo = [ & ]() {};", Spaces);
15597   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15598   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15599 }
15600 
15601 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15602   FormatStyle NoSpaceStyle = getLLVMStyle();
15603   verifyFormat("int a[5];", NoSpaceStyle);
15604   verifyFormat("a[3] += 42;", NoSpaceStyle);
15605 
15606   verifyFormat("int a[1];", NoSpaceStyle);
15607   verifyFormat("int 1 [a];", NoSpaceStyle);
15608   verifyFormat("int a[1][2];", NoSpaceStyle);
15609   verifyFormat("a[7] = 5;", NoSpaceStyle);
15610   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15611   verifyFormat("f([] {})", NoSpaceStyle);
15612 
15613   FormatStyle Space = getLLVMStyle();
15614   Space.SpaceBeforeSquareBrackets = true;
15615   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15616   verifyFormat("return [i, args...] {};", Space);
15617 
15618   verifyFormat("int a [5];", Space);
15619   verifyFormat("a [3] += 42;", Space);
15620   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15621   verifyFormat("double &operator[](int i) { return 0; }\n"
15622                "int i;",
15623                Space);
15624   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15625   verifyFormat("int i = a [a][a]->f();", Space);
15626   verifyFormat("int i = (*b) [a]->f();", Space);
15627 
15628   verifyFormat("int a [1];", Space);
15629   verifyFormat("int 1 [a];", Space);
15630   verifyFormat("int a [1][2];", Space);
15631   verifyFormat("a [7] = 5;", Space);
15632   verifyFormat("int a = (f()) [23];", Space);
15633   verifyFormat("f([] {})", Space);
15634 }
15635 
15636 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15637   verifyFormat("int a = 5;");
15638   verifyFormat("a += 42;");
15639   verifyFormat("a or_eq 8;");
15640 
15641   FormatStyle Spaces = getLLVMStyle();
15642   Spaces.SpaceBeforeAssignmentOperators = false;
15643   verifyFormat("int a= 5;", Spaces);
15644   verifyFormat("a+= 42;", Spaces);
15645   verifyFormat("a or_eq 8;", Spaces);
15646 }
15647 
15648 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15649   verifyFormat("class Foo : public Bar {};");
15650   verifyFormat("Foo::Foo() : foo(1) {}");
15651   verifyFormat("for (auto a : b) {\n}");
15652   verifyFormat("int x = a ? b : c;");
15653   verifyFormat("{\n"
15654                "label0:\n"
15655                "  int x = 0;\n"
15656                "}");
15657   verifyFormat("switch (x) {\n"
15658                "case 1:\n"
15659                "default:\n"
15660                "}");
15661   verifyFormat("switch (allBraces) {\n"
15662                "case 1: {\n"
15663                "  break;\n"
15664                "}\n"
15665                "case 2: {\n"
15666                "  [[fallthrough]];\n"
15667                "}\n"
15668                "default: {\n"
15669                "  break;\n"
15670                "}\n"
15671                "}");
15672 
15673   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15674   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15675   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15676   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15677   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15678   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15679   verifyFormat("{\n"
15680                "label1:\n"
15681                "  int x = 0;\n"
15682                "}",
15683                CtorInitializerStyle);
15684   verifyFormat("switch (x) {\n"
15685                "case 1:\n"
15686                "default:\n"
15687                "}",
15688                CtorInitializerStyle);
15689   verifyFormat("switch (allBraces) {\n"
15690                "case 1: {\n"
15691                "  break;\n"
15692                "}\n"
15693                "case 2: {\n"
15694                "  [[fallthrough]];\n"
15695                "}\n"
15696                "default: {\n"
15697                "  break;\n"
15698                "}\n"
15699                "}",
15700                CtorInitializerStyle);
15701   CtorInitializerStyle.BreakConstructorInitializers =
15702       FormatStyle::BCIS_AfterColon;
15703   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15704                "    aaaaaaaaaaaaaaaa(1),\n"
15705                "    bbbbbbbbbbbbbbbb(2) {}",
15706                CtorInitializerStyle);
15707   CtorInitializerStyle.BreakConstructorInitializers =
15708       FormatStyle::BCIS_BeforeComma;
15709   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15710                "    : aaaaaaaaaaaaaaaa(1)\n"
15711                "    , bbbbbbbbbbbbbbbb(2) {}",
15712                CtorInitializerStyle);
15713   CtorInitializerStyle.BreakConstructorInitializers =
15714       FormatStyle::BCIS_BeforeColon;
15715   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15716                "    : aaaaaaaaaaaaaaaa(1),\n"
15717                "      bbbbbbbbbbbbbbbb(2) {}",
15718                CtorInitializerStyle);
15719   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15720   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15721                ": aaaaaaaaaaaaaaaa(1),\n"
15722                "  bbbbbbbbbbbbbbbb(2) {}",
15723                CtorInitializerStyle);
15724 
15725   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15726   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15727   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15728   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15729   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15730   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15731   verifyFormat("{\n"
15732                "label2:\n"
15733                "  int x = 0;\n"
15734                "}",
15735                InheritanceStyle);
15736   verifyFormat("switch (x) {\n"
15737                "case 1:\n"
15738                "default:\n"
15739                "}",
15740                InheritanceStyle);
15741   verifyFormat("switch (allBraces) {\n"
15742                "case 1: {\n"
15743                "  break;\n"
15744                "}\n"
15745                "case 2: {\n"
15746                "  [[fallthrough]];\n"
15747                "}\n"
15748                "default: {\n"
15749                "  break;\n"
15750                "}\n"
15751                "}",
15752                InheritanceStyle);
15753   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15754   verifyFormat("class Foooooooooooooooooooooo\n"
15755                "    : public aaaaaaaaaaaaaaaaaa,\n"
15756                "      public bbbbbbbbbbbbbbbbbb {\n"
15757                "}",
15758                InheritanceStyle);
15759   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15760   verifyFormat("class Foooooooooooooooooooooo:\n"
15761                "    public aaaaaaaaaaaaaaaaaa,\n"
15762                "    public bbbbbbbbbbbbbbbbbb {\n"
15763                "}",
15764                InheritanceStyle);
15765   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15766   verifyFormat("class Foooooooooooooooooooooo\n"
15767                "    : public aaaaaaaaaaaaaaaaaa\n"
15768                "    , public bbbbbbbbbbbbbbbbbb {\n"
15769                "}",
15770                InheritanceStyle);
15771   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15772   verifyFormat("class Foooooooooooooooooooooo\n"
15773                "    : public aaaaaaaaaaaaaaaaaa,\n"
15774                "      public bbbbbbbbbbbbbbbbbb {\n"
15775                "}",
15776                InheritanceStyle);
15777   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15778   verifyFormat("class Foooooooooooooooooooooo\n"
15779                ": public aaaaaaaaaaaaaaaaaa,\n"
15780                "  public bbbbbbbbbbbbbbbbbb {}",
15781                InheritanceStyle);
15782 
15783   FormatStyle ForLoopStyle = getLLVMStyle();
15784   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15785   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15786   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15787   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15788   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15789   verifyFormat("{\n"
15790                "label2:\n"
15791                "  int x = 0;\n"
15792                "}",
15793                ForLoopStyle);
15794   verifyFormat("switch (x) {\n"
15795                "case 1:\n"
15796                "default:\n"
15797                "}",
15798                ForLoopStyle);
15799   verifyFormat("switch (allBraces) {\n"
15800                "case 1: {\n"
15801                "  break;\n"
15802                "}\n"
15803                "case 2: {\n"
15804                "  [[fallthrough]];\n"
15805                "}\n"
15806                "default: {\n"
15807                "  break;\n"
15808                "}\n"
15809                "}",
15810                ForLoopStyle);
15811 
15812   FormatStyle CaseStyle = getLLVMStyle();
15813   CaseStyle.SpaceBeforeCaseColon = true;
15814   verifyFormat("class Foo : public Bar {};", CaseStyle);
15815   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15816   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15817   verifyFormat("int x = a ? b : c;", CaseStyle);
15818   verifyFormat("switch (x) {\n"
15819                "case 1 :\n"
15820                "default :\n"
15821                "}",
15822                CaseStyle);
15823   verifyFormat("switch (allBraces) {\n"
15824                "case 1 : {\n"
15825                "  break;\n"
15826                "}\n"
15827                "case 2 : {\n"
15828                "  [[fallthrough]];\n"
15829                "}\n"
15830                "default : {\n"
15831                "  break;\n"
15832                "}\n"
15833                "}",
15834                CaseStyle);
15835 
15836   FormatStyle NoSpaceStyle = getLLVMStyle();
15837   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15838   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15839   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15840   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15841   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15842   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15843   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15844   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15845   verifyFormat("{\n"
15846                "label3:\n"
15847                "  int x = 0;\n"
15848                "}",
15849                NoSpaceStyle);
15850   verifyFormat("switch (x) {\n"
15851                "case 1:\n"
15852                "default:\n"
15853                "}",
15854                NoSpaceStyle);
15855   verifyFormat("switch (allBraces) {\n"
15856                "case 1: {\n"
15857                "  break;\n"
15858                "}\n"
15859                "case 2: {\n"
15860                "  [[fallthrough]];\n"
15861                "}\n"
15862                "default: {\n"
15863                "  break;\n"
15864                "}\n"
15865                "}",
15866                NoSpaceStyle);
15867 
15868   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15869   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15870   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15871   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15872   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15873   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15874   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15875   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15876   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15877   verifyFormat("{\n"
15878                "label3:\n"
15879                "  int x = 0;\n"
15880                "}",
15881                InvertedSpaceStyle);
15882   verifyFormat("switch (x) {\n"
15883                "case 1 :\n"
15884                "case 2 : {\n"
15885                "  break;\n"
15886                "}\n"
15887                "default :\n"
15888                "  break;\n"
15889                "}",
15890                InvertedSpaceStyle);
15891   verifyFormat("switch (allBraces) {\n"
15892                "case 1 : {\n"
15893                "  break;\n"
15894                "}\n"
15895                "case 2 : {\n"
15896                "  [[fallthrough]];\n"
15897                "}\n"
15898                "default : {\n"
15899                "  break;\n"
15900                "}\n"
15901                "}",
15902                InvertedSpaceStyle);
15903 }
15904 
15905 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15906   FormatStyle Style = getLLVMStyle();
15907 
15908   Style.PointerAlignment = FormatStyle::PAS_Left;
15909   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15910   verifyFormat("void* const* x = NULL;", Style);
15911 
15912 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15913   do {                                                                         \
15914     Style.PointerAlignment = FormatStyle::Pointers;                            \
15915     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15916     verifyFormat(Code, Style);                                                 \
15917   } while (false)
15918 
15919   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15920   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15921   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15922 
15923   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15924   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15925   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15926 
15927   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15928   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15929   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15930 
15931   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15932   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15933   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15934 
15935   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15936   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15937                         SAPQ_Default);
15938   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15939                         SAPQ_Default);
15940 
15941   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15942   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15943                         SAPQ_Before);
15944   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15945                         SAPQ_Before);
15946 
15947   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15948   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15949   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15950                         SAPQ_After);
15951 
15952   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15953   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15954   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15955 
15956 #undef verifyQualifierSpaces
15957 
15958   FormatStyle Spaces = getLLVMStyle();
15959   Spaces.AttributeMacros.push_back("qualified");
15960   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15961   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
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   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15968   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15969   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15970   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15971   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15972   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15973 
15974   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15975   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15976   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15977   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15978   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15979   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15980   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15981   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15982   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15983   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15984   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15985   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15986   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15987   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15988   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15989 
15990   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15991   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15992   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15993   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15994   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15995   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15996   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15997   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15998 }
15999 
16000 TEST_F(FormatTest, AlignConsecutiveMacros) {
16001   FormatStyle Style = getLLVMStyle();
16002   Style.AlignConsecutiveAssignments.Enabled = true;
16003   Style.AlignConsecutiveDeclarations.Enabled = true;
16004 
16005   verifyFormat("#define a 3\n"
16006                "#define bbbb 4\n"
16007                "#define ccc (5)",
16008                Style);
16009 
16010   verifyFormat("#define f(x) (x * x)\n"
16011                "#define fff(x, y, z) (x * y + z)\n"
16012                "#define ffff(x, y) (x - y)",
16013                Style);
16014 
16015   verifyFormat("#define foo(x, y) (x + y)\n"
16016                "#define bar (5, 6)(2 + 2)",
16017                Style);
16018 
16019   verifyFormat("#define a 3\n"
16020                "#define bbbb 4\n"
16021                "#define ccc (5)\n"
16022                "#define f(x) (x * x)\n"
16023                "#define fff(x, y, z) (x * y + z)\n"
16024                "#define ffff(x, y) (x - y)",
16025                Style);
16026 
16027   Style.AlignConsecutiveMacros.Enabled = true;
16028   verifyFormat("#define a    3\n"
16029                "#define bbbb 4\n"
16030                "#define ccc  (5)",
16031                Style);
16032 
16033   verifyFormat("#define true  1\n"
16034                "#define false 0",
16035                Style);
16036 
16037   verifyFormat("#define f(x)         (x * x)\n"
16038                "#define fff(x, y, z) (x * y + z)\n"
16039                "#define ffff(x, y)   (x - y)",
16040                Style);
16041 
16042   verifyFormat("#define foo(x, y) (x + y)\n"
16043                "#define bar       (5, 6)(2 + 2)",
16044                Style);
16045 
16046   verifyFormat("#define a            3\n"
16047                "#define bbbb         4\n"
16048                "#define ccc          (5)\n"
16049                "#define f(x)         (x * x)\n"
16050                "#define fff(x, y, z) (x * y + z)\n"
16051                "#define ffff(x, y)   (x - y)",
16052                Style);
16053 
16054   verifyFormat("#define a         5\n"
16055                "#define foo(x, y) (x + y)\n"
16056                "#define CCC       (6)\n"
16057                "auto lambda = []() {\n"
16058                "  auto  ii = 0;\n"
16059                "  float j  = 0;\n"
16060                "  return 0;\n"
16061                "};\n"
16062                "int   i  = 0;\n"
16063                "float i2 = 0;\n"
16064                "auto  v  = type{\n"
16065                "    i = 1,   //\n"
16066                "    (i = 2), //\n"
16067                "    i = 3    //\n"
16068                "};",
16069                Style);
16070 
16071   Style.AlignConsecutiveMacros.Enabled = false;
16072   Style.ColumnLimit = 20;
16073 
16074   verifyFormat("#define a          \\\n"
16075                "  \"aabbbbbbbbbbbb\"\n"
16076                "#define D          \\\n"
16077                "  \"aabbbbbbbbbbbb\" \\\n"
16078                "  \"ccddeeeeeeeee\"\n"
16079                "#define B          \\\n"
16080                "  \"QQQQQQQQQQQQQ\"  \\\n"
16081                "  \"FFFFFFFFFFFFF\"  \\\n"
16082                "  \"LLLLLLLL\"\n",
16083                Style);
16084 
16085   Style.AlignConsecutiveMacros.Enabled = true;
16086   verifyFormat("#define a          \\\n"
16087                "  \"aabbbbbbbbbbbb\"\n"
16088                "#define D          \\\n"
16089                "  \"aabbbbbbbbbbbb\" \\\n"
16090                "  \"ccddeeeeeeeee\"\n"
16091                "#define B          \\\n"
16092                "  \"QQQQQQQQQQQQQ\"  \\\n"
16093                "  \"FFFFFFFFFFFFF\"  \\\n"
16094                "  \"LLLLLLLL\"\n",
16095                Style);
16096 
16097   // Test across comments
16098   Style.MaxEmptyLinesToKeep = 10;
16099   Style.ReflowComments = false;
16100   Style.AlignConsecutiveMacros.AcrossComments = true;
16101   EXPECT_EQ("#define a    3\n"
16102             "// line comment\n"
16103             "#define bbbb 4\n"
16104             "#define ccc  (5)",
16105             format("#define a 3\n"
16106                    "// line comment\n"
16107                    "#define bbbb 4\n"
16108                    "#define ccc (5)",
16109                    Style));
16110 
16111   EXPECT_EQ("#define a    3\n"
16112             "/* block comment */\n"
16113             "#define bbbb 4\n"
16114             "#define ccc  (5)",
16115             format("#define a  3\n"
16116                    "/* block comment */\n"
16117                    "#define bbbb 4\n"
16118                    "#define ccc (5)",
16119                    Style));
16120 
16121   EXPECT_EQ("#define a    3\n"
16122             "/* multi-line *\n"
16123             " * block comment */\n"
16124             "#define bbbb 4\n"
16125             "#define ccc  (5)",
16126             format("#define a 3\n"
16127                    "/* multi-line *\n"
16128                    " * block comment */\n"
16129                    "#define bbbb 4\n"
16130                    "#define ccc (5)",
16131                    Style));
16132 
16133   EXPECT_EQ("#define a    3\n"
16134             "// multi-line line comment\n"
16135             "//\n"
16136             "#define bbbb 4\n"
16137             "#define ccc  (5)",
16138             format("#define a  3\n"
16139                    "// multi-line line comment\n"
16140                    "//\n"
16141                    "#define bbbb 4\n"
16142                    "#define ccc (5)",
16143                    Style));
16144 
16145   EXPECT_EQ("#define a 3\n"
16146             "// empty lines still break.\n"
16147             "\n"
16148             "#define bbbb 4\n"
16149             "#define ccc  (5)",
16150             format("#define a     3\n"
16151                    "// empty lines still break.\n"
16152                    "\n"
16153                    "#define bbbb     4\n"
16154                    "#define ccc  (5)",
16155                    Style));
16156 
16157   // Test across empty lines
16158   Style.AlignConsecutiveMacros.AcrossComments = false;
16159   Style.AlignConsecutiveMacros.AcrossEmptyLines = true;
16160   EXPECT_EQ("#define a    3\n"
16161             "\n"
16162             "#define bbbb 4\n"
16163             "#define ccc  (5)",
16164             format("#define a 3\n"
16165                    "\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             "\n"
16174             "#define bbbb 4\n"
16175             "#define ccc  (5)",
16176             format("#define a        3\n"
16177                    "\n"
16178                    "\n"
16179                    "\n"
16180                    "#define bbbb 4\n"
16181                    "#define ccc (5)",
16182                    Style));
16183 
16184   EXPECT_EQ("#define a 3\n"
16185             "// comments should break alignment\n"
16186             "//\n"
16187             "#define bbbb 4\n"
16188             "#define ccc  (5)",
16189             format("#define a        3\n"
16190                    "// comments should break alignment\n"
16191                    "//\n"
16192                    "#define bbbb 4\n"
16193                    "#define ccc (5)",
16194                    Style));
16195 
16196   // Test across empty lines and comments
16197   Style.AlignConsecutiveMacros.AcrossComments = true;
16198   verifyFormat("#define a    3\n"
16199                "\n"
16200                "// line comment\n"
16201                "#define bbbb 4\n"
16202                "#define ccc  (5)",
16203                Style);
16204 
16205   EXPECT_EQ("#define a    3\n"
16206             "\n"
16207             "\n"
16208             "/* multi-line *\n"
16209             " * block comment */\n"
16210             "\n"
16211             "\n"
16212             "#define bbbb 4\n"
16213             "#define ccc  (5)",
16214             format("#define a 3\n"
16215                    "\n"
16216                    "\n"
16217                    "/* multi-line *\n"
16218                    " * block comment */\n"
16219                    "\n"
16220                    "\n"
16221                    "#define bbbb 4\n"
16222                    "#define ccc (5)",
16223                    Style));
16224 
16225   EXPECT_EQ("#define a    3\n"
16226             "\n"
16227             "\n"
16228             "/* multi-line *\n"
16229             " * block comment */\n"
16230             "\n"
16231             "\n"
16232             "#define bbbb 4\n"
16233             "#define ccc  (5)",
16234             format("#define a 3\n"
16235                    "\n"
16236                    "\n"
16237                    "/* multi-line *\n"
16238                    " * block comment */\n"
16239                    "\n"
16240                    "\n"
16241                    "#define bbbb 4\n"
16242                    "#define ccc       (5)",
16243                    Style));
16244 }
16245 
16246 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16247   FormatStyle Alignment = getLLVMStyle();
16248   Alignment.AlignConsecutiveMacros.Enabled = true;
16249   Alignment.AlignConsecutiveAssignments.Enabled = true;
16250   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16251 
16252   Alignment.MaxEmptyLinesToKeep = 10;
16253   /* Test alignment across empty lines */
16254   EXPECT_EQ("int a           = 5;\n"
16255             "\n"
16256             "int oneTwoThree = 123;",
16257             format("int a       = 5;\n"
16258                    "\n"
16259                    "int oneTwoThree= 123;",
16260                    Alignment));
16261   EXPECT_EQ("int a           = 5;\n"
16262             "int one         = 1;\n"
16263             "\n"
16264             "int oneTwoThree = 123;",
16265             format("int a = 5;\n"
16266                    "int one = 1;\n"
16267                    "\n"
16268                    "int oneTwoThree = 123;",
16269                    Alignment));
16270   EXPECT_EQ("int a           = 5;\n"
16271             "int one         = 1;\n"
16272             "\n"
16273             "int oneTwoThree = 123;\n"
16274             "int oneTwo      = 12;",
16275             format("int a = 5;\n"
16276                    "int one = 1;\n"
16277                    "\n"
16278                    "int oneTwoThree = 123;\n"
16279                    "int oneTwo = 12;",
16280                    Alignment));
16281 
16282   /* Test across comments */
16283   EXPECT_EQ("int a = 5;\n"
16284             "/* block comment */\n"
16285             "int oneTwoThree = 123;",
16286             format("int a = 5;\n"
16287                    "/* block comment */\n"
16288                    "int oneTwoThree=123;",
16289                    Alignment));
16290 
16291   EXPECT_EQ("int a = 5;\n"
16292             "// line comment\n"
16293             "int oneTwoThree = 123;",
16294             format("int a = 5;\n"
16295                    "// line comment\n"
16296                    "int oneTwoThree=123;",
16297                    Alignment));
16298 
16299   /* Test across comments and newlines */
16300   EXPECT_EQ("int a = 5;\n"
16301             "\n"
16302             "/* block comment */\n"
16303             "int oneTwoThree = 123;",
16304             format("int a = 5;\n"
16305                    "\n"
16306                    "/* block comment */\n"
16307                    "int oneTwoThree=123;",
16308                    Alignment));
16309 
16310   EXPECT_EQ("int a = 5;\n"
16311             "\n"
16312             "// line comment\n"
16313             "int oneTwoThree = 123;",
16314             format("int a = 5;\n"
16315                    "\n"
16316                    "// line comment\n"
16317                    "int oneTwoThree=123;",
16318                    Alignment));
16319 }
16320 
16321 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16322   FormatStyle Alignment = getLLVMStyle();
16323   Alignment.AlignConsecutiveDeclarations.Enabled = true;
16324   Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true;
16325   Alignment.AlignConsecutiveDeclarations.AcrossComments = true;
16326 
16327   Alignment.MaxEmptyLinesToKeep = 10;
16328   /* Test alignment across empty lines */
16329   EXPECT_EQ("int         a = 5;\n"
16330             "\n"
16331             "float const oneTwoThree = 123;",
16332             format("int a = 5;\n"
16333                    "\n"
16334                    "float const oneTwoThree = 123;",
16335                    Alignment));
16336   EXPECT_EQ("int         a = 5;\n"
16337             "float const one = 1;\n"
16338             "\n"
16339             "int         oneTwoThree = 123;",
16340             format("int a = 5;\n"
16341                    "float const one = 1;\n"
16342                    "\n"
16343                    "int oneTwoThree = 123;",
16344                    Alignment));
16345 
16346   /* Test across comments */
16347   EXPECT_EQ("float const a = 5;\n"
16348             "/* block comment */\n"
16349             "int         oneTwoThree = 123;",
16350             format("float const a = 5;\n"
16351                    "/* block comment */\n"
16352                    "int oneTwoThree=123;",
16353                    Alignment));
16354 
16355   EXPECT_EQ("float const a = 5;\n"
16356             "// line comment\n"
16357             "int         oneTwoThree = 123;",
16358             format("float const a = 5;\n"
16359                    "// line comment\n"
16360                    "int oneTwoThree=123;",
16361                    Alignment));
16362 
16363   /* Test across comments and newlines */
16364   EXPECT_EQ("float const a = 5;\n"
16365             "\n"
16366             "/* block comment */\n"
16367             "int         oneTwoThree = 123;",
16368             format("float const a = 5;\n"
16369                    "\n"
16370                    "/* block comment */\n"
16371                    "int         oneTwoThree=123;",
16372                    Alignment));
16373 
16374   EXPECT_EQ("float const a = 5;\n"
16375             "\n"
16376             "// line comment\n"
16377             "int         oneTwoThree = 123;",
16378             format("float const a = 5;\n"
16379                    "\n"
16380                    "// line comment\n"
16381                    "int oneTwoThree=123;",
16382                    Alignment));
16383 }
16384 
16385 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16386   FormatStyle Alignment = getLLVMStyle();
16387   Alignment.AlignConsecutiveBitFields.Enabled = true;
16388   Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true;
16389   Alignment.AlignConsecutiveBitFields.AcrossComments = true;
16390 
16391   Alignment.MaxEmptyLinesToKeep = 10;
16392   /* Test alignment across empty lines */
16393   EXPECT_EQ("int a            : 5;\n"
16394             "\n"
16395             "int longbitfield : 6;",
16396             format("int a : 5;\n"
16397                    "\n"
16398                    "int longbitfield : 6;",
16399                    Alignment));
16400   EXPECT_EQ("int a            : 5;\n"
16401             "int one          : 1;\n"
16402             "\n"
16403             "int longbitfield : 6;",
16404             format("int a : 5;\n"
16405                    "int one : 1;\n"
16406                    "\n"
16407                    "int longbitfield : 6;",
16408                    Alignment));
16409 
16410   /* Test across comments */
16411   EXPECT_EQ("int a            : 5;\n"
16412             "/* block comment */\n"
16413             "int longbitfield : 6;",
16414             format("int a : 5;\n"
16415                    "/* block comment */\n"
16416                    "int longbitfield : 6;",
16417                    Alignment));
16418   EXPECT_EQ("int a            : 5;\n"
16419             "int one          : 1;\n"
16420             "// line comment\n"
16421             "int longbitfield : 6;",
16422             format("int a : 5;\n"
16423                    "int one : 1;\n"
16424                    "// line comment\n"
16425                    "int longbitfield : 6;",
16426                    Alignment));
16427 
16428   /* Test across comments and newlines */
16429   EXPECT_EQ("int a            : 5;\n"
16430             "/* block comment */\n"
16431             "\n"
16432             "int longbitfield : 6;",
16433             format("int a : 5;\n"
16434                    "/* block comment */\n"
16435                    "\n"
16436                    "int longbitfield : 6;",
16437                    Alignment));
16438   EXPECT_EQ("int a            : 5;\n"
16439             "int one          : 1;\n"
16440             "\n"
16441             "// line comment\n"
16442             "\n"
16443             "int longbitfield : 6;",
16444             format("int a : 5;\n"
16445                    "int one : 1;\n"
16446                    "\n"
16447                    "// line comment \n"
16448                    "\n"
16449                    "int longbitfield : 6;",
16450                    Alignment));
16451 }
16452 
16453 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16454   FormatStyle Alignment = getLLVMStyle();
16455   Alignment.AlignConsecutiveMacros.Enabled = true;
16456   Alignment.AlignConsecutiveAssignments.Enabled = true;
16457   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16458 
16459   Alignment.MaxEmptyLinesToKeep = 10;
16460   /* Test alignment across empty lines */
16461   EXPECT_EQ("int a = 5;\n"
16462             "\n"
16463             "int oneTwoThree = 123;",
16464             format("int a       = 5;\n"
16465                    "\n"
16466                    "int oneTwoThree= 123;",
16467                    Alignment));
16468   EXPECT_EQ("int a   = 5;\n"
16469             "int one = 1;\n"
16470             "\n"
16471             "int oneTwoThree = 123;",
16472             format("int a = 5;\n"
16473                    "int one = 1;\n"
16474                    "\n"
16475                    "int oneTwoThree = 123;",
16476                    Alignment));
16477 
16478   /* Test across comments */
16479   EXPECT_EQ("int a           = 5;\n"
16480             "/* block comment */\n"
16481             "int oneTwoThree = 123;",
16482             format("int a = 5;\n"
16483                    "/* block comment */\n"
16484                    "int oneTwoThree=123;",
16485                    Alignment));
16486 
16487   EXPECT_EQ("int a           = 5;\n"
16488             "// line comment\n"
16489             "int oneTwoThree = 123;",
16490             format("int a = 5;\n"
16491                    "// line comment\n"
16492                    "int oneTwoThree=123;",
16493                    Alignment));
16494 
16495   EXPECT_EQ("int a           = 5;\n"
16496             "/*\n"
16497             " * multi-line block comment\n"
16498             " */\n"
16499             "int oneTwoThree = 123;",
16500             format("int a = 5;\n"
16501                    "/*\n"
16502                    " * multi-line block comment\n"
16503                    " */\n"
16504                    "int oneTwoThree=123;",
16505                    Alignment));
16506 
16507   EXPECT_EQ("int a           = 5;\n"
16508             "//\n"
16509             "// multi-line line comment\n"
16510             "//\n"
16511             "int oneTwoThree = 123;",
16512             format("int a = 5;\n"
16513                    "//\n"
16514                    "// multi-line line comment\n"
16515                    "//\n"
16516                    "int oneTwoThree=123;",
16517                    Alignment));
16518 
16519   /* Test across comments and newlines */
16520   EXPECT_EQ("int a = 5;\n"
16521             "\n"
16522             "/* block comment */\n"
16523             "int oneTwoThree = 123;",
16524             format("int a = 5;\n"
16525                    "\n"
16526                    "/* block comment */\n"
16527                    "int oneTwoThree=123;",
16528                    Alignment));
16529 
16530   EXPECT_EQ("int a = 5;\n"
16531             "\n"
16532             "// line comment\n"
16533             "int oneTwoThree = 123;",
16534             format("int a = 5;\n"
16535                    "\n"
16536                    "// line comment\n"
16537                    "int oneTwoThree=123;",
16538                    Alignment));
16539 }
16540 
16541 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16542   FormatStyle Alignment = getLLVMStyle();
16543   Alignment.AlignConsecutiveMacros.Enabled = true;
16544   Alignment.AlignConsecutiveAssignments.Enabled = true;
16545   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16546   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16547   verifyFormat("int a           = 5;\n"
16548                "int oneTwoThree = 123;",
16549                Alignment);
16550   verifyFormat("int a           = method();\n"
16551                "int oneTwoThree = 133;",
16552                Alignment);
16553   verifyFormat("a &= 5;\n"
16554                "bcd *= 5;\n"
16555                "ghtyf += 5;\n"
16556                "dvfvdb -= 5;\n"
16557                "a /= 5;\n"
16558                "vdsvsv %= 5;\n"
16559                "sfdbddfbdfbb ^= 5;\n"
16560                "dvsdsv |= 5;\n"
16561                "int dsvvdvsdvvv = 123;",
16562                Alignment);
16563   verifyFormat("int i = 1, j = 10;\n"
16564                "something = 2000;",
16565                Alignment);
16566   verifyFormat("something = 2000;\n"
16567                "int i = 1, j = 10;\n",
16568                Alignment);
16569   verifyFormat("something = 2000;\n"
16570                "another   = 911;\n"
16571                "int i = 1, j = 10;\n"
16572                "oneMore = 1;\n"
16573                "i       = 2;",
16574                Alignment);
16575   verifyFormat("int a   = 5;\n"
16576                "int one = 1;\n"
16577                "method();\n"
16578                "int oneTwoThree = 123;\n"
16579                "int oneTwo      = 12;",
16580                Alignment);
16581   verifyFormat("int oneTwoThree = 123;\n"
16582                "int oneTwo      = 12;\n"
16583                "method();\n",
16584                Alignment);
16585   verifyFormat("int oneTwoThree = 123; // comment\n"
16586                "int oneTwo      = 12;  // comment",
16587                Alignment);
16588 
16589   // Bug 25167
16590   /* Uncomment when fixed
16591     verifyFormat("#if A\n"
16592                  "#else\n"
16593                  "int aaaaaaaa = 12;\n"
16594                  "#endif\n"
16595                  "#if B\n"
16596                  "#else\n"
16597                  "int a = 12;\n"
16598                  "#endif\n",
16599                  Alignment);
16600     verifyFormat("enum foo {\n"
16601                  "#if A\n"
16602                  "#else\n"
16603                  "  aaaaaaaa = 12;\n"
16604                  "#endif\n"
16605                  "#if B\n"
16606                  "#else\n"
16607                  "  a = 12;\n"
16608                  "#endif\n"
16609                  "};\n",
16610                  Alignment);
16611   */
16612 
16613   Alignment.MaxEmptyLinesToKeep = 10;
16614   /* Test alignment across empty lines */
16615   EXPECT_EQ("int a           = 5;\n"
16616             "\n"
16617             "int oneTwoThree = 123;",
16618             format("int a       = 5;\n"
16619                    "\n"
16620                    "int oneTwoThree= 123;",
16621                    Alignment));
16622   EXPECT_EQ("int a           = 5;\n"
16623             "int one         = 1;\n"
16624             "\n"
16625             "int oneTwoThree = 123;",
16626             format("int a = 5;\n"
16627                    "int one = 1;\n"
16628                    "\n"
16629                    "int oneTwoThree = 123;",
16630                    Alignment));
16631   EXPECT_EQ("int a           = 5;\n"
16632             "int one         = 1;\n"
16633             "\n"
16634             "int oneTwoThree = 123;\n"
16635             "int oneTwo      = 12;",
16636             format("int a = 5;\n"
16637                    "int one = 1;\n"
16638                    "\n"
16639                    "int oneTwoThree = 123;\n"
16640                    "int oneTwo = 12;",
16641                    Alignment));
16642 
16643   /* Test across comments */
16644   EXPECT_EQ("int a           = 5;\n"
16645             "/* block comment */\n"
16646             "int oneTwoThree = 123;",
16647             format("int a = 5;\n"
16648                    "/* block comment */\n"
16649                    "int oneTwoThree=123;",
16650                    Alignment));
16651 
16652   EXPECT_EQ("int a           = 5;\n"
16653             "// line comment\n"
16654             "int oneTwoThree = 123;",
16655             format("int a = 5;\n"
16656                    "// line comment\n"
16657                    "int oneTwoThree=123;",
16658                    Alignment));
16659 
16660   /* Test across comments and newlines */
16661   EXPECT_EQ("int a           = 5;\n"
16662             "\n"
16663             "/* block comment */\n"
16664             "int oneTwoThree = 123;",
16665             format("int a = 5;\n"
16666                    "\n"
16667                    "/* block comment */\n"
16668                    "int oneTwoThree=123;",
16669                    Alignment));
16670 
16671   EXPECT_EQ("int a           = 5;\n"
16672             "\n"
16673             "// line comment\n"
16674             "int oneTwoThree = 123;",
16675             format("int a = 5;\n"
16676                    "\n"
16677                    "// line comment\n"
16678                    "int oneTwoThree=123;",
16679                    Alignment));
16680 
16681   EXPECT_EQ("int a           = 5;\n"
16682             "//\n"
16683             "// multi-line line comment\n"
16684             "//\n"
16685             "int oneTwoThree = 123;",
16686             format("int a = 5;\n"
16687                    "//\n"
16688                    "// multi-line line comment\n"
16689                    "//\n"
16690                    "int oneTwoThree=123;",
16691                    Alignment));
16692 
16693   EXPECT_EQ("int a           = 5;\n"
16694             "/*\n"
16695             " *  multi-line block comment\n"
16696             " */\n"
16697             "int oneTwoThree = 123;",
16698             format("int a = 5;\n"
16699                    "/*\n"
16700                    " *  multi-line block comment\n"
16701                    " */\n"
16702                    "int oneTwoThree=123;",
16703                    Alignment));
16704 
16705   EXPECT_EQ("int a           = 5;\n"
16706             "\n"
16707             "/* block comment */\n"
16708             "\n"
16709             "\n"
16710             "\n"
16711             "int oneTwoThree = 123;",
16712             format("int a = 5;\n"
16713                    "\n"
16714                    "/* block comment */\n"
16715                    "\n"
16716                    "\n"
16717                    "\n"
16718                    "int oneTwoThree=123;",
16719                    Alignment));
16720 
16721   EXPECT_EQ("int a           = 5;\n"
16722             "\n"
16723             "// line comment\n"
16724             "\n"
16725             "\n"
16726             "\n"
16727             "int oneTwoThree = 123;",
16728             format("int a = 5;\n"
16729                    "\n"
16730                    "// line comment\n"
16731                    "\n"
16732                    "\n"
16733                    "\n"
16734                    "int oneTwoThree=123;",
16735                    Alignment));
16736 
16737   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16738   verifyFormat("#define A \\\n"
16739                "  int aaaa       = 12; \\\n"
16740                "  int b          = 23; \\\n"
16741                "  int ccc        = 234; \\\n"
16742                "  int dddddddddd = 2345;",
16743                Alignment);
16744   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16745   verifyFormat("#define A               \\\n"
16746                "  int aaaa       = 12;  \\\n"
16747                "  int b          = 23;  \\\n"
16748                "  int ccc        = 234; \\\n"
16749                "  int dddddddddd = 2345;",
16750                Alignment);
16751   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16752   verifyFormat("#define A                                                      "
16753                "                \\\n"
16754                "  int aaaa       = 12;                                         "
16755                "                \\\n"
16756                "  int b          = 23;                                         "
16757                "                \\\n"
16758                "  int ccc        = 234;                                        "
16759                "                \\\n"
16760                "  int dddddddddd = 2345;",
16761                Alignment);
16762   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16763                "k = 4, int l = 5,\n"
16764                "                  int m = 6) {\n"
16765                "  int j      = 10;\n"
16766                "  otherThing = 1;\n"
16767                "}",
16768                Alignment);
16769   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16770                "  int i   = 1;\n"
16771                "  int j   = 2;\n"
16772                "  int big = 10000;\n"
16773                "}",
16774                Alignment);
16775   verifyFormat("class C {\n"
16776                "public:\n"
16777                "  int i            = 1;\n"
16778                "  virtual void f() = 0;\n"
16779                "};",
16780                Alignment);
16781   verifyFormat("int i = 1;\n"
16782                "if (SomeType t = getSomething()) {\n"
16783                "}\n"
16784                "int j   = 2;\n"
16785                "int big = 10000;",
16786                Alignment);
16787   verifyFormat("int j = 7;\n"
16788                "for (int k = 0; k < N; ++k) {\n"
16789                "}\n"
16790                "int j   = 2;\n"
16791                "int big = 10000;\n"
16792                "}",
16793                Alignment);
16794   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16795   verifyFormat("int i = 1;\n"
16796                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16797                "    = someLooooooooooooooooongFunction();\n"
16798                "int j = 2;",
16799                Alignment);
16800   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16801   verifyFormat("int i = 1;\n"
16802                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16803                "    someLooooooooooooooooongFunction();\n"
16804                "int j = 2;",
16805                Alignment);
16806 
16807   verifyFormat("auto lambda = []() {\n"
16808                "  auto i = 0;\n"
16809                "  return 0;\n"
16810                "};\n"
16811                "int i  = 0;\n"
16812                "auto v = type{\n"
16813                "    i = 1,   //\n"
16814                "    (i = 2), //\n"
16815                "    i = 3    //\n"
16816                "};",
16817                Alignment);
16818 
16819   verifyFormat(
16820       "int i      = 1;\n"
16821       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16822       "                          loooooooooooooooooooooongParameterB);\n"
16823       "int j      = 2;",
16824       Alignment);
16825 
16826   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16827                "          typename B   = very_long_type_name_1,\n"
16828                "          typename T_2 = very_long_type_name_2>\n"
16829                "auto foo() {}\n",
16830                Alignment);
16831   verifyFormat("int a, b = 1;\n"
16832                "int c  = 2;\n"
16833                "int dd = 3;\n",
16834                Alignment);
16835   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16836                "float b[1][] = {{3.f}};\n",
16837                Alignment);
16838   verifyFormat("for (int i = 0; i < 1; i++)\n"
16839                "  int x = 1;\n",
16840                Alignment);
16841   verifyFormat("for (i = 0; i < 1; i++)\n"
16842                "  x = 1;\n"
16843                "y = 1;\n",
16844                Alignment);
16845 
16846   Alignment.ReflowComments = true;
16847   Alignment.ColumnLimit = 50;
16848   EXPECT_EQ("int x   = 0;\n"
16849             "int yy  = 1; /// specificlennospace\n"
16850             "int zzz = 2;\n",
16851             format("int x   = 0;\n"
16852                    "int yy  = 1; ///specificlennospace\n"
16853                    "int zzz = 2;\n",
16854                    Alignment));
16855 }
16856 
16857 TEST_F(FormatTest, AlignCompoundAssignments) {
16858   FormatStyle Alignment = getLLVMStyle();
16859   Alignment.AlignConsecutiveAssignments.Enabled = true;
16860   Alignment.AlignConsecutiveAssignments.AlignCompound = true;
16861   Alignment.AlignConsecutiveAssignments.PadOperators = false;
16862   verifyFormat("sfdbddfbdfbb    = 5;\n"
16863                "dvsdsv          = 5;\n"
16864                "int dsvvdvsdvvv = 123;",
16865                Alignment);
16866   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16867                "dvsdsv         |= 5;\n"
16868                "int dsvvdvsdvvv = 123;",
16869                Alignment);
16870   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16871                "dvsdsv        <<= 5;\n"
16872                "int dsvvdvsdvvv = 123;",
16873                Alignment);
16874   // Test that `<=` is not treated as a compound assignment.
16875   verifyFormat("aa &= 5;\n"
16876                "b <= 10;\n"
16877                "c = 15;",
16878                Alignment);
16879   Alignment.AlignConsecutiveAssignments.PadOperators = true;
16880   verifyFormat("sfdbddfbdfbb    = 5;\n"
16881                "dvsdsv          = 5;\n"
16882                "int dsvvdvsdvvv = 123;",
16883                Alignment);
16884   verifyFormat("sfdbddfbdfbb    ^= 5;\n"
16885                "dvsdsv          |= 5;\n"
16886                "int dsvvdvsdvvv  = 123;",
16887                Alignment);
16888   verifyFormat("sfdbddfbdfbb     ^= 5;\n"
16889                "dvsdsv          <<= 5;\n"
16890                "int dsvvdvsdvvv   = 123;",
16891                Alignment);
16892   EXPECT_EQ("a   += 5;\n"
16893             "one  = 1;\n"
16894             "\n"
16895             "oneTwoThree = 123;\n",
16896             format("a += 5;\n"
16897                    "one = 1;\n"
16898                    "\n"
16899                    "oneTwoThree = 123;\n",
16900                    Alignment));
16901   EXPECT_EQ("a   += 5;\n"
16902             "one  = 1;\n"
16903             "//\n"
16904             "oneTwoThree = 123;\n",
16905             format("a += 5;\n"
16906                    "one = 1;\n"
16907                    "//\n"
16908                    "oneTwoThree = 123;\n",
16909                    Alignment));
16910   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16911   EXPECT_EQ("a           += 5;\n"
16912             "one          = 1;\n"
16913             "\n"
16914             "oneTwoThree  = 123;\n",
16915             format("a += 5;\n"
16916                    "one = 1;\n"
16917                    "\n"
16918                    "oneTwoThree = 123;\n",
16919                    Alignment));
16920   EXPECT_EQ("a   += 5;\n"
16921             "one  = 1;\n"
16922             "//\n"
16923             "oneTwoThree = 123;\n",
16924             format("a += 5;\n"
16925                    "one = 1;\n"
16926                    "//\n"
16927                    "oneTwoThree = 123;\n",
16928                    Alignment));
16929   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false;
16930   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16931   EXPECT_EQ("a   += 5;\n"
16932             "one  = 1;\n"
16933             "\n"
16934             "oneTwoThree = 123;\n",
16935             format("a += 5;\n"
16936                    "one = 1;\n"
16937                    "\n"
16938                    "oneTwoThree = 123;\n",
16939                    Alignment));
16940   EXPECT_EQ("a           += 5;\n"
16941             "one          = 1;\n"
16942             "//\n"
16943             "oneTwoThree  = 123;\n",
16944             format("a += 5;\n"
16945                    "one = 1;\n"
16946                    "//\n"
16947                    "oneTwoThree = 123;\n",
16948                    Alignment));
16949   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16950   EXPECT_EQ("a            += 5;\n"
16951             "one         >>= 1;\n"
16952             "\n"
16953             "oneTwoThree   = 123;\n",
16954             format("a += 5;\n"
16955                    "one >>= 1;\n"
16956                    "\n"
16957                    "oneTwoThree = 123;\n",
16958                    Alignment));
16959   EXPECT_EQ("a            += 5;\n"
16960             "one           = 1;\n"
16961             "//\n"
16962             "oneTwoThree <<= 123;\n",
16963             format("a += 5;\n"
16964                    "one = 1;\n"
16965                    "//\n"
16966                    "oneTwoThree <<= 123;\n",
16967                    Alignment));
16968 }
16969 
16970 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16971   FormatStyle Alignment = getLLVMStyle();
16972   Alignment.AlignConsecutiveMacros.Enabled = true;
16973   verifyFormat("int a = 5;\n"
16974                "int oneTwoThree = 123;",
16975                Alignment);
16976   verifyFormat("int a = 5;\n"
16977                "int oneTwoThree = 123;",
16978                Alignment);
16979 
16980   Alignment.AlignConsecutiveAssignments.Enabled = true;
16981   verifyFormat("int a           = 5;\n"
16982                "int oneTwoThree = 123;",
16983                Alignment);
16984   verifyFormat("int a           = method();\n"
16985                "int oneTwoThree = 133;",
16986                Alignment);
16987   verifyFormat("aa <= 5;\n"
16988                "a &= 5;\n"
16989                "bcd *= 5;\n"
16990                "ghtyf += 5;\n"
16991                "dvfvdb -= 5;\n"
16992                "a /= 5;\n"
16993                "vdsvsv %= 5;\n"
16994                "sfdbddfbdfbb ^= 5;\n"
16995                "dvsdsv |= 5;\n"
16996                "int dsvvdvsdvvv = 123;",
16997                Alignment);
16998   verifyFormat("int i = 1, j = 10;\n"
16999                "something = 2000;",
17000                Alignment);
17001   verifyFormat("something = 2000;\n"
17002                "int i = 1, j = 10;\n",
17003                Alignment);
17004   verifyFormat("something = 2000;\n"
17005                "another   = 911;\n"
17006                "int i = 1, j = 10;\n"
17007                "oneMore = 1;\n"
17008                "i       = 2;",
17009                Alignment);
17010   verifyFormat("int a   = 5;\n"
17011                "int one = 1;\n"
17012                "method();\n"
17013                "int oneTwoThree = 123;\n"
17014                "int oneTwo      = 12;",
17015                Alignment);
17016   verifyFormat("int oneTwoThree = 123;\n"
17017                "int oneTwo      = 12;\n"
17018                "method();\n",
17019                Alignment);
17020   verifyFormat("int oneTwoThree = 123; // comment\n"
17021                "int oneTwo      = 12;  // comment",
17022                Alignment);
17023   verifyFormat("int f()         = default;\n"
17024                "int &operator() = default;\n"
17025                "int &operator=() {",
17026                Alignment);
17027   verifyFormat("int f()         = delete;\n"
17028                "int &operator() = delete;\n"
17029                "int &operator=() {",
17030                Alignment);
17031   verifyFormat("int f()         = default; // comment\n"
17032                "int &operator() = default; // comment\n"
17033                "int &operator=() {",
17034                Alignment);
17035   verifyFormat("int f()         = default;\n"
17036                "int &operator() = default;\n"
17037                "int &operator==() {",
17038                Alignment);
17039   verifyFormat("int f()         = default;\n"
17040                "int &operator() = default;\n"
17041                "int &operator<=() {",
17042                Alignment);
17043   verifyFormat("int f()         = default;\n"
17044                "int &operator() = default;\n"
17045                "int &operator!=() {",
17046                Alignment);
17047   verifyFormat("int f()         = default;\n"
17048                "int &operator() = default;\n"
17049                "int &operator=();",
17050                Alignment);
17051   verifyFormat("int f()         = delete;\n"
17052                "int &operator() = delete;\n"
17053                "int &operator=();",
17054                Alignment);
17055   verifyFormat("/* long long padding */ int f() = default;\n"
17056                "int &operator()                 = default;\n"
17057                "int &operator/**/ =();",
17058                Alignment);
17059   // https://llvm.org/PR33697
17060   FormatStyle AlignmentWithPenalty = getLLVMStyle();
17061   AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true;
17062   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
17063   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
17064                "  void f() = delete;\n"
17065                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
17066                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
17067                "};\n",
17068                AlignmentWithPenalty);
17069 
17070   // Bug 25167
17071   /* Uncomment when fixed
17072     verifyFormat("#if A\n"
17073                  "#else\n"
17074                  "int aaaaaaaa = 12;\n"
17075                  "#endif\n"
17076                  "#if B\n"
17077                  "#else\n"
17078                  "int a = 12;\n"
17079                  "#endif\n",
17080                  Alignment);
17081     verifyFormat("enum foo {\n"
17082                  "#if A\n"
17083                  "#else\n"
17084                  "  aaaaaaaa = 12;\n"
17085                  "#endif\n"
17086                  "#if B\n"
17087                  "#else\n"
17088                  "  a = 12;\n"
17089                  "#endif\n"
17090                  "};\n",
17091                  Alignment);
17092   */
17093 
17094   EXPECT_EQ("int a = 5;\n"
17095             "\n"
17096             "int oneTwoThree = 123;",
17097             format("int a       = 5;\n"
17098                    "\n"
17099                    "int oneTwoThree= 123;",
17100                    Alignment));
17101   EXPECT_EQ("int a   = 5;\n"
17102             "int one = 1;\n"
17103             "\n"
17104             "int oneTwoThree = 123;",
17105             format("int a = 5;\n"
17106                    "int one = 1;\n"
17107                    "\n"
17108                    "int oneTwoThree = 123;",
17109                    Alignment));
17110   EXPECT_EQ("int a   = 5;\n"
17111             "int one = 1;\n"
17112             "\n"
17113             "int oneTwoThree = 123;\n"
17114             "int oneTwo      = 12;",
17115             format("int a = 5;\n"
17116                    "int one = 1;\n"
17117                    "\n"
17118                    "int oneTwoThree = 123;\n"
17119                    "int oneTwo = 12;",
17120                    Alignment));
17121   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17122   verifyFormat("#define A \\\n"
17123                "  int aaaa       = 12; \\\n"
17124                "  int b          = 23; \\\n"
17125                "  int ccc        = 234; \\\n"
17126                "  int dddddddddd = 2345;",
17127                Alignment);
17128   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17129   verifyFormat("#define A               \\\n"
17130                "  int aaaa       = 12;  \\\n"
17131                "  int b          = 23;  \\\n"
17132                "  int ccc        = 234; \\\n"
17133                "  int dddddddddd = 2345;",
17134                Alignment);
17135   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17136   verifyFormat("#define A                                                      "
17137                "                \\\n"
17138                "  int aaaa       = 12;                                         "
17139                "                \\\n"
17140                "  int b          = 23;                                         "
17141                "                \\\n"
17142                "  int ccc        = 234;                                        "
17143                "                \\\n"
17144                "  int dddddddddd = 2345;",
17145                Alignment);
17146   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17147                "k = 4, int l = 5,\n"
17148                "                  int m = 6) {\n"
17149                "  int j      = 10;\n"
17150                "  otherThing = 1;\n"
17151                "}",
17152                Alignment);
17153   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17154                "  int i   = 1;\n"
17155                "  int j   = 2;\n"
17156                "  int big = 10000;\n"
17157                "}",
17158                Alignment);
17159   verifyFormat("class C {\n"
17160                "public:\n"
17161                "  int i            = 1;\n"
17162                "  virtual void f() = 0;\n"
17163                "};",
17164                Alignment);
17165   verifyFormat("int i = 1;\n"
17166                "if (SomeType t = getSomething()) {\n"
17167                "}\n"
17168                "int j   = 2;\n"
17169                "int big = 10000;",
17170                Alignment);
17171   verifyFormat("int j = 7;\n"
17172                "for (int k = 0; k < N; ++k) {\n"
17173                "}\n"
17174                "int j   = 2;\n"
17175                "int big = 10000;\n"
17176                "}",
17177                Alignment);
17178   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17179   verifyFormat("int i = 1;\n"
17180                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17181                "    = someLooooooooooooooooongFunction();\n"
17182                "int j = 2;",
17183                Alignment);
17184   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17185   verifyFormat("int i = 1;\n"
17186                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17187                "    someLooooooooooooooooongFunction();\n"
17188                "int j = 2;",
17189                Alignment);
17190 
17191   verifyFormat("auto lambda = []() {\n"
17192                "  auto i = 0;\n"
17193                "  return 0;\n"
17194                "};\n"
17195                "int i  = 0;\n"
17196                "auto v = type{\n"
17197                "    i = 1,   //\n"
17198                "    (i = 2), //\n"
17199                "    i = 3    //\n"
17200                "};",
17201                Alignment);
17202 
17203   verifyFormat(
17204       "int i      = 1;\n"
17205       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17206       "                          loooooooooooooooooooooongParameterB);\n"
17207       "int j      = 2;",
17208       Alignment);
17209 
17210   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17211                "          typename B   = very_long_type_name_1,\n"
17212                "          typename T_2 = very_long_type_name_2>\n"
17213                "auto foo() {}\n",
17214                Alignment);
17215   verifyFormat("int a, b = 1;\n"
17216                "int c  = 2;\n"
17217                "int dd = 3;\n",
17218                Alignment);
17219   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17220                "float b[1][] = {{3.f}};\n",
17221                Alignment);
17222   verifyFormat("for (int i = 0; i < 1; i++)\n"
17223                "  int x = 1;\n",
17224                Alignment);
17225   verifyFormat("for (i = 0; i < 1; i++)\n"
17226                "  x = 1;\n"
17227                "y = 1;\n",
17228                Alignment);
17229 
17230   EXPECT_EQ(Alignment.ReflowComments, true);
17231   Alignment.ColumnLimit = 50;
17232   EXPECT_EQ("int x   = 0;\n"
17233             "int yy  = 1; /// specificlennospace\n"
17234             "int zzz = 2;\n",
17235             format("int x   = 0;\n"
17236                    "int yy  = 1; ///specificlennospace\n"
17237                    "int zzz = 2;\n",
17238                    Alignment));
17239 
17240   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17241                "auto b                     = [] {\n"
17242                "  f();\n"
17243                "  return;\n"
17244                "};",
17245                Alignment);
17246   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17247                "auto b                     = g([] {\n"
17248                "  f();\n"
17249                "  return;\n"
17250                "});",
17251                Alignment);
17252   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17253                "auto b                     = g(param, [] {\n"
17254                "  f();\n"
17255                "  return;\n"
17256                "});",
17257                Alignment);
17258   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17259                "auto b                     = [] {\n"
17260                "  if (condition) {\n"
17261                "    return;\n"
17262                "  }\n"
17263                "};",
17264                Alignment);
17265 
17266   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17267                "           ccc ? aaaaa : bbbbb,\n"
17268                "           dddddddddddddddddddddddddd);",
17269                Alignment);
17270   // FIXME: https://llvm.org/PR53497
17271   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
17272   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17273   //              "    ccc ? aaaaa : bbbbb,\n"
17274   //              "    dddddddddddddddddddddddddd);",
17275   //              Alignment);
17276 }
17277 
17278 TEST_F(FormatTest, AlignConsecutiveBitFields) {
17279   FormatStyle Alignment = getLLVMStyle();
17280   Alignment.AlignConsecutiveBitFields.Enabled = true;
17281   verifyFormat("int const a     : 5;\n"
17282                "int oneTwoThree : 23;",
17283                Alignment);
17284 
17285   // Initializers are allowed starting with c++2a
17286   verifyFormat("int const a     : 5 = 1;\n"
17287                "int oneTwoThree : 23 = 0;",
17288                Alignment);
17289 
17290   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17291   verifyFormat("int const a           : 5;\n"
17292                "int       oneTwoThree : 23;",
17293                Alignment);
17294 
17295   verifyFormat("int const a           : 5;  // comment\n"
17296                "int       oneTwoThree : 23; // comment",
17297                Alignment);
17298 
17299   verifyFormat("int const a           : 5 = 1;\n"
17300                "int       oneTwoThree : 23 = 0;",
17301                Alignment);
17302 
17303   Alignment.AlignConsecutiveAssignments.Enabled = true;
17304   verifyFormat("int const a           : 5  = 1;\n"
17305                "int       oneTwoThree : 23 = 0;",
17306                Alignment);
17307   verifyFormat("int const a           : 5  = {1};\n"
17308                "int       oneTwoThree : 23 = 0;",
17309                Alignment);
17310 
17311   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
17312   verifyFormat("int const a          :5;\n"
17313                "int       oneTwoThree:23;",
17314                Alignment);
17315 
17316   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
17317   verifyFormat("int const a           :5;\n"
17318                "int       oneTwoThree :23;",
17319                Alignment);
17320 
17321   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
17322   verifyFormat("int const a          : 5;\n"
17323                "int       oneTwoThree: 23;",
17324                Alignment);
17325 
17326   // Known limitations: ':' is only recognized as a bitfield colon when
17327   // followed by a number.
17328   /*
17329   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
17330                "int a           : 5;",
17331                Alignment);
17332   */
17333 }
17334 
17335 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
17336   FormatStyle Alignment = getLLVMStyle();
17337   Alignment.AlignConsecutiveMacros.Enabled = true;
17338   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17339   verifyFormat("float const a = 5;\n"
17340                "int oneTwoThree = 123;",
17341                Alignment);
17342   verifyFormat("int a = 5;\n"
17343                "float const oneTwoThree = 123;",
17344                Alignment);
17345 
17346   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17347   verifyFormat("float const a = 5;\n"
17348                "int         oneTwoThree = 123;",
17349                Alignment);
17350   verifyFormat("int         a = method();\n"
17351                "float const oneTwoThree = 133;",
17352                Alignment);
17353   verifyFormat("int i = 1, j = 10;\n"
17354                "something = 2000;",
17355                Alignment);
17356   verifyFormat("something = 2000;\n"
17357                "int i = 1, j = 10;\n",
17358                Alignment);
17359   verifyFormat("float      something = 2000;\n"
17360                "double     another = 911;\n"
17361                "int        i = 1, j = 10;\n"
17362                "const int *oneMore = 1;\n"
17363                "unsigned   i = 2;",
17364                Alignment);
17365   verifyFormat("float a = 5;\n"
17366                "int   one = 1;\n"
17367                "method();\n"
17368                "const double       oneTwoThree = 123;\n"
17369                "const unsigned int oneTwo = 12;",
17370                Alignment);
17371   verifyFormat("int      oneTwoThree{0}; // comment\n"
17372                "unsigned oneTwo;         // comment",
17373                Alignment);
17374   verifyFormat("unsigned int       *a;\n"
17375                "int                *b;\n"
17376                "unsigned int Const *c;\n"
17377                "unsigned int const *d;\n"
17378                "unsigned int Const &e;\n"
17379                "unsigned int const &f;",
17380                Alignment);
17381   verifyFormat("Const unsigned int *c;\n"
17382                "const unsigned int *d;\n"
17383                "Const unsigned int &e;\n"
17384                "const unsigned int &f;\n"
17385                "const unsigned      g;\n"
17386                "Const unsigned      h;",
17387                Alignment);
17388   EXPECT_EQ("float const a = 5;\n"
17389             "\n"
17390             "int oneTwoThree = 123;",
17391             format("float const   a = 5;\n"
17392                    "\n"
17393                    "int           oneTwoThree= 123;",
17394                    Alignment));
17395   EXPECT_EQ("float a = 5;\n"
17396             "int   one = 1;\n"
17397             "\n"
17398             "unsigned oneTwoThree = 123;",
17399             format("float    a = 5;\n"
17400                    "int      one = 1;\n"
17401                    "\n"
17402                    "unsigned oneTwoThree = 123;",
17403                    Alignment));
17404   EXPECT_EQ("float a = 5;\n"
17405             "int   one = 1;\n"
17406             "\n"
17407             "unsigned oneTwoThree = 123;\n"
17408             "int      oneTwo = 12;",
17409             format("float    a = 5;\n"
17410                    "int one = 1;\n"
17411                    "\n"
17412                    "unsigned oneTwoThree = 123;\n"
17413                    "int oneTwo = 12;",
17414                    Alignment));
17415   // Function prototype alignment
17416   verifyFormat("int    a();\n"
17417                "double b();",
17418                Alignment);
17419   verifyFormat("int    a(int x);\n"
17420                "double b();",
17421                Alignment);
17422   unsigned OldColumnLimit = Alignment.ColumnLimit;
17423   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17424   // otherwise the function parameters will be re-flowed onto a single line.
17425   Alignment.ColumnLimit = 0;
17426   EXPECT_EQ("int    a(int   x,\n"
17427             "         float y);\n"
17428             "double b(int    x,\n"
17429             "         double y);",
17430             format("int a(int x,\n"
17431                    " float y);\n"
17432                    "double b(int x,\n"
17433                    " double y);",
17434                    Alignment));
17435   // This ensures that function parameters of function declarations are
17436   // correctly indented when their owning functions are indented.
17437   // The failure case here is for 'double y' to not be indented enough.
17438   EXPECT_EQ("double a(int x);\n"
17439             "int    b(int    y,\n"
17440             "         double z);",
17441             format("double a(int x);\n"
17442                    "int b(int y,\n"
17443                    " double z);",
17444                    Alignment));
17445   // Set ColumnLimit low so that we induce wrapping immediately after
17446   // the function name and opening paren.
17447   Alignment.ColumnLimit = 13;
17448   verifyFormat("int function(\n"
17449                "    int  x,\n"
17450                "    bool y);",
17451                Alignment);
17452   Alignment.ColumnLimit = OldColumnLimit;
17453   // Ensure function pointers don't screw up recursive alignment
17454   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17455                "double b();",
17456                Alignment);
17457   Alignment.AlignConsecutiveAssignments.Enabled = true;
17458   // Ensure recursive alignment is broken by function braces, so that the
17459   // "a = 1" does not align with subsequent assignments inside the function
17460   // body.
17461   verifyFormat("int func(int a = 1) {\n"
17462                "  int b  = 2;\n"
17463                "  int cc = 3;\n"
17464                "}",
17465                Alignment);
17466   verifyFormat("float      something = 2000;\n"
17467                "double     another   = 911;\n"
17468                "int        i = 1, j = 10;\n"
17469                "const int *oneMore = 1;\n"
17470                "unsigned   i       = 2;",
17471                Alignment);
17472   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17473                "unsigned oneTwo      = 0;   // comment",
17474                Alignment);
17475   // Make sure that scope is correctly tracked, in the absence of braces
17476   verifyFormat("for (int i = 0; i < n; i++)\n"
17477                "  j = i;\n"
17478                "double x = 1;\n",
17479                Alignment);
17480   verifyFormat("if (int i = 0)\n"
17481                "  j = i;\n"
17482                "double x = 1;\n",
17483                Alignment);
17484   // Ensure operator[] and operator() are comprehended
17485   verifyFormat("struct test {\n"
17486                "  long long int foo();\n"
17487                "  int           operator[](int a);\n"
17488                "  double        bar();\n"
17489                "};\n",
17490                Alignment);
17491   verifyFormat("struct test {\n"
17492                "  long long int foo();\n"
17493                "  int           operator()(int a);\n"
17494                "  double        bar();\n"
17495                "};\n",
17496                Alignment);
17497   // http://llvm.org/PR52914
17498   verifyFormat("char *a[]     = {\"a\", // comment\n"
17499                "                 \"bb\"};\n"
17500                "int   bbbbbbb = 0;",
17501                Alignment);
17502 
17503   // PAS_Right
17504   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17505             "  int const i   = 1;\n"
17506             "  int      *j   = 2;\n"
17507             "  int       big = 10000;\n"
17508             "\n"
17509             "  unsigned oneTwoThree = 123;\n"
17510             "  int      oneTwo      = 12;\n"
17511             "  method();\n"
17512             "  float k  = 2;\n"
17513             "  int   ll = 10000;\n"
17514             "}",
17515             format("void SomeFunction(int parameter= 0) {\n"
17516                    " int const  i= 1;\n"
17517                    "  int *j=2;\n"
17518                    " int big  =  10000;\n"
17519                    "\n"
17520                    "unsigned oneTwoThree  =123;\n"
17521                    "int oneTwo = 12;\n"
17522                    "  method();\n"
17523                    "float k= 2;\n"
17524                    "int ll=10000;\n"
17525                    "}",
17526                    Alignment));
17527   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17528             "  int const i   = 1;\n"
17529             "  int     **j   = 2, ***k;\n"
17530             "  int      &k   = i;\n"
17531             "  int     &&l   = i + j;\n"
17532             "  int       big = 10000;\n"
17533             "\n"
17534             "  unsigned oneTwoThree = 123;\n"
17535             "  int      oneTwo      = 12;\n"
17536             "  method();\n"
17537             "  float k  = 2;\n"
17538             "  int   ll = 10000;\n"
17539             "}",
17540             format("void SomeFunction(int parameter= 0) {\n"
17541                    " int const  i= 1;\n"
17542                    "  int **j=2,***k;\n"
17543                    "int &k=i;\n"
17544                    "int &&l=i+j;\n"
17545                    " int big  =  10000;\n"
17546                    "\n"
17547                    "unsigned oneTwoThree  =123;\n"
17548                    "int oneTwo = 12;\n"
17549                    "  method();\n"
17550                    "float k= 2;\n"
17551                    "int ll=10000;\n"
17552                    "}",
17553                    Alignment));
17554   // variables are aligned at their name, pointers are at the right most
17555   // position
17556   verifyFormat("int   *a;\n"
17557                "int  **b;\n"
17558                "int ***c;\n"
17559                "int    foobar;\n",
17560                Alignment);
17561 
17562   // PAS_Left
17563   FormatStyle AlignmentLeft = Alignment;
17564   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17565   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17566             "  int const i   = 1;\n"
17567             "  int*      j   = 2;\n"
17568             "  int       big = 10000;\n"
17569             "\n"
17570             "  unsigned oneTwoThree = 123;\n"
17571             "  int      oneTwo      = 12;\n"
17572             "  method();\n"
17573             "  float k  = 2;\n"
17574             "  int   ll = 10000;\n"
17575             "}",
17576             format("void SomeFunction(int parameter= 0) {\n"
17577                    " int const  i= 1;\n"
17578                    "  int *j=2;\n"
17579                    " int big  =  10000;\n"
17580                    "\n"
17581                    "unsigned oneTwoThree  =123;\n"
17582                    "int oneTwo = 12;\n"
17583                    "  method();\n"
17584                    "float k= 2;\n"
17585                    "int ll=10000;\n"
17586                    "}",
17587                    AlignmentLeft));
17588   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17589             "  int const i   = 1;\n"
17590             "  int**     j   = 2;\n"
17591             "  int&      k   = i;\n"
17592             "  int&&     l   = i + j;\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 &k=i;\n"
17605                    "int &&l=i+j;\n"
17606                    " int big  =  10000;\n"
17607                    "\n"
17608                    "unsigned oneTwoThree  =123;\n"
17609                    "int oneTwo = 12;\n"
17610                    "  method();\n"
17611                    "float k= 2;\n"
17612                    "int ll=10000;\n"
17613                    "}",
17614                    AlignmentLeft));
17615   // variables are aligned at their name, pointers are at the left most position
17616   verifyFormat("int*   a;\n"
17617                "int**  b;\n"
17618                "int*** c;\n"
17619                "int    foobar;\n",
17620                AlignmentLeft);
17621 
17622   // PAS_Middle
17623   FormatStyle AlignmentMiddle = Alignment;
17624   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17625   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17626             "  int const i   = 1;\n"
17627             "  int *     j   = 2;\n"
17628             "  int       big = 10000;\n"
17629             "\n"
17630             "  unsigned oneTwoThree = 123;\n"
17631             "  int      oneTwo      = 12;\n"
17632             "  method();\n"
17633             "  float k  = 2;\n"
17634             "  int   ll = 10000;\n"
17635             "}",
17636             format("void SomeFunction(int parameter= 0) {\n"
17637                    " int const  i= 1;\n"
17638                    "  int *j=2;\n"
17639                    " int big  =  10000;\n"
17640                    "\n"
17641                    "unsigned oneTwoThree  =123;\n"
17642                    "int oneTwo = 12;\n"
17643                    "  method();\n"
17644                    "float k= 2;\n"
17645                    "int ll=10000;\n"
17646                    "}",
17647                    AlignmentMiddle));
17648   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17649             "  int const i   = 1;\n"
17650             "  int **    j   = 2, ***k;\n"
17651             "  int &     k   = i;\n"
17652             "  int &&    l   = i + j;\n"
17653             "  int       big = 10000;\n"
17654             "\n"
17655             "  unsigned oneTwoThree = 123;\n"
17656             "  int      oneTwo      = 12;\n"
17657             "  method();\n"
17658             "  float k  = 2;\n"
17659             "  int   ll = 10000;\n"
17660             "}",
17661             format("void SomeFunction(int parameter= 0) {\n"
17662                    " int const  i= 1;\n"
17663                    "  int **j=2,***k;\n"
17664                    "int &k=i;\n"
17665                    "int &&l=i+j;\n"
17666                    " int big  =  10000;\n"
17667                    "\n"
17668                    "unsigned oneTwoThree  =123;\n"
17669                    "int oneTwo = 12;\n"
17670                    "  method();\n"
17671                    "float k= 2;\n"
17672                    "int ll=10000;\n"
17673                    "}",
17674                    AlignmentMiddle));
17675   // variables are aligned at their name, pointers are in the middle
17676   verifyFormat("int *   a;\n"
17677                "int *   b;\n"
17678                "int *** c;\n"
17679                "int     foobar;\n",
17680                AlignmentMiddle);
17681 
17682   Alignment.AlignConsecutiveAssignments.Enabled = false;
17683   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17684   verifyFormat("#define A \\\n"
17685                "  int       aaaa = 12; \\\n"
17686                "  float     b = 23; \\\n"
17687                "  const int ccc = 234; \\\n"
17688                "  unsigned  dddddddddd = 2345;",
17689                Alignment);
17690   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17691   verifyFormat("#define A              \\\n"
17692                "  int       aaaa = 12; \\\n"
17693                "  float     b = 23;    \\\n"
17694                "  const int ccc = 234; \\\n"
17695                "  unsigned  dddddddddd = 2345;",
17696                Alignment);
17697   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17698   Alignment.ColumnLimit = 30;
17699   verifyFormat("#define A                    \\\n"
17700                "  int       aaaa = 12;       \\\n"
17701                "  float     b = 23;          \\\n"
17702                "  const int ccc = 234;       \\\n"
17703                "  int       dddddddddd = 2345;",
17704                Alignment);
17705   Alignment.ColumnLimit = 80;
17706   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17707                "k = 4, int l = 5,\n"
17708                "                  int m = 6) {\n"
17709                "  const int j = 10;\n"
17710                "  otherThing = 1;\n"
17711                "}",
17712                Alignment);
17713   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17714                "  int const i = 1;\n"
17715                "  int      *j = 2;\n"
17716                "  int       big = 10000;\n"
17717                "}",
17718                Alignment);
17719   verifyFormat("class C {\n"
17720                "public:\n"
17721                "  int          i = 1;\n"
17722                "  virtual void f() = 0;\n"
17723                "};",
17724                Alignment);
17725   verifyFormat("float i = 1;\n"
17726                "if (SomeType t = getSomething()) {\n"
17727                "}\n"
17728                "const unsigned j = 2;\n"
17729                "int            big = 10000;",
17730                Alignment);
17731   verifyFormat("float j = 7;\n"
17732                "for (int k = 0; k < N; ++k) {\n"
17733                "}\n"
17734                "unsigned j = 2;\n"
17735                "int      big = 10000;\n"
17736                "}",
17737                Alignment);
17738   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17739   verifyFormat("float              i = 1;\n"
17740                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17741                "    = someLooooooooooooooooongFunction();\n"
17742                "int j = 2;",
17743                Alignment);
17744   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17745   verifyFormat("int                i = 1;\n"
17746                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17747                "    someLooooooooooooooooongFunction();\n"
17748                "int j = 2;",
17749                Alignment);
17750 
17751   Alignment.AlignConsecutiveAssignments.Enabled = true;
17752   verifyFormat("auto lambda = []() {\n"
17753                "  auto  ii = 0;\n"
17754                "  float j  = 0;\n"
17755                "  return 0;\n"
17756                "};\n"
17757                "int   i  = 0;\n"
17758                "float i2 = 0;\n"
17759                "auto  v  = type{\n"
17760                "    i = 1,   //\n"
17761                "    (i = 2), //\n"
17762                "    i = 3    //\n"
17763                "};",
17764                Alignment);
17765   Alignment.AlignConsecutiveAssignments.Enabled = false;
17766 
17767   verifyFormat(
17768       "int      i = 1;\n"
17769       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17770       "                          loooooooooooooooooooooongParameterB);\n"
17771       "int      j = 2;",
17772       Alignment);
17773 
17774   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17775   // We expect declarations and assignments to align, as long as it doesn't
17776   // exceed the column limit, starting a new alignment sequence whenever it
17777   // happens.
17778   Alignment.AlignConsecutiveAssignments.Enabled = true;
17779   Alignment.ColumnLimit = 30;
17780   verifyFormat("float    ii              = 1;\n"
17781                "unsigned j               = 2;\n"
17782                "int someVerylongVariable = 1;\n"
17783                "AnotherLongType  ll = 123456;\n"
17784                "VeryVeryLongType k  = 2;\n"
17785                "int              myvar = 1;",
17786                Alignment);
17787   Alignment.ColumnLimit = 80;
17788   Alignment.AlignConsecutiveAssignments.Enabled = false;
17789 
17790   verifyFormat(
17791       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17792       "          typename LongType, typename B>\n"
17793       "auto foo() {}\n",
17794       Alignment);
17795   verifyFormat("float a, b = 1;\n"
17796                "int   c = 2;\n"
17797                "int   dd = 3;\n",
17798                Alignment);
17799   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17800                "float b[1][] = {{3.f}};\n",
17801                Alignment);
17802   Alignment.AlignConsecutiveAssignments.Enabled = true;
17803   verifyFormat("float a, b = 1;\n"
17804                "int   c  = 2;\n"
17805                "int   dd = 3;\n",
17806                Alignment);
17807   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17808                "float b[1][] = {{3.f}};\n",
17809                Alignment);
17810   Alignment.AlignConsecutiveAssignments.Enabled = false;
17811 
17812   Alignment.ColumnLimit = 30;
17813   Alignment.BinPackParameters = false;
17814   verifyFormat("void foo(float     a,\n"
17815                "         float     b,\n"
17816                "         int       c,\n"
17817                "         uint32_t *d) {\n"
17818                "  int   *e = 0;\n"
17819                "  float  f = 0;\n"
17820                "  double g = 0;\n"
17821                "}\n"
17822                "void bar(ino_t     a,\n"
17823                "         int       b,\n"
17824                "         uint32_t *c,\n"
17825                "         bool      d) {}\n",
17826                Alignment);
17827   Alignment.BinPackParameters = true;
17828   Alignment.ColumnLimit = 80;
17829 
17830   // Bug 33507
17831   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17832   verifyFormat(
17833       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
17834       "  static const Version verVs2017;\n"
17835       "  return true;\n"
17836       "});\n",
17837       Alignment);
17838   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17839 
17840   // See llvm.org/PR35641
17841   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17842   verifyFormat("int func() { //\n"
17843                "  int      b;\n"
17844                "  unsigned c;\n"
17845                "}",
17846                Alignment);
17847 
17848   // See PR37175
17849   FormatStyle Style = getMozillaStyle();
17850   Style.AlignConsecutiveDeclarations.Enabled = true;
17851   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17852             "foo(int a);",
17853             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17854 
17855   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17856   verifyFormat("unsigned int*       a;\n"
17857                "int*                b;\n"
17858                "unsigned int Const* c;\n"
17859                "unsigned int const* d;\n"
17860                "unsigned int Const& e;\n"
17861                "unsigned int const& f;",
17862                Alignment);
17863   verifyFormat("Const unsigned int* c;\n"
17864                "const unsigned int* d;\n"
17865                "Const unsigned int& e;\n"
17866                "const unsigned int& f;\n"
17867                "const unsigned      g;\n"
17868                "Const unsigned      h;",
17869                Alignment);
17870 
17871   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17872   verifyFormat("unsigned int *       a;\n"
17873                "int *                b;\n"
17874                "unsigned int Const * c;\n"
17875                "unsigned int const * d;\n"
17876                "unsigned int Const & e;\n"
17877                "unsigned int const & f;",
17878                Alignment);
17879   verifyFormat("Const unsigned int * c;\n"
17880                "const unsigned int * d;\n"
17881                "Const unsigned int & e;\n"
17882                "const unsigned int & f;\n"
17883                "const unsigned       g;\n"
17884                "Const unsigned       h;",
17885                Alignment);
17886 
17887   // See PR46529
17888   FormatStyle BracedAlign = getLLVMStyle();
17889   BracedAlign.AlignConsecutiveDeclarations.Enabled = true;
17890   verifyFormat("const auto result{[]() {\n"
17891                "  const auto something = 1;\n"
17892                "  return 2;\n"
17893                "}};",
17894                BracedAlign);
17895   verifyFormat("int foo{[]() {\n"
17896                "  int bar{0};\n"
17897                "  return 0;\n"
17898                "}()};",
17899                BracedAlign);
17900   BracedAlign.Cpp11BracedListStyle = false;
17901   verifyFormat("const auto result{ []() {\n"
17902                "  const auto something = 1;\n"
17903                "  return 2;\n"
17904                "} };",
17905                BracedAlign);
17906   verifyFormat("int foo{ []() {\n"
17907                "  int bar{ 0 };\n"
17908                "  return 0;\n"
17909                "}() };",
17910                BracedAlign);
17911 }
17912 
17913 TEST_F(FormatTest, AlignWithLineBreaks) {
17914   auto Style = getLLVMStyleWithColumns(120);
17915 
17916   EXPECT_EQ(Style.AlignConsecutiveAssignments,
17917             FormatStyle::AlignConsecutiveStyle(
17918                 {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
17919                  /*AcrossComments=*/false, /*AlignCompound=*/false,
17920                  /*PadOperators=*/true}));
17921   EXPECT_EQ(Style.AlignConsecutiveDeclarations,
17922             FormatStyle::AlignConsecutiveStyle({}));
17923   verifyFormat("void foo() {\n"
17924                "  int myVar = 5;\n"
17925                "  double x = 3.14;\n"
17926                "  auto str = \"Hello \"\n"
17927                "             \"World\";\n"
17928                "  auto s = \"Hello \"\n"
17929                "           \"Again\";\n"
17930                "}",
17931                Style);
17932 
17933   // clang-format off
17934   verifyFormat("void foo() {\n"
17935                "  const int capacityBefore = Entries.capacity();\n"
17936                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17937                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17938                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17939                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17940                "}",
17941                Style);
17942   // clang-format on
17943 
17944   Style.AlignConsecutiveAssignments.Enabled = true;
17945   verifyFormat("void foo() {\n"
17946                "  int myVar = 5;\n"
17947                "  double x  = 3.14;\n"
17948                "  auto str  = \"Hello \"\n"
17949                "              \"World\";\n"
17950                "  auto s    = \"Hello \"\n"
17951                "              \"Again\";\n"
17952                "}",
17953                Style);
17954 
17955   // clang-format off
17956   verifyFormat("void foo() {\n"
17957                "  const int capacityBefore = Entries.capacity();\n"
17958                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17959                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17960                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17961                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17962                "}",
17963                Style);
17964   // clang-format on
17965 
17966   Style.AlignConsecutiveAssignments.Enabled = false;
17967   Style.AlignConsecutiveDeclarations.Enabled = true;
17968   verifyFormat("void foo() {\n"
17969                "  int    myVar = 5;\n"
17970                "  double x = 3.14;\n"
17971                "  auto   str = \"Hello \"\n"
17972                "               \"World\";\n"
17973                "  auto   s = \"Hello \"\n"
17974                "             \"Again\";\n"
17975                "}",
17976                Style);
17977 
17978   // clang-format off
17979   verifyFormat("void foo() {\n"
17980                "  const int  capacityBefore = Entries.capacity();\n"
17981                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17982                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17983                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17984                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17985                "}",
17986                Style);
17987   // clang-format on
17988 
17989   Style.AlignConsecutiveAssignments.Enabled = true;
17990   Style.AlignConsecutiveDeclarations.Enabled = true;
17991 
17992   verifyFormat("void foo() {\n"
17993                "  int    myVar = 5;\n"
17994                "  double x     = 3.14;\n"
17995                "  auto   str   = \"Hello \"\n"
17996                "                 \"World\";\n"
17997                "  auto   s     = \"Hello \"\n"
17998                "                 \"Again\";\n"
17999                "}",
18000                Style);
18001 
18002   // clang-format off
18003   verifyFormat("void foo() {\n"
18004                "  const int  capacityBefore = Entries.capacity();\n"
18005                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18006                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18007                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18008                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18009                "}",
18010                Style);
18011   // clang-format on
18012 
18013   Style = getLLVMStyleWithColumns(20);
18014   Style.AlignConsecutiveAssignments.Enabled = true;
18015   Style.IndentWidth = 4;
18016 
18017   verifyFormat("void foo() {\n"
18018                "    int i1 = 1;\n"
18019                "    int j  = 0;\n"
18020                "    int k  = bar(\n"
18021                "        argument1,\n"
18022                "        argument2);\n"
18023                "}",
18024                Style);
18025 
18026   Style.ColumnLimit = 120;
18027 
18028   // clang-format off
18029   verifyFormat("void SomeFunc() {\n"
18030                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18031                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18032                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18033                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18034                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18035                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18036                "}",
18037                Style);
18038   // clang-format on
18039 
18040   Style.BinPackArguments = false;
18041 
18042   // clang-format off
18043   verifyFormat("void SomeFunc() {\n"
18044                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
18045                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18046                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
18047                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18048                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
18049                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18050                "}",
18051                Style);
18052   // clang-format on
18053 }
18054 
18055 TEST_F(FormatTest, AlignWithInitializerPeriods) {
18056   auto Style = getLLVMStyleWithColumns(60);
18057 
18058   verifyFormat("void foo1(void) {\n"
18059                "  BYTE p[1] = 1;\n"
18060                "  A B = {.one_foooooooooooooooo = 2,\n"
18061                "         .two_fooooooooooooo = 3,\n"
18062                "         .three_fooooooooooooo = 4};\n"
18063                "  BYTE payload = 2;\n"
18064                "}",
18065                Style);
18066 
18067   Style.AlignConsecutiveAssignments.Enabled = true;
18068   Style.AlignConsecutiveDeclarations.Enabled = false;
18069   verifyFormat("void foo2(void) {\n"
18070                "  BYTE p[1]    = 1;\n"
18071                "  A B          = {.one_foooooooooooooooo = 2,\n"
18072                "                  .two_fooooooooooooo    = 3,\n"
18073                "                  .three_fooooooooooooo  = 4};\n"
18074                "  BYTE payload = 2;\n"
18075                "}",
18076                Style);
18077 
18078   Style.AlignConsecutiveAssignments.Enabled = false;
18079   Style.AlignConsecutiveDeclarations.Enabled = true;
18080   verifyFormat("void foo3(void) {\n"
18081                "  BYTE p[1] = 1;\n"
18082                "  A    B = {.one_foooooooooooooooo = 2,\n"
18083                "            .two_fooooooooooooo = 3,\n"
18084                "            .three_fooooooooooooo = 4};\n"
18085                "  BYTE payload = 2;\n"
18086                "}",
18087                Style);
18088 
18089   Style.AlignConsecutiveAssignments.Enabled = true;
18090   Style.AlignConsecutiveDeclarations.Enabled = true;
18091   verifyFormat("void foo4(void) {\n"
18092                "  BYTE p[1]    = 1;\n"
18093                "  A    B       = {.one_foooooooooooooooo = 2,\n"
18094                "                  .two_fooooooooooooo    = 3,\n"
18095                "                  .three_fooooooooooooo  = 4};\n"
18096                "  BYTE payload = 2;\n"
18097                "}",
18098                Style);
18099 }
18100 
18101 TEST_F(FormatTest, LinuxBraceBreaking) {
18102   FormatStyle LinuxBraceStyle = getLLVMStyle();
18103   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
18104   verifyFormat("namespace a\n"
18105                "{\n"
18106                "class A\n"
18107                "{\n"
18108                "  void f()\n"
18109                "  {\n"
18110                "    if (true) {\n"
18111                "      a();\n"
18112                "      b();\n"
18113                "    } else {\n"
18114                "      a();\n"
18115                "    }\n"
18116                "  }\n"
18117                "  void g() { return; }\n"
18118                "};\n"
18119                "struct B {\n"
18120                "  int x;\n"
18121                "};\n"
18122                "} // namespace a\n",
18123                LinuxBraceStyle);
18124   verifyFormat("enum X {\n"
18125                "  Y = 0,\n"
18126                "}\n",
18127                LinuxBraceStyle);
18128   verifyFormat("struct S {\n"
18129                "  int Type;\n"
18130                "  union {\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                LinuxBraceStyle);
18140 }
18141 
18142 TEST_F(FormatTest, MozillaBraceBreaking) {
18143   FormatStyle MozillaBraceStyle = getLLVMStyle();
18144   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
18145   MozillaBraceStyle.FixNamespaceComments = false;
18146   verifyFormat("namespace a {\n"
18147                "class A\n"
18148                "{\n"
18149                "  void f()\n"
18150                "  {\n"
18151                "    if (true) {\n"
18152                "      a();\n"
18153                "      b();\n"
18154                "    }\n"
18155                "  }\n"
18156                "  void g() { return; }\n"
18157                "};\n"
18158                "enum E\n"
18159                "{\n"
18160                "  A,\n"
18161                "  // foo\n"
18162                "  B,\n"
18163                "  C\n"
18164                "};\n"
18165                "struct B\n"
18166                "{\n"
18167                "  int x;\n"
18168                "};\n"
18169                "}\n",
18170                MozillaBraceStyle);
18171   verifyFormat("struct S\n"
18172                "{\n"
18173                "  int Type;\n"
18174                "  union\n"
18175                "  {\n"
18176                "    int x;\n"
18177                "    double y;\n"
18178                "  } Value;\n"
18179                "  class C\n"
18180                "  {\n"
18181                "    MyFavoriteType Value;\n"
18182                "  } Class;\n"
18183                "}\n",
18184                MozillaBraceStyle);
18185 }
18186 
18187 TEST_F(FormatTest, StroustrupBraceBreaking) {
18188   FormatStyle StroustrupBraceStyle = getLLVMStyle();
18189   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18190   verifyFormat("namespace a {\n"
18191                "class A {\n"
18192                "  void f()\n"
18193                "  {\n"
18194                "    if (true) {\n"
18195                "      a();\n"
18196                "      b();\n"
18197                "    }\n"
18198                "  }\n"
18199                "  void g() { return; }\n"
18200                "};\n"
18201                "struct B {\n"
18202                "  int x;\n"
18203                "};\n"
18204                "} // namespace a\n",
18205                StroustrupBraceStyle);
18206 
18207   verifyFormat("void foo()\n"
18208                "{\n"
18209                "  if (a) {\n"
18210                "    a();\n"
18211                "  }\n"
18212                "  else {\n"
18213                "    b();\n"
18214                "  }\n"
18215                "}\n",
18216                StroustrupBraceStyle);
18217 
18218   verifyFormat("#ifdef _DEBUG\n"
18219                "int foo(int i = 0)\n"
18220                "#else\n"
18221                "int foo(int i = 5)\n"
18222                "#endif\n"
18223                "{\n"
18224                "  return i;\n"
18225                "}",
18226                StroustrupBraceStyle);
18227 
18228   verifyFormat("void foo() {}\n"
18229                "void bar()\n"
18230                "#ifdef _DEBUG\n"
18231                "{\n"
18232                "  foo();\n"
18233                "}\n"
18234                "#else\n"
18235                "{\n"
18236                "}\n"
18237                "#endif",
18238                StroustrupBraceStyle);
18239 
18240   verifyFormat("void foobar() { int i = 5; }\n"
18241                "#ifdef _DEBUG\n"
18242                "void bar() {}\n"
18243                "#else\n"
18244                "void bar() { foobar(); }\n"
18245                "#endif",
18246                StroustrupBraceStyle);
18247 }
18248 
18249 TEST_F(FormatTest, AllmanBraceBreaking) {
18250   FormatStyle AllmanBraceStyle = getLLVMStyle();
18251   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
18252 
18253   EXPECT_EQ("namespace a\n"
18254             "{\n"
18255             "void f();\n"
18256             "void g();\n"
18257             "} // namespace a\n",
18258             format("namespace a\n"
18259                    "{\n"
18260                    "void f();\n"
18261                    "void g();\n"
18262                    "}\n",
18263                    AllmanBraceStyle));
18264 
18265   verifyFormat("namespace a\n"
18266                "{\n"
18267                "class A\n"
18268                "{\n"
18269                "  void f()\n"
18270                "  {\n"
18271                "    if (true)\n"
18272                "    {\n"
18273                "      a();\n"
18274                "      b();\n"
18275                "    }\n"
18276                "  }\n"
18277                "  void g() { return; }\n"
18278                "};\n"
18279                "struct B\n"
18280                "{\n"
18281                "  int x;\n"
18282                "};\n"
18283                "union C\n"
18284                "{\n"
18285                "};\n"
18286                "} // namespace a",
18287                AllmanBraceStyle);
18288 
18289   verifyFormat("void f()\n"
18290                "{\n"
18291                "  if (true)\n"
18292                "  {\n"
18293                "    a();\n"
18294                "  }\n"
18295                "  else if (false)\n"
18296                "  {\n"
18297                "    b();\n"
18298                "  }\n"
18299                "  else\n"
18300                "  {\n"
18301                "    c();\n"
18302                "  }\n"
18303                "}\n",
18304                AllmanBraceStyle);
18305 
18306   verifyFormat("void f()\n"
18307                "{\n"
18308                "  for (int i = 0; i < 10; ++i)\n"
18309                "  {\n"
18310                "    a();\n"
18311                "  }\n"
18312                "  while (false)\n"
18313                "  {\n"
18314                "    b();\n"
18315                "  }\n"
18316                "  do\n"
18317                "  {\n"
18318                "    c();\n"
18319                "  } while (false)\n"
18320                "}\n",
18321                AllmanBraceStyle);
18322 
18323   verifyFormat("void f(int a)\n"
18324                "{\n"
18325                "  switch (a)\n"
18326                "  {\n"
18327                "  case 0:\n"
18328                "    break;\n"
18329                "  case 1:\n"
18330                "  {\n"
18331                "    break;\n"
18332                "  }\n"
18333                "  case 2:\n"
18334                "  {\n"
18335                "  }\n"
18336                "  break;\n"
18337                "  default:\n"
18338                "    break;\n"
18339                "  }\n"
18340                "}\n",
18341                AllmanBraceStyle);
18342 
18343   verifyFormat("enum X\n"
18344                "{\n"
18345                "  Y = 0,\n"
18346                "}\n",
18347                AllmanBraceStyle);
18348   verifyFormat("enum X\n"
18349                "{\n"
18350                "  Y = 0\n"
18351                "}\n",
18352                AllmanBraceStyle);
18353 
18354   verifyFormat("@interface BSApplicationController ()\n"
18355                "{\n"
18356                "@private\n"
18357                "  id _extraIvar;\n"
18358                "}\n"
18359                "@end\n",
18360                AllmanBraceStyle);
18361 
18362   verifyFormat("#ifdef _DEBUG\n"
18363                "int foo(int i = 0)\n"
18364                "#else\n"
18365                "int foo(int i = 5)\n"
18366                "#endif\n"
18367                "{\n"
18368                "  return i;\n"
18369                "}",
18370                AllmanBraceStyle);
18371 
18372   verifyFormat("void foo() {}\n"
18373                "void bar()\n"
18374                "#ifdef _DEBUG\n"
18375                "{\n"
18376                "  foo();\n"
18377                "}\n"
18378                "#else\n"
18379                "{\n"
18380                "}\n"
18381                "#endif",
18382                AllmanBraceStyle);
18383 
18384   verifyFormat("void foobar() { int i = 5; }\n"
18385                "#ifdef _DEBUG\n"
18386                "void bar() {}\n"
18387                "#else\n"
18388                "void bar() { foobar(); }\n"
18389                "#endif",
18390                AllmanBraceStyle);
18391 
18392   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18393             FormatStyle::SLS_All);
18394 
18395   verifyFormat("[](int i) { return i + 2; };\n"
18396                "[](int i, int j)\n"
18397                "{\n"
18398                "  auto x = i + j;\n"
18399                "  auto y = i * j;\n"
18400                "  return x ^ y;\n"
18401                "};\n"
18402                "void foo()\n"
18403                "{\n"
18404                "  auto shortLambda = [](int i) { return i + 2; };\n"
18405                "  auto longLambda = [](int i, int j)\n"
18406                "  {\n"
18407                "    auto x = i + j;\n"
18408                "    auto y = i * j;\n"
18409                "    return x ^ y;\n"
18410                "  };\n"
18411                "}",
18412                AllmanBraceStyle);
18413 
18414   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18415 
18416   verifyFormat("[](int i)\n"
18417                "{\n"
18418                "  return i + 2;\n"
18419                "};\n"
18420                "[](int i, int j)\n"
18421                "{\n"
18422                "  auto x = i + j;\n"
18423                "  auto y = i * j;\n"
18424                "  return x ^ y;\n"
18425                "};\n"
18426                "void foo()\n"
18427                "{\n"
18428                "  auto shortLambda = [](int i)\n"
18429                "  {\n"
18430                "    return i + 2;\n"
18431                "  };\n"
18432                "  auto longLambda = [](int i, int j)\n"
18433                "  {\n"
18434                "    auto x = i + j;\n"
18435                "    auto y = i * j;\n"
18436                "    return x ^ y;\n"
18437                "  };\n"
18438                "}",
18439                AllmanBraceStyle);
18440 
18441   // Reset
18442   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18443 
18444   // This shouldn't affect ObjC blocks..
18445   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18446                "  // ...\n"
18447                "  int i;\n"
18448                "}];",
18449                AllmanBraceStyle);
18450   verifyFormat("void (^block)(void) = ^{\n"
18451                "  // ...\n"
18452                "  int i;\n"
18453                "};",
18454                AllmanBraceStyle);
18455   // .. or dict literals.
18456   verifyFormat("void f()\n"
18457                "{\n"
18458                "  // ...\n"
18459                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18460                "}",
18461                AllmanBraceStyle);
18462   verifyFormat("void f()\n"
18463                "{\n"
18464                "  // ...\n"
18465                "  [object someMethod:@{a : @\"b\"}];\n"
18466                "}",
18467                AllmanBraceStyle);
18468   verifyFormat("int f()\n"
18469                "{ // comment\n"
18470                "  return 42;\n"
18471                "}",
18472                AllmanBraceStyle);
18473 
18474   AllmanBraceStyle.ColumnLimit = 19;
18475   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18476   AllmanBraceStyle.ColumnLimit = 18;
18477   verifyFormat("void f()\n"
18478                "{\n"
18479                "  int i;\n"
18480                "}",
18481                AllmanBraceStyle);
18482   AllmanBraceStyle.ColumnLimit = 80;
18483 
18484   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18485   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18486       FormatStyle::SIS_WithoutElse;
18487   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18488   verifyFormat("void f(bool b)\n"
18489                "{\n"
18490                "  if (b)\n"
18491                "  {\n"
18492                "    return;\n"
18493                "  }\n"
18494                "}\n",
18495                BreakBeforeBraceShortIfs);
18496   verifyFormat("void f(bool b)\n"
18497                "{\n"
18498                "  if constexpr (b)\n"
18499                "  {\n"
18500                "    return;\n"
18501                "  }\n"
18502                "}\n",
18503                BreakBeforeBraceShortIfs);
18504   verifyFormat("void f(bool b)\n"
18505                "{\n"
18506                "  if CONSTEXPR (b)\n"
18507                "  {\n"
18508                "    return;\n"
18509                "  }\n"
18510                "}\n",
18511                BreakBeforeBraceShortIfs);
18512   verifyFormat("void f(bool b)\n"
18513                "{\n"
18514                "  if (b) return;\n"
18515                "}\n",
18516                BreakBeforeBraceShortIfs);
18517   verifyFormat("void f(bool b)\n"
18518                "{\n"
18519                "  if constexpr (b) return;\n"
18520                "}\n",
18521                BreakBeforeBraceShortIfs);
18522   verifyFormat("void f(bool b)\n"
18523                "{\n"
18524                "  if CONSTEXPR (b) return;\n"
18525                "}\n",
18526                BreakBeforeBraceShortIfs);
18527   verifyFormat("void f(bool b)\n"
18528                "{\n"
18529                "  while (b)\n"
18530                "  {\n"
18531                "    return;\n"
18532                "  }\n"
18533                "}\n",
18534                BreakBeforeBraceShortIfs);
18535 }
18536 
18537 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18538   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18539   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18540 
18541   // Make a few changes to the style for testing purposes
18542   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18543       FormatStyle::SFS_Empty;
18544   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18545 
18546   // FIXME: this test case can't decide whether there should be a blank line
18547   // after the ~D() line or not. It adds one if one doesn't exist in the test
18548   // and it removes the line if one exists.
18549   /*
18550   verifyFormat("class A;\n"
18551                "namespace B\n"
18552                "  {\n"
18553                "class C;\n"
18554                "// Comment\n"
18555                "class D\n"
18556                "  {\n"
18557                "public:\n"
18558                "  D();\n"
18559                "  ~D() {}\n"
18560                "private:\n"
18561                "  enum E\n"
18562                "    {\n"
18563                "    F\n"
18564                "    }\n"
18565                "  };\n"
18566                "  } // namespace B\n",
18567                WhitesmithsBraceStyle);
18568   */
18569 
18570   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18571   verifyFormat("namespace a\n"
18572                "  {\n"
18573                "class A\n"
18574                "  {\n"
18575                "  void f()\n"
18576                "    {\n"
18577                "    if (true)\n"
18578                "      {\n"
18579                "      a();\n"
18580                "      b();\n"
18581                "      }\n"
18582                "    }\n"
18583                "  void g()\n"
18584                "    {\n"
18585                "    return;\n"
18586                "    }\n"
18587                "  };\n"
18588                "struct B\n"
18589                "  {\n"
18590                "  int x;\n"
18591                "  };\n"
18592                "  } // namespace a",
18593                WhitesmithsBraceStyle);
18594 
18595   verifyFormat("namespace a\n"
18596                "  {\n"
18597                "namespace b\n"
18598                "  {\n"
18599                "class A\n"
18600                "  {\n"
18601                "  void f()\n"
18602                "    {\n"
18603                "    if (true)\n"
18604                "      {\n"
18605                "      a();\n"
18606                "      b();\n"
18607                "      }\n"
18608                "    }\n"
18609                "  void g()\n"
18610                "    {\n"
18611                "    return;\n"
18612                "    }\n"
18613                "  };\n"
18614                "struct B\n"
18615                "  {\n"
18616                "  int x;\n"
18617                "  };\n"
18618                "  } // namespace b\n"
18619                "  } // namespace a",
18620                WhitesmithsBraceStyle);
18621 
18622   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18623   verifyFormat("namespace a\n"
18624                "  {\n"
18625                "namespace b\n"
18626                "  {\n"
18627                "  class A\n"
18628                "    {\n"
18629                "    void f()\n"
18630                "      {\n"
18631                "      if (true)\n"
18632                "        {\n"
18633                "        a();\n"
18634                "        b();\n"
18635                "        }\n"
18636                "      }\n"
18637                "    void g()\n"
18638                "      {\n"
18639                "      return;\n"
18640                "      }\n"
18641                "    };\n"
18642                "  struct B\n"
18643                "    {\n"
18644                "    int x;\n"
18645                "    };\n"
18646                "  } // namespace b\n"
18647                "  } // namespace a",
18648                WhitesmithsBraceStyle);
18649 
18650   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18651   verifyFormat("namespace a\n"
18652                "  {\n"
18653                "  namespace b\n"
18654                "    {\n"
18655                "    class A\n"
18656                "      {\n"
18657                "      void f()\n"
18658                "        {\n"
18659                "        if (true)\n"
18660                "          {\n"
18661                "          a();\n"
18662                "          b();\n"
18663                "          }\n"
18664                "        }\n"
18665                "      void g()\n"
18666                "        {\n"
18667                "        return;\n"
18668                "        }\n"
18669                "      };\n"
18670                "    struct B\n"
18671                "      {\n"
18672                "      int x;\n"
18673                "      };\n"
18674                "    } // namespace b\n"
18675                "  }   // namespace a",
18676                WhitesmithsBraceStyle);
18677 
18678   verifyFormat("void f()\n"
18679                "  {\n"
18680                "  if (true)\n"
18681                "    {\n"
18682                "    a();\n"
18683                "    }\n"
18684                "  else if (false)\n"
18685                "    {\n"
18686                "    b();\n"
18687                "    }\n"
18688                "  else\n"
18689                "    {\n"
18690                "    c();\n"
18691                "    }\n"
18692                "  }\n",
18693                WhitesmithsBraceStyle);
18694 
18695   verifyFormat("void f()\n"
18696                "  {\n"
18697                "  for (int i = 0; i < 10; ++i)\n"
18698                "    {\n"
18699                "    a();\n"
18700                "    }\n"
18701                "  while (false)\n"
18702                "    {\n"
18703                "    b();\n"
18704                "    }\n"
18705                "  do\n"
18706                "    {\n"
18707                "    c();\n"
18708                "    } while (false)\n"
18709                "  }\n",
18710                WhitesmithsBraceStyle);
18711 
18712   WhitesmithsBraceStyle.IndentCaseLabels = true;
18713   verifyFormat("void switchTest1(int a)\n"
18714                "  {\n"
18715                "  switch (a)\n"
18716                "    {\n"
18717                "    case 2:\n"
18718                "      {\n"
18719                "      }\n"
18720                "      break;\n"
18721                "    }\n"
18722                "  }\n",
18723                WhitesmithsBraceStyle);
18724 
18725   verifyFormat("void switchTest2(int a)\n"
18726                "  {\n"
18727                "  switch (a)\n"
18728                "    {\n"
18729                "    case 0:\n"
18730                "      break;\n"
18731                "    case 1:\n"
18732                "      {\n"
18733                "      break;\n"
18734                "      }\n"
18735                "    case 2:\n"
18736                "      {\n"
18737                "      }\n"
18738                "      break;\n"
18739                "    default:\n"
18740                "      break;\n"
18741                "    }\n"
18742                "  }\n",
18743                WhitesmithsBraceStyle);
18744 
18745   verifyFormat("void switchTest3(int a)\n"
18746                "  {\n"
18747                "  switch (a)\n"
18748                "    {\n"
18749                "    case 0:\n"
18750                "      {\n"
18751                "      foo(x);\n"
18752                "      }\n"
18753                "      break;\n"
18754                "    default:\n"
18755                "      {\n"
18756                "      foo(1);\n"
18757                "      }\n"
18758                "      break;\n"
18759                "    }\n"
18760                "  }\n",
18761                WhitesmithsBraceStyle);
18762 
18763   WhitesmithsBraceStyle.IndentCaseLabels = false;
18764 
18765   verifyFormat("void switchTest4(int a)\n"
18766                "  {\n"
18767                "  switch (a)\n"
18768                "    {\n"
18769                "  case 2:\n"
18770                "    {\n"
18771                "    }\n"
18772                "    break;\n"
18773                "    }\n"
18774                "  }\n",
18775                WhitesmithsBraceStyle);
18776 
18777   verifyFormat("void switchTest5(int a)\n"
18778                "  {\n"
18779                "  switch (a)\n"
18780                "    {\n"
18781                "  case 0:\n"
18782                "    break;\n"
18783                "  case 1:\n"
18784                "    {\n"
18785                "    foo();\n"
18786                "    break;\n"
18787                "    }\n"
18788                "  case 2:\n"
18789                "    {\n"
18790                "    }\n"
18791                "    break;\n"
18792                "  default:\n"
18793                "    break;\n"
18794                "    }\n"
18795                "  }\n",
18796                WhitesmithsBraceStyle);
18797 
18798   verifyFormat("void switchTest6(int a)\n"
18799                "  {\n"
18800                "  switch (a)\n"
18801                "    {\n"
18802                "  case 0:\n"
18803                "    {\n"
18804                "    foo(x);\n"
18805                "    }\n"
18806                "    break;\n"
18807                "  default:\n"
18808                "    {\n"
18809                "    foo(1);\n"
18810                "    }\n"
18811                "    break;\n"
18812                "    }\n"
18813                "  }\n",
18814                WhitesmithsBraceStyle);
18815 
18816   verifyFormat("enum X\n"
18817                "  {\n"
18818                "  Y = 0, // testing\n"
18819                "  }\n",
18820                WhitesmithsBraceStyle);
18821 
18822   verifyFormat("enum X\n"
18823                "  {\n"
18824                "  Y = 0\n"
18825                "  }\n",
18826                WhitesmithsBraceStyle);
18827   verifyFormat("enum X\n"
18828                "  {\n"
18829                "  Y = 0,\n"
18830                "  Z = 1\n"
18831                "  };\n",
18832                WhitesmithsBraceStyle);
18833 
18834   verifyFormat("@interface BSApplicationController ()\n"
18835                "  {\n"
18836                "@private\n"
18837                "  id _extraIvar;\n"
18838                "  }\n"
18839                "@end\n",
18840                WhitesmithsBraceStyle);
18841 
18842   verifyFormat("#ifdef _DEBUG\n"
18843                "int foo(int i = 0)\n"
18844                "#else\n"
18845                "int foo(int i = 5)\n"
18846                "#endif\n"
18847                "  {\n"
18848                "  return i;\n"
18849                "  }",
18850                WhitesmithsBraceStyle);
18851 
18852   verifyFormat("void foo() {}\n"
18853                "void bar()\n"
18854                "#ifdef _DEBUG\n"
18855                "  {\n"
18856                "  foo();\n"
18857                "  }\n"
18858                "#else\n"
18859                "  {\n"
18860                "  }\n"
18861                "#endif",
18862                WhitesmithsBraceStyle);
18863 
18864   verifyFormat("void foobar()\n"
18865                "  {\n"
18866                "  int i = 5;\n"
18867                "  }\n"
18868                "#ifdef _DEBUG\n"
18869                "void bar()\n"
18870                "  {\n"
18871                "  }\n"
18872                "#else\n"
18873                "void bar()\n"
18874                "  {\n"
18875                "  foobar();\n"
18876                "  }\n"
18877                "#endif",
18878                WhitesmithsBraceStyle);
18879 
18880   // This shouldn't affect ObjC blocks..
18881   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18882                "  // ...\n"
18883                "  int i;\n"
18884                "}];",
18885                WhitesmithsBraceStyle);
18886   verifyFormat("void (^block)(void) = ^{\n"
18887                "  // ...\n"
18888                "  int i;\n"
18889                "};",
18890                WhitesmithsBraceStyle);
18891   // .. or dict literals.
18892   verifyFormat("void f()\n"
18893                "  {\n"
18894                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18895                "  }",
18896                WhitesmithsBraceStyle);
18897 
18898   verifyFormat("int f()\n"
18899                "  { // comment\n"
18900                "  return 42;\n"
18901                "  }",
18902                WhitesmithsBraceStyle);
18903 
18904   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18905   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18906       FormatStyle::SIS_OnlyFirstIf;
18907   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18908   verifyFormat("void f(bool b)\n"
18909                "  {\n"
18910                "  if (b)\n"
18911                "    {\n"
18912                "    return;\n"
18913                "    }\n"
18914                "  }\n",
18915                BreakBeforeBraceShortIfs);
18916   verifyFormat("void f(bool b)\n"
18917                "  {\n"
18918                "  if (b) return;\n"
18919                "  }\n",
18920                BreakBeforeBraceShortIfs);
18921   verifyFormat("void f(bool b)\n"
18922                "  {\n"
18923                "  while (b)\n"
18924                "    {\n"
18925                "    return;\n"
18926                "    }\n"
18927                "  }\n",
18928                BreakBeforeBraceShortIfs);
18929 }
18930 
18931 TEST_F(FormatTest, GNUBraceBreaking) {
18932   FormatStyle GNUBraceStyle = getLLVMStyle();
18933   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
18934   verifyFormat("namespace a\n"
18935                "{\n"
18936                "class A\n"
18937                "{\n"
18938                "  void f()\n"
18939                "  {\n"
18940                "    int a;\n"
18941                "    {\n"
18942                "      int b;\n"
18943                "    }\n"
18944                "    if (true)\n"
18945                "      {\n"
18946                "        a();\n"
18947                "        b();\n"
18948                "      }\n"
18949                "  }\n"
18950                "  void g() { return; }\n"
18951                "}\n"
18952                "} // namespace a",
18953                GNUBraceStyle);
18954 
18955   verifyFormat("void f()\n"
18956                "{\n"
18957                "  if (true)\n"
18958                "    {\n"
18959                "      a();\n"
18960                "    }\n"
18961                "  else if (false)\n"
18962                "    {\n"
18963                "      b();\n"
18964                "    }\n"
18965                "  else\n"
18966                "    {\n"
18967                "      c();\n"
18968                "    }\n"
18969                "}\n",
18970                GNUBraceStyle);
18971 
18972   verifyFormat("void f()\n"
18973                "{\n"
18974                "  for (int i = 0; i < 10; ++i)\n"
18975                "    {\n"
18976                "      a();\n"
18977                "    }\n"
18978                "  while (false)\n"
18979                "    {\n"
18980                "      b();\n"
18981                "    }\n"
18982                "  do\n"
18983                "    {\n"
18984                "      c();\n"
18985                "    }\n"
18986                "  while (false);\n"
18987                "}\n",
18988                GNUBraceStyle);
18989 
18990   verifyFormat("void f(int a)\n"
18991                "{\n"
18992                "  switch (a)\n"
18993                "    {\n"
18994                "    case 0:\n"
18995                "      break;\n"
18996                "    case 1:\n"
18997                "      {\n"
18998                "        break;\n"
18999                "      }\n"
19000                "    case 2:\n"
19001                "      {\n"
19002                "      }\n"
19003                "      break;\n"
19004                "    default:\n"
19005                "      break;\n"
19006                "    }\n"
19007                "}\n",
19008                GNUBraceStyle);
19009 
19010   verifyFormat("enum X\n"
19011                "{\n"
19012                "  Y = 0,\n"
19013                "}\n",
19014                GNUBraceStyle);
19015 
19016   verifyFormat("@interface BSApplicationController ()\n"
19017                "{\n"
19018                "@private\n"
19019                "  id _extraIvar;\n"
19020                "}\n"
19021                "@end\n",
19022                GNUBraceStyle);
19023 
19024   verifyFormat("#ifdef _DEBUG\n"
19025                "int foo(int i = 0)\n"
19026                "#else\n"
19027                "int foo(int i = 5)\n"
19028                "#endif\n"
19029                "{\n"
19030                "  return i;\n"
19031                "}",
19032                GNUBraceStyle);
19033 
19034   verifyFormat("void foo() {}\n"
19035                "void bar()\n"
19036                "#ifdef _DEBUG\n"
19037                "{\n"
19038                "  foo();\n"
19039                "}\n"
19040                "#else\n"
19041                "{\n"
19042                "}\n"
19043                "#endif",
19044                GNUBraceStyle);
19045 
19046   verifyFormat("void foobar() { int i = 5; }\n"
19047                "#ifdef _DEBUG\n"
19048                "void bar() {}\n"
19049                "#else\n"
19050                "void bar() { foobar(); }\n"
19051                "#endif",
19052                GNUBraceStyle);
19053 }
19054 
19055 TEST_F(FormatTest, WebKitBraceBreaking) {
19056   FormatStyle WebKitBraceStyle = getLLVMStyle();
19057   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
19058   WebKitBraceStyle.FixNamespaceComments = false;
19059   verifyFormat("namespace a {\n"
19060                "class A {\n"
19061                "  void f()\n"
19062                "  {\n"
19063                "    if (true) {\n"
19064                "      a();\n"
19065                "      b();\n"
19066                "    }\n"
19067                "  }\n"
19068                "  void g() { return; }\n"
19069                "};\n"
19070                "enum E {\n"
19071                "  A,\n"
19072                "  // foo\n"
19073                "  B,\n"
19074                "  C\n"
19075                "};\n"
19076                "struct B {\n"
19077                "  int x;\n"
19078                "};\n"
19079                "}\n",
19080                WebKitBraceStyle);
19081   verifyFormat("struct S {\n"
19082                "  int Type;\n"
19083                "  union {\n"
19084                "    int x;\n"
19085                "    double y;\n"
19086                "  } Value;\n"
19087                "  class C {\n"
19088                "    MyFavoriteType Value;\n"
19089                "  } Class;\n"
19090                "};\n",
19091                WebKitBraceStyle);
19092 }
19093 
19094 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
19095   verifyFormat("void f() {\n"
19096                "  try {\n"
19097                "  } catch (const Exception &e) {\n"
19098                "  }\n"
19099                "}\n",
19100                getLLVMStyle());
19101 }
19102 
19103 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
19104   auto Style = getLLVMStyle();
19105   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19106   Style.AlignConsecutiveAssignments.Enabled = true;
19107   Style.AlignConsecutiveDeclarations.Enabled = true;
19108   verifyFormat("struct test demo[] = {\n"
19109                "    {56,    23, \"hello\"},\n"
19110                "    {-1, 93463, \"world\"},\n"
19111                "    { 7,     5,    \"!!\"}\n"
19112                "};\n",
19113                Style);
19114 
19115   verifyFormat("struct test demo[] = {\n"
19116                "    {56,    23, \"hello\"}, // first line\n"
19117                "    {-1, 93463, \"world\"}, // second line\n"
19118                "    { 7,     5,    \"!!\"}  // third line\n"
19119                "};\n",
19120                Style);
19121 
19122   verifyFormat("struct test demo[4] = {\n"
19123                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19124                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19125                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19126                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19127                "};\n",
19128                Style);
19129 
19130   verifyFormat("struct test demo[3] = {\n"
19131                "    {56,    23, \"hello\"},\n"
19132                "    {-1, 93463, \"world\"},\n"
19133                "    { 7,     5,    \"!!\"}\n"
19134                "};\n",
19135                Style);
19136 
19137   verifyFormat("struct test demo[3] = {\n"
19138                "    {int{56},    23, \"hello\"},\n"
19139                "    {int{-1}, 93463, \"world\"},\n"
19140                "    { int{7},     5,    \"!!\"}\n"
19141                "};\n",
19142                Style);
19143 
19144   verifyFormat("struct test demo[] = {\n"
19145                "    {56,    23, \"hello\"},\n"
19146                "    {-1, 93463, \"world\"},\n"
19147                "    { 7,     5,    \"!!\"},\n"
19148                "};\n",
19149                Style);
19150 
19151   verifyFormat("test demo[] = {\n"
19152                "    {56,    23, \"hello\"},\n"
19153                "    {-1, 93463, \"world\"},\n"
19154                "    { 7,     5,    \"!!\"},\n"
19155                "};\n",
19156                Style);
19157 
19158   verifyFormat("demo = std::array<struct test, 3>{\n"
19159                "    test{56,    23, \"hello\"},\n"
19160                "    test{-1, 93463, \"world\"},\n"
19161                "    test{ 7,     5,    \"!!\"},\n"
19162                "};\n",
19163                Style);
19164 
19165   verifyFormat("test demo[] = {\n"
19166                "    {56,    23, \"hello\"},\n"
19167                "#if X\n"
19168                "    {-1, 93463, \"world\"},\n"
19169                "#endif\n"
19170                "    { 7,     5,    \"!!\"}\n"
19171                "};\n",
19172                Style);
19173 
19174   verifyFormat(
19175       "test demo[] = {\n"
19176       "    { 7,    23,\n"
19177       "     \"hello world i am a very long line that really, in any\"\n"
19178       "     \"just world, ought to be split over multiple lines\"},\n"
19179       "    {-1, 93463,                                  \"world\"},\n"
19180       "    {56,     5,                                     \"!!\"}\n"
19181       "};\n",
19182       Style);
19183 
19184   verifyFormat("return GradForUnaryCwise(g, {\n"
19185                "                                {{\"sign\"}, \"Sign\",  "
19186                "  {\"x\", \"dy\"}},\n"
19187                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
19188                ", \"sign\"}},\n"
19189                "});\n",
19190                Style);
19191 
19192   Style.ColumnLimit = 0;
19193   EXPECT_EQ(
19194       "test demo[] = {\n"
19195       "    {56,    23, \"hello world i am a very long line that really, "
19196       "in any just world, ought to be split over multiple lines\"},\n"
19197       "    {-1, 93463,                                                  "
19198       "                                                 \"world\"},\n"
19199       "    { 7,     5,                                                  "
19200       "                                                    \"!!\"},\n"
19201       "};",
19202       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19203              "that really, in any just world, ought to be split over multiple "
19204              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19205              Style));
19206 
19207   Style.ColumnLimit = 80;
19208   verifyFormat("test demo[] = {\n"
19209                "    {56,    23, /* a comment */ \"hello\"},\n"
19210                "    {-1, 93463,                 \"world\"},\n"
19211                "    { 7,     5,                    \"!!\"}\n"
19212                "};\n",
19213                Style);
19214 
19215   verifyFormat("test demo[] = {\n"
19216                "    {56,    23,                    \"hello\"},\n"
19217                "    {-1, 93463, \"world\" /* comment here */},\n"
19218                "    { 7,     5,                       \"!!\"}\n"
19219                "};\n",
19220                Style);
19221 
19222   verifyFormat("test demo[] = {\n"
19223                "    {56, /* a comment */ 23, \"hello\"},\n"
19224                "    {-1,              93463, \"world\"},\n"
19225                "    { 7,                  5,    \"!!\"}\n"
19226                "};\n",
19227                Style);
19228 
19229   Style.ColumnLimit = 20;
19230   EXPECT_EQ(
19231       "demo = std::array<\n"
19232       "    struct test, 3>{\n"
19233       "    test{\n"
19234       "         56,    23,\n"
19235       "         \"hello \"\n"
19236       "         \"world i \"\n"
19237       "         \"am a very \"\n"
19238       "         \"long line \"\n"
19239       "         \"that \"\n"
19240       "         \"really, \"\n"
19241       "         \"in any \"\n"
19242       "         \"just \"\n"
19243       "         \"world, \"\n"
19244       "         \"ought to \"\n"
19245       "         \"be split \"\n"
19246       "         \"over \"\n"
19247       "         \"multiple \"\n"
19248       "         \"lines\"},\n"
19249       "    test{-1, 93463,\n"
19250       "         \"world\"},\n"
19251       "    test{ 7,     5,\n"
19252       "         \"!!\"   },\n"
19253       "};",
19254       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19255              "i am a very long line that really, in any just world, ought "
19256              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19257              "test{7, 5, \"!!\"},};",
19258              Style));
19259   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19260   Style = getLLVMStyleWithColumns(50);
19261   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19262   verifyFormat("static A x = {\n"
19263                "    {{init1, init2, init3, init4},\n"
19264                "     {init1, init2, init3, init4}}\n"
19265                "};",
19266                Style);
19267   // TODO: Fix the indentations below when this option is fully functional.
19268   verifyFormat("int a[][] = {\n"
19269                "    {\n"
19270                "     {0, 2}, //\n"
19271                " {1, 2}  //\n"
19272                "    }\n"
19273                "};",
19274                Style);
19275   Style.ColumnLimit = 100;
19276   EXPECT_EQ(
19277       "test demo[] = {\n"
19278       "    {56,    23,\n"
19279       "     \"hello world i am a very long line that really, in any just world"
19280       ", ought to be split over \"\n"
19281       "     \"multiple lines\"  },\n"
19282       "    {-1, 93463, \"world\"},\n"
19283       "    { 7,     5,    \"!!\"},\n"
19284       "};",
19285       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19286              "that really, in any just world, ought to be split over multiple "
19287              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19288              Style));
19289 
19290   Style = getLLVMStyleWithColumns(50);
19291   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19292   verifyFormat("struct test demo[] = {\n"
19293                "    {56,    23, \"hello\"},\n"
19294                "    {-1, 93463, \"world\"},\n"
19295                "    { 7,     5,    \"!!\"}\n"
19296                "};\n"
19297                "static A x = {\n"
19298                "    {{init1, init2, init3, init4},\n"
19299                "     {init1, init2, init3, init4}}\n"
19300                "};",
19301                Style);
19302   Style.ColumnLimit = 100;
19303   Style.AlignConsecutiveAssignments.AcrossComments = true;
19304   Style.AlignConsecutiveDeclarations.AcrossComments = true;
19305   verifyFormat("struct test demo[] = {\n"
19306                "    {56,    23, \"hello\"},\n"
19307                "    {-1, 93463, \"world\"},\n"
19308                "    { 7,     5,    \"!!\"}\n"
19309                "};\n"
19310                "struct test demo[4] = {\n"
19311                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19312                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19313                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19314                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19315                "};\n",
19316                Style);
19317   EXPECT_EQ(
19318       "test demo[] = {\n"
19319       "    {56,\n"
19320       "     \"hello world i am a very long line that really, in any just world"
19321       ", ought to be split over \"\n"
19322       "     \"multiple lines\",    23},\n"
19323       "    {-1,      \"world\", 93463},\n"
19324       "    { 7,         \"!!\",     5},\n"
19325       "};",
19326       format("test demo[] = {{56, \"hello world i am a very long line "
19327              "that really, in any just world, ought to be split over multiple "
19328              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
19329              Style));
19330 }
19331 
19332 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
19333   auto Style = getLLVMStyle();
19334   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19335   /* FIXME: This case gets misformatted.
19336   verifyFormat("auto foo = Items{\n"
19337                "    Section{0, bar(), },\n"
19338                "    Section{1, boo()  }\n"
19339                "};\n",
19340                Style);
19341   */
19342   verifyFormat("auto foo = Items{\n"
19343                "    Section{\n"
19344                "            0, bar(),\n"
19345                "            }\n"
19346                "};\n",
19347                Style);
19348   verifyFormat("struct test demo[] = {\n"
19349                "    {56, 23,    \"hello\"},\n"
19350                "    {-1, 93463, \"world\"},\n"
19351                "    {7,  5,     \"!!\"   }\n"
19352                "};\n",
19353                Style);
19354   verifyFormat("struct test demo[] = {\n"
19355                "    {56, 23,    \"hello\"}, // first line\n"
19356                "    {-1, 93463, \"world\"}, // second line\n"
19357                "    {7,  5,     \"!!\"   }  // third line\n"
19358                "};\n",
19359                Style);
19360   verifyFormat("struct test demo[4] = {\n"
19361                "    {56,  23,    21, \"oh\"      }, // first line\n"
19362                "    {-1,  93463, 22, \"my\"      }, // second line\n"
19363                "    {7,   5,     1,  \"goodness\"}  // third line\n"
19364                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
19365                "};\n",
19366                Style);
19367   verifyFormat("struct test demo[3] = {\n"
19368                "    {56, 23,    \"hello\"},\n"
19369                "    {-1, 93463, \"world\"},\n"
19370                "    {7,  5,     \"!!\"   }\n"
19371                "};\n",
19372                Style);
19373 
19374   verifyFormat("struct test demo[3] = {\n"
19375                "    {int{56}, 23,    \"hello\"},\n"
19376                "    {int{-1}, 93463, \"world\"},\n"
19377                "    {int{7},  5,     \"!!\"   }\n"
19378                "};\n",
19379                Style);
19380   verifyFormat("struct test demo[] = {\n"
19381                "    {56, 23,    \"hello\"},\n"
19382                "    {-1, 93463, \"world\"},\n"
19383                "    {7,  5,     \"!!\"   },\n"
19384                "};\n",
19385                Style);
19386   verifyFormat("test demo[] = {\n"
19387                "    {56, 23,    \"hello\"},\n"
19388                "    {-1, 93463, \"world\"},\n"
19389                "    {7,  5,     \"!!\"   },\n"
19390                "};\n",
19391                Style);
19392   verifyFormat("demo = std::array<struct test, 3>{\n"
19393                "    test{56, 23,    \"hello\"},\n"
19394                "    test{-1, 93463, \"world\"},\n"
19395                "    test{7,  5,     \"!!\"   },\n"
19396                "};\n",
19397                Style);
19398   verifyFormat("test demo[] = {\n"
19399                "    {56, 23,    \"hello\"},\n"
19400                "#if X\n"
19401                "    {-1, 93463, \"world\"},\n"
19402                "#endif\n"
19403                "    {7,  5,     \"!!\"   }\n"
19404                "};\n",
19405                Style);
19406   verifyFormat(
19407       "test demo[] = {\n"
19408       "    {7,  23,\n"
19409       "     \"hello world i am a very long line that really, in any\"\n"
19410       "     \"just world, ought to be split over multiple lines\"},\n"
19411       "    {-1, 93463, \"world\"                                 },\n"
19412       "    {56, 5,     \"!!\"                                    }\n"
19413       "};\n",
19414       Style);
19415 
19416   verifyFormat("return GradForUnaryCwise(g, {\n"
19417                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19418                "\"dy\"}   },\n"
19419                "                                {{\"dx\"},   \"Mul\",  "
19420                "{\"dy\", \"sign\"}},\n"
19421                "});\n",
19422                Style);
19423 
19424   Style.ColumnLimit = 0;
19425   EXPECT_EQ(
19426       "test demo[] = {\n"
19427       "    {56, 23,    \"hello world i am a very long line that really, in any "
19428       "just world, ought to be split over multiple lines\"},\n"
19429       "    {-1, 93463, \"world\"                                               "
19430       "                                                   },\n"
19431       "    {7,  5,     \"!!\"                                                  "
19432       "                                                   },\n"
19433       "};",
19434       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19435              "that really, in any just world, ought to be split over multiple "
19436              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19437              Style));
19438 
19439   Style.ColumnLimit = 80;
19440   verifyFormat("test demo[] = {\n"
19441                "    {56, 23,    /* a comment */ \"hello\"},\n"
19442                "    {-1, 93463, \"world\"                },\n"
19443                "    {7,  5,     \"!!\"                   }\n"
19444                "};\n",
19445                Style);
19446 
19447   verifyFormat("test demo[] = {\n"
19448                "    {56, 23,    \"hello\"                   },\n"
19449                "    {-1, 93463, \"world\" /* comment here */},\n"
19450                "    {7,  5,     \"!!\"                      }\n"
19451                "};\n",
19452                Style);
19453 
19454   verifyFormat("test demo[] = {\n"
19455                "    {56, /* a comment */ 23, \"hello\"},\n"
19456                "    {-1, 93463,              \"world\"},\n"
19457                "    {7,  5,                  \"!!\"   }\n"
19458                "};\n",
19459                Style);
19460 
19461   Style.ColumnLimit = 20;
19462   EXPECT_EQ(
19463       "demo = std::array<\n"
19464       "    struct test, 3>{\n"
19465       "    test{\n"
19466       "         56, 23,\n"
19467       "         \"hello \"\n"
19468       "         \"world i \"\n"
19469       "         \"am a very \"\n"
19470       "         \"long line \"\n"
19471       "         \"that \"\n"
19472       "         \"really, \"\n"
19473       "         \"in any \"\n"
19474       "         \"just \"\n"
19475       "         \"world, \"\n"
19476       "         \"ought to \"\n"
19477       "         \"be split \"\n"
19478       "         \"over \"\n"
19479       "         \"multiple \"\n"
19480       "         \"lines\"},\n"
19481       "    test{-1, 93463,\n"
19482       "         \"world\"},\n"
19483       "    test{7,  5,\n"
19484       "         \"!!\"   },\n"
19485       "};",
19486       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19487              "i am a very long line that really, in any just world, ought "
19488              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19489              "test{7, 5, \"!!\"},};",
19490              Style));
19491 
19492   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19493   Style = getLLVMStyleWithColumns(50);
19494   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19495   verifyFormat("static A x = {\n"
19496                "    {{init1, init2, init3, init4},\n"
19497                "     {init1, init2, init3, init4}}\n"
19498                "};",
19499                Style);
19500   Style.ColumnLimit = 100;
19501   EXPECT_EQ(
19502       "test demo[] = {\n"
19503       "    {56, 23,\n"
19504       "     \"hello world i am a very long line that really, in any just world"
19505       ", ought to be split over \"\n"
19506       "     \"multiple lines\"  },\n"
19507       "    {-1, 93463, \"world\"},\n"
19508       "    {7,  5,     \"!!\"   },\n"
19509       "};",
19510       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19511              "that really, in any just world, ought to be split over multiple "
19512              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19513              Style));
19514 }
19515 
19516 TEST_F(FormatTest, UnderstandsPragmas) {
19517   verifyFormat("#pragma omp reduction(| : var)");
19518   verifyFormat("#pragma omp reduction(+ : var)");
19519 
19520   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19521             "(including parentheses).",
19522             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19523                    "(including parentheses)."));
19524 }
19525 
19526 TEST_F(FormatTest, UnderstandPragmaOption) {
19527   verifyFormat("#pragma option -C -A");
19528 
19529   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19530 }
19531 
19532 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19533   FormatStyle Style = getLLVMStyleWithColumns(20);
19534 
19535   // See PR41213
19536   EXPECT_EQ("/*\n"
19537             " *\t9012345\n"
19538             " * /8901\n"
19539             " */",
19540             format("/*\n"
19541                    " *\t9012345 /8901\n"
19542                    " */",
19543                    Style));
19544   EXPECT_EQ("/*\n"
19545             " *345678\n"
19546             " *\t/8901\n"
19547             " */",
19548             format("/*\n"
19549                    " *345678\t/8901\n"
19550                    " */",
19551                    Style));
19552 
19553   verifyFormat("int a; // the\n"
19554                "       // comment",
19555                Style);
19556   EXPECT_EQ("int a; /* first line\n"
19557             "        * second\n"
19558             "        * line third\n"
19559             "        * line\n"
19560             "        */",
19561             format("int a; /* first line\n"
19562                    "        * second\n"
19563                    "        * line third\n"
19564                    "        * line\n"
19565                    "        */",
19566                    Style));
19567   EXPECT_EQ("int a; // first line\n"
19568             "       // second\n"
19569             "       // line third\n"
19570             "       // line",
19571             format("int a; // first line\n"
19572                    "       // second line\n"
19573                    "       // third line",
19574                    Style));
19575 
19576   Style.PenaltyExcessCharacter = 90;
19577   verifyFormat("int a; // the comment", Style);
19578   EXPECT_EQ("int a; // the comment\n"
19579             "       // aaa",
19580             format("int a; // the comment aaa", Style));
19581   EXPECT_EQ("int a; /* first line\n"
19582             "        * second line\n"
19583             "        * third line\n"
19584             "        */",
19585             format("int a; /* first line\n"
19586                    "        * second line\n"
19587                    "        * third line\n"
19588                    "        */",
19589                    Style));
19590   EXPECT_EQ("int a; // first line\n"
19591             "       // second line\n"
19592             "       // third line",
19593             format("int a; // first line\n"
19594                    "       // second line\n"
19595                    "       // third line",
19596                    Style));
19597   // FIXME: Investigate why this is not getting the same layout as the test
19598   // above.
19599   EXPECT_EQ("int a; /* first line\n"
19600             "        * second line\n"
19601             "        * third line\n"
19602             "        */",
19603             format("int a; /* first line second line third line"
19604                    "\n*/",
19605                    Style));
19606 
19607   EXPECT_EQ("// foo bar baz bazfoo\n"
19608             "// foo bar foo bar\n",
19609             format("// foo bar baz bazfoo\n"
19610                    "// foo bar foo           bar\n",
19611                    Style));
19612   EXPECT_EQ("// foo bar baz bazfoo\n"
19613             "// foo bar foo bar\n",
19614             format("// foo bar baz      bazfoo\n"
19615                    "// foo            bar foo bar\n",
19616                    Style));
19617 
19618   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19619   // next one.
19620   EXPECT_EQ("// foo bar baz bazfoo\n"
19621             "// bar foo bar\n",
19622             format("// foo bar baz      bazfoo bar\n"
19623                    "// foo            bar\n",
19624                    Style));
19625 
19626   EXPECT_EQ("// foo bar baz bazfoo\n"
19627             "// foo bar baz bazfoo\n"
19628             "// bar foo bar\n",
19629             format("// foo bar baz      bazfoo\n"
19630                    "// foo bar baz      bazfoo bar\n"
19631                    "// foo bar\n",
19632                    Style));
19633 
19634   EXPECT_EQ("// foo bar baz bazfoo\n"
19635             "// foo bar baz bazfoo\n"
19636             "// bar foo bar\n",
19637             format("// foo bar baz      bazfoo\n"
19638                    "// foo bar baz      bazfoo bar\n"
19639                    "// foo           bar\n",
19640                    Style));
19641 
19642   // Make sure we do not keep protruding characters if strict mode reflow is
19643   // cheaper than keeping protruding characters.
19644   Style.ColumnLimit = 21;
19645   EXPECT_EQ(
19646       "// foo foo foo foo\n"
19647       "// foo foo foo foo\n"
19648       "// foo foo foo foo\n",
19649       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19650 
19651   EXPECT_EQ("int a = /* long block\n"
19652             "           comment */\n"
19653             "    42;",
19654             format("int a = /* long block comment */ 42;", Style));
19655 }
19656 
19657 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19658   FormatStyle Style = getLLVMStyle();
19659   Style.ColumnLimit = 8;
19660   Style.PenaltyExcessCharacter = 15;
19661   verifyFormat("int foo(\n"
19662                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19663                Style);
19664   Style.PenaltyBreakOpenParenthesis = 200;
19665   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19666             format("int foo(\n"
19667                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19668                    Style));
19669 }
19670 
19671 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19672   FormatStyle Style = getLLVMStyle();
19673   Style.ColumnLimit = 5;
19674   Style.PenaltyExcessCharacter = 150;
19675   verifyFormat("foo((\n"
19676                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19677 
19678                Style);
19679   Style.PenaltyBreakOpenParenthesis = 100000;
19680   EXPECT_EQ("foo((int)\n"
19681             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19682             format("foo((\n"
19683                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19684                    Style));
19685 }
19686 
19687 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19688   FormatStyle Style = getLLVMStyle();
19689   Style.ColumnLimit = 4;
19690   Style.PenaltyExcessCharacter = 100;
19691   verifyFormat("for (\n"
19692                "    int iiiiiiiiiiiiiiiii =\n"
19693                "        0;\n"
19694                "    iiiiiiiiiiiiiiiii <\n"
19695                "    2;\n"
19696                "    iiiiiiiiiiiiiiiii++) {\n"
19697                "}",
19698 
19699                Style);
19700   Style.PenaltyBreakOpenParenthesis = 1250;
19701   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19702             "         0;\n"
19703             "     iiiiiiiiiiiiiiiii <\n"
19704             "     2;\n"
19705             "     iiiiiiiiiiiiiiiii++) {\n"
19706             "}",
19707             format("for (\n"
19708                    "    int iiiiiiiiiiiiiiiii =\n"
19709                    "        0;\n"
19710                    "    iiiiiiiiiiiiiiiii <\n"
19711                    "    2;\n"
19712                    "    iiiiiiiiiiiiiiiii++) {\n"
19713                    "}",
19714                    Style));
19715 }
19716 
19717 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19718   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19719   EXPECT_EQ(Styles[0], Styles[i])                                              \
19720       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19721 
19722 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19723   SmallVector<FormatStyle, 3> Styles;
19724   Styles.resize(3);
19725 
19726   Styles[0] = getLLVMStyle();
19727   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19728   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19729   EXPECT_ALL_STYLES_EQUAL(Styles);
19730 
19731   Styles[0] = getGoogleStyle();
19732   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19733   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19734   EXPECT_ALL_STYLES_EQUAL(Styles);
19735 
19736   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19737   EXPECT_TRUE(
19738       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19739   EXPECT_TRUE(
19740       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19741   EXPECT_ALL_STYLES_EQUAL(Styles);
19742 
19743   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19744   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19745   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19746   EXPECT_ALL_STYLES_EQUAL(Styles);
19747 
19748   Styles[0] = getMozillaStyle();
19749   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19750   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19751   EXPECT_ALL_STYLES_EQUAL(Styles);
19752 
19753   Styles[0] = getWebKitStyle();
19754   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19755   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19756   EXPECT_ALL_STYLES_EQUAL(Styles);
19757 
19758   Styles[0] = getGNUStyle();
19759   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19760   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19761   EXPECT_ALL_STYLES_EQUAL(Styles);
19762 
19763   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19764 }
19765 
19766 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19767   SmallVector<FormatStyle, 8> Styles;
19768   Styles.resize(2);
19769 
19770   Styles[0] = getGoogleStyle();
19771   Styles[1] = getLLVMStyle();
19772   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19773   EXPECT_ALL_STYLES_EQUAL(Styles);
19774 
19775   Styles.resize(5);
19776   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19777   Styles[1] = getLLVMStyle();
19778   Styles[1].Language = FormatStyle::LK_JavaScript;
19779   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19780 
19781   Styles[2] = getLLVMStyle();
19782   Styles[2].Language = FormatStyle::LK_JavaScript;
19783   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19784                                   "BasedOnStyle: Google",
19785                                   &Styles[2])
19786                    .value());
19787 
19788   Styles[3] = getLLVMStyle();
19789   Styles[3].Language = FormatStyle::LK_JavaScript;
19790   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19791                                   "Language: JavaScript",
19792                                   &Styles[3])
19793                    .value());
19794 
19795   Styles[4] = getLLVMStyle();
19796   Styles[4].Language = FormatStyle::LK_JavaScript;
19797   EXPECT_EQ(0, parseConfiguration("---\n"
19798                                   "BasedOnStyle: LLVM\n"
19799                                   "IndentWidth: 123\n"
19800                                   "---\n"
19801                                   "BasedOnStyle: Google\n"
19802                                   "Language: JavaScript",
19803                                   &Styles[4])
19804                    .value());
19805   EXPECT_ALL_STYLES_EQUAL(Styles);
19806 }
19807 
19808 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
19809   Style.FIELD = false;                                                         \
19810   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
19811   EXPECT_TRUE(Style.FIELD);                                                    \
19812   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
19813   EXPECT_FALSE(Style.FIELD);
19814 
19815 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
19816 
19817 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
19818   Style.STRUCT.FIELD = false;                                                  \
19819   EXPECT_EQ(0,                                                                 \
19820             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
19821                 .value());                                                     \
19822   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
19823   EXPECT_EQ(0,                                                                 \
19824             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
19825                 .value());                                                     \
19826   EXPECT_FALSE(Style.STRUCT.FIELD);
19827 
19828 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
19829   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
19830 
19831 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
19832   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
19833   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
19834   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
19835 
19836 TEST_F(FormatTest, ParsesConfigurationBools) {
19837   FormatStyle Style = {};
19838   Style.Language = FormatStyle::LK_Cpp;
19839   CHECK_PARSE_BOOL(AlignTrailingComments);
19840   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
19841   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
19842   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
19843   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
19844   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
19845   CHECK_PARSE_BOOL(BinPackArguments);
19846   CHECK_PARSE_BOOL(BinPackParameters);
19847   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
19848   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
19849   CHECK_PARSE_BOOL(BreakStringLiterals);
19850   CHECK_PARSE_BOOL(CompactNamespaces);
19851   CHECK_PARSE_BOOL(DeriveLineEnding);
19852   CHECK_PARSE_BOOL(DerivePointerAlignment);
19853   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
19854   CHECK_PARSE_BOOL(DisableFormat);
19855   CHECK_PARSE_BOOL(IndentAccessModifiers);
19856   CHECK_PARSE_BOOL(IndentCaseLabels);
19857   CHECK_PARSE_BOOL(IndentCaseBlocks);
19858   CHECK_PARSE_BOOL(IndentGotoLabels);
19859   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
19860   CHECK_PARSE_BOOL(IndentRequiresClause);
19861   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
19862   CHECK_PARSE_BOOL(InsertBraces);
19863   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
19864   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
19865   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
19866   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
19867   CHECK_PARSE_BOOL(ReflowComments);
19868   CHECK_PARSE_BOOL(RemoveBracesLLVM);
19869   CHECK_PARSE_BOOL(SortUsingDeclarations);
19870   CHECK_PARSE_BOOL(SpacesInParentheses);
19871   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
19872   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
19873   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
19874   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
19875   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
19876   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19877   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19878   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19879   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19880   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19881   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19882   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19883   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19884   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19885   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19886   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19887   CHECK_PARSE_BOOL(UseCRLF);
19888 
19889   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19890   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19891   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19892   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19893   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19894   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19895   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19896   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19897   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19898   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19899   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19900   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19901   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19902   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19903   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19904   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19905   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19906   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19907   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19908   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19909                           AfterFunctionDeclarationName);
19910   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19911                           AfterFunctionDefinitionName);
19912   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19913   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19914   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19915 }
19916 
19917 #undef CHECK_PARSE_BOOL
19918 
19919 TEST_F(FormatTest, ParsesConfiguration) {
19920   FormatStyle Style = {};
19921   Style.Language = FormatStyle::LK_Cpp;
19922   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19923   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19924               ConstructorInitializerIndentWidth, 1234u);
19925   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19926   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19927   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19928   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19929   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19930               PenaltyBreakBeforeFirstCallParameter, 1234u);
19931   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
19932               PenaltyBreakTemplateDeclaration, 1234u);
19933   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
19934               1234u);
19935   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
19936   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
19937               PenaltyReturnTypeOnItsOwnLine, 1234u);
19938   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
19939               SpacesBeforeTrailingComments, 1234u);
19940   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
19941   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
19942   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
19943 
19944   Style.QualifierAlignment = FormatStyle::QAS_Right;
19945   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
19946               FormatStyle::QAS_Leave);
19947   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
19948               FormatStyle::QAS_Right);
19949   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
19950               FormatStyle::QAS_Left);
19951   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
19952               FormatStyle::QAS_Custom);
19953 
19954   Style.QualifierOrder.clear();
19955   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
19956               std::vector<std::string>({"const", "volatile", "type"}));
19957   Style.QualifierOrder.clear();
19958   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
19959               std::vector<std::string>({"const", "type"}));
19960   Style.QualifierOrder.clear();
19961   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
19962               std::vector<std::string>({"volatile", "type"}));
19963 
19964 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
19965   do {                                                                         \
19966     Style.FIELD.Enabled = true;                                                \
19967     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
19968                 FormatStyle::AlignConsecutiveStyle(                            \
19969                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19970                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19971                      /*PadOperators=*/true}));                                 \
19972     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
19973                 FormatStyle::AlignConsecutiveStyle(                            \
19974                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19975                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19976                      /*PadOperators=*/true}));                                 \
19977     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
19978                 FormatStyle::AlignConsecutiveStyle(                            \
19979                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19980                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19981                      /*PadOperators=*/true}));                                 \
19982     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
19983                 FormatStyle::AlignConsecutiveStyle(                            \
19984                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19985                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
19986                      /*PadOperators=*/true}));                                 \
19987     /* For backwards compability, false / true should still parse */           \
19988     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
19989                 FormatStyle::AlignConsecutiveStyle(                            \
19990                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19991                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19992                      /*PadOperators=*/true}));                                 \
19993     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
19994                 FormatStyle::AlignConsecutiveStyle(                            \
19995                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19996                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19997                      /*PadOperators=*/true}));                                 \
19998                                                                                \
19999     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
20000     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
20001     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
20002     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
20003     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
20004   } while (false)
20005 
20006   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
20007   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
20008   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
20009   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
20010 
20011 #undef CHECK_ALIGN_CONSECUTIVE
20012 
20013   Style.PointerAlignment = FormatStyle::PAS_Middle;
20014   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
20015               FormatStyle::PAS_Left);
20016   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
20017               FormatStyle::PAS_Right);
20018   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
20019               FormatStyle::PAS_Middle);
20020   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
20021   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
20022               FormatStyle::RAS_Pointer);
20023   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
20024               FormatStyle::RAS_Left);
20025   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
20026               FormatStyle::RAS_Right);
20027   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
20028               FormatStyle::RAS_Middle);
20029   // For backward compatibility:
20030   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
20031               FormatStyle::PAS_Left);
20032   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
20033               FormatStyle::PAS_Right);
20034   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
20035               FormatStyle::PAS_Middle);
20036 
20037   Style.Standard = FormatStyle::LS_Auto;
20038   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
20039   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
20040   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
20041   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
20042   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
20043   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
20044   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
20045   // Legacy aliases:
20046   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
20047   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
20048   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
20049   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
20050 
20051   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
20052   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
20053               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
20054   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
20055               FormatStyle::BOS_None);
20056   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
20057               FormatStyle::BOS_All);
20058   // For backward compatibility:
20059   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
20060               FormatStyle::BOS_None);
20061   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
20062               FormatStyle::BOS_All);
20063 
20064   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20065   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
20066               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20067   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
20068               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
20069   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
20070               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
20071   // For backward compatibility:
20072   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
20073               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20074 
20075   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
20076   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
20077               FormatStyle::BILS_AfterComma);
20078   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
20079               FormatStyle::BILS_BeforeComma);
20080   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
20081               FormatStyle::BILS_AfterColon);
20082   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
20083               FormatStyle::BILS_BeforeColon);
20084   // For backward compatibility:
20085   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
20086               FormatStyle::BILS_BeforeComma);
20087 
20088   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20089   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
20090               FormatStyle::PCIS_Never);
20091   CHECK_PARSE("PackConstructorInitializers: BinPack",
20092               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20093   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
20094               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20095   CHECK_PARSE("PackConstructorInitializers: NextLine",
20096               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20097   // For backward compatibility:
20098   CHECK_PARSE("BasedOnStyle: Google\n"
20099               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20100               "AllowAllConstructorInitializersOnNextLine: false",
20101               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20102   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20103   CHECK_PARSE("BasedOnStyle: Google\n"
20104               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
20105               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20106   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20107               "AllowAllConstructorInitializersOnNextLine: true",
20108               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20109   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20110   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20111               "AllowAllConstructorInitializersOnNextLine: false",
20112               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20113 
20114   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
20115   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
20116               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
20117   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
20118               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
20119   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
20120               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
20121   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
20122               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
20123 
20124   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20125   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
20126               FormatStyle::BAS_Align);
20127   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
20128               FormatStyle::BAS_DontAlign);
20129   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
20130               FormatStyle::BAS_AlwaysBreak);
20131   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
20132               FormatStyle::BAS_BlockIndent);
20133   // For backward compatibility:
20134   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
20135               FormatStyle::BAS_DontAlign);
20136   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
20137               FormatStyle::BAS_Align);
20138 
20139   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
20140   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
20141               FormatStyle::ENAS_DontAlign);
20142   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
20143               FormatStyle::ENAS_Left);
20144   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
20145               FormatStyle::ENAS_Right);
20146   // For backward compatibility:
20147   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
20148               FormatStyle::ENAS_Left);
20149   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
20150               FormatStyle::ENAS_Right);
20151 
20152   Style.AlignOperands = FormatStyle::OAS_Align;
20153   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
20154               FormatStyle::OAS_DontAlign);
20155   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
20156   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
20157               FormatStyle::OAS_AlignAfterOperator);
20158   // For backward compatibility:
20159   CHECK_PARSE("AlignOperands: false", AlignOperands,
20160               FormatStyle::OAS_DontAlign);
20161   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
20162 
20163   Style.UseTab = FormatStyle::UT_ForIndentation;
20164   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
20165   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
20166   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
20167   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
20168               FormatStyle::UT_ForContinuationAndIndentation);
20169   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
20170               FormatStyle::UT_AlignWithSpaces);
20171   // For backward compatibility:
20172   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
20173   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
20174 
20175   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
20176   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
20177               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20178   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
20179               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
20180   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
20181               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20182   // For backward compatibility:
20183   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
20184               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20185   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
20186               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20187 
20188   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
20189   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
20190               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20191   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
20192               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
20193   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
20194               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
20195   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
20196               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20197   // For backward compatibility:
20198   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
20199               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20200   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
20201               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20202 
20203   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
20204   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
20205               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
20206   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
20207               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
20208   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
20209               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
20210   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
20211               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
20212 
20213   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20214   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
20215               FormatStyle::SBPO_Never);
20216   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
20217               FormatStyle::SBPO_Always);
20218   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
20219               FormatStyle::SBPO_ControlStatements);
20220   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
20221               SpaceBeforeParens,
20222               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20223   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
20224               FormatStyle::SBPO_NonEmptyParentheses);
20225   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
20226               FormatStyle::SBPO_Custom);
20227   // For backward compatibility:
20228   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
20229               FormatStyle::SBPO_Never);
20230   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
20231               FormatStyle::SBPO_ControlStatements);
20232   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
20233               SpaceBeforeParens,
20234               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20235 
20236   Style.ColumnLimit = 123;
20237   FormatStyle BaseStyle = getLLVMStyle();
20238   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
20239   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
20240 
20241   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
20242   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
20243               FormatStyle::BS_Attach);
20244   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
20245               FormatStyle::BS_Linux);
20246   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
20247               FormatStyle::BS_Mozilla);
20248   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
20249               FormatStyle::BS_Stroustrup);
20250   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
20251               FormatStyle::BS_Allman);
20252   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
20253               FormatStyle::BS_Whitesmiths);
20254   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
20255   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
20256               FormatStyle::BS_WebKit);
20257   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
20258               FormatStyle::BS_Custom);
20259 
20260   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
20261   CHECK_PARSE("BraceWrapping:\n"
20262               "  AfterControlStatement: MultiLine",
20263               BraceWrapping.AfterControlStatement,
20264               FormatStyle::BWACS_MultiLine);
20265   CHECK_PARSE("BraceWrapping:\n"
20266               "  AfterControlStatement: Always",
20267               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20268   CHECK_PARSE("BraceWrapping:\n"
20269               "  AfterControlStatement: Never",
20270               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20271   // For backward compatibility:
20272   CHECK_PARSE("BraceWrapping:\n"
20273               "  AfterControlStatement: true",
20274               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20275   CHECK_PARSE("BraceWrapping:\n"
20276               "  AfterControlStatement: false",
20277               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20278 
20279   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
20280   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
20281               FormatStyle::RTBS_None);
20282   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
20283               FormatStyle::RTBS_All);
20284   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
20285               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
20286   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
20287               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
20288   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
20289               AlwaysBreakAfterReturnType,
20290               FormatStyle::RTBS_TopLevelDefinitions);
20291 
20292   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20293   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
20294               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
20295   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
20296               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20297   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
20298               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20299   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
20300               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20301   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
20302               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20303 
20304   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
20305   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
20306               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
20307   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
20308               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
20309   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
20310               AlwaysBreakAfterDefinitionReturnType,
20311               FormatStyle::DRTBS_TopLevel);
20312 
20313   Style.NamespaceIndentation = FormatStyle::NI_All;
20314   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
20315               FormatStyle::NI_None);
20316   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
20317               FormatStyle::NI_Inner);
20318   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
20319               FormatStyle::NI_All);
20320 
20321   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
20322   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
20323               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20324   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
20325               AllowShortIfStatementsOnASingleLine,
20326               FormatStyle::SIS_WithoutElse);
20327   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
20328               AllowShortIfStatementsOnASingleLine,
20329               FormatStyle::SIS_OnlyFirstIf);
20330   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
20331               AllowShortIfStatementsOnASingleLine,
20332               FormatStyle::SIS_AllIfsAndElse);
20333   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
20334               AllowShortIfStatementsOnASingleLine,
20335               FormatStyle::SIS_OnlyFirstIf);
20336   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
20337               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20338   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
20339               AllowShortIfStatementsOnASingleLine,
20340               FormatStyle::SIS_WithoutElse);
20341 
20342   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
20343   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
20344               FormatStyle::IEBS_AfterExternBlock);
20345   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
20346               FormatStyle::IEBS_Indent);
20347   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
20348               FormatStyle::IEBS_NoIndent);
20349   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
20350               FormatStyle::IEBS_Indent);
20351   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20352               FormatStyle::IEBS_NoIndent);
20353 
20354   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20355   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20356               FormatStyle::BFCS_Both);
20357   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20358               FormatStyle::BFCS_None);
20359   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20360               FormatStyle::BFCS_Before);
20361   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20362               FormatStyle::BFCS_After);
20363 
20364   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20365   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20366               FormatStyle::SJSIO_After);
20367   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20368               FormatStyle::SJSIO_Before);
20369 
20370   // FIXME: This is required because parsing a configuration simply overwrites
20371   // the first N elements of the list instead of resetting it.
20372   Style.ForEachMacros.clear();
20373   std::vector<std::string> BoostForeach;
20374   BoostForeach.push_back("BOOST_FOREACH");
20375   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20376   std::vector<std::string> BoostAndQForeach;
20377   BoostAndQForeach.push_back("BOOST_FOREACH");
20378   BoostAndQForeach.push_back("Q_FOREACH");
20379   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20380               BoostAndQForeach);
20381 
20382   Style.IfMacros.clear();
20383   std::vector<std::string> CustomIfs;
20384   CustomIfs.push_back("MYIF");
20385   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20386 
20387   Style.AttributeMacros.clear();
20388   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20389               std::vector<std::string>{"__capability"});
20390   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20391               std::vector<std::string>({"attr1", "attr2"}));
20392 
20393   Style.StatementAttributeLikeMacros.clear();
20394   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20395               StatementAttributeLikeMacros,
20396               std::vector<std::string>({"emit", "Q_EMIT"}));
20397 
20398   Style.StatementMacros.clear();
20399   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20400               std::vector<std::string>{"QUNUSED"});
20401   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20402               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20403 
20404   Style.NamespaceMacros.clear();
20405   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20406               std::vector<std::string>{"TESTSUITE"});
20407   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20408               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20409 
20410   Style.WhitespaceSensitiveMacros.clear();
20411   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20412               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20413   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20414               WhitespaceSensitiveMacros,
20415               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20416   Style.WhitespaceSensitiveMacros.clear();
20417   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20418               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20419   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20420               WhitespaceSensitiveMacros,
20421               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20422 
20423   Style.IncludeStyle.IncludeCategories.clear();
20424   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20425       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20426   CHECK_PARSE("IncludeCategories:\n"
20427               "  - Regex: abc/.*\n"
20428               "    Priority: 2\n"
20429               "  - Regex: .*\n"
20430               "    Priority: 1\n"
20431               "    CaseSensitive: true\n",
20432               IncludeStyle.IncludeCategories, ExpectedCategories);
20433   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20434               "abc$");
20435   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20436               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20437 
20438   Style.SortIncludes = FormatStyle::SI_Never;
20439   CHECK_PARSE("SortIncludes: true", SortIncludes,
20440               FormatStyle::SI_CaseSensitive);
20441   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20442   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20443               FormatStyle::SI_CaseInsensitive);
20444   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20445               FormatStyle::SI_CaseSensitive);
20446   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20447 
20448   Style.RawStringFormats.clear();
20449   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20450       {
20451           FormatStyle::LK_TextProto,
20452           {"pb", "proto"},
20453           {"PARSE_TEXT_PROTO"},
20454           /*CanonicalDelimiter=*/"",
20455           "llvm",
20456       },
20457       {
20458           FormatStyle::LK_Cpp,
20459           {"cc", "cpp"},
20460           {"C_CODEBLOCK", "CPPEVAL"},
20461           /*CanonicalDelimiter=*/"cc",
20462           /*BasedOnStyle=*/"",
20463       },
20464   };
20465 
20466   CHECK_PARSE("RawStringFormats:\n"
20467               "  - Language: TextProto\n"
20468               "    Delimiters:\n"
20469               "      - 'pb'\n"
20470               "      - 'proto'\n"
20471               "    EnclosingFunctions:\n"
20472               "      - 'PARSE_TEXT_PROTO'\n"
20473               "    BasedOnStyle: llvm\n"
20474               "  - Language: Cpp\n"
20475               "    Delimiters:\n"
20476               "      - 'cc'\n"
20477               "      - 'cpp'\n"
20478               "    EnclosingFunctions:\n"
20479               "      - 'C_CODEBLOCK'\n"
20480               "      - 'CPPEVAL'\n"
20481               "    CanonicalDelimiter: 'cc'",
20482               RawStringFormats, ExpectedRawStringFormats);
20483 
20484   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20485               "  Minimum: 0\n"
20486               "  Maximum: 0",
20487               SpacesInLineCommentPrefix.Minimum, 0u);
20488   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20489   Style.SpacesInLineCommentPrefix.Minimum = 1;
20490   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20491               "  Minimum: 2",
20492               SpacesInLineCommentPrefix.Minimum, 0u);
20493   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20494               "  Maximum: -1",
20495               SpacesInLineCommentPrefix.Maximum, -1u);
20496   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20497               "  Minimum: 2",
20498               SpacesInLineCommentPrefix.Minimum, 2u);
20499   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20500               "  Maximum: 1",
20501               SpacesInLineCommentPrefix.Maximum, 1u);
20502   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20503 
20504   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20505   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20506   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20507               FormatStyle::SIAS_Always);
20508   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20509   // For backward compatibility:
20510   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20511   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20512 
20513   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20514               FormatStyle::RCPS_WithPreceding);
20515   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20516               FormatStyle::RCPS_WithFollowing);
20517   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20518               FormatStyle::RCPS_SingleLine);
20519   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20520               FormatStyle::RCPS_OwnLine);
20521 
20522   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20523               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20524   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20525               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20526   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20527               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20528   // For backward compatibility:
20529   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20530               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20531   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20532               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20533 }
20534 
20535 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20536   FormatStyle Style = {};
20537   Style.Language = FormatStyle::LK_Cpp;
20538   CHECK_PARSE("Language: Cpp\n"
20539               "IndentWidth: 12",
20540               IndentWidth, 12u);
20541   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20542                                "IndentWidth: 34",
20543                                &Style),
20544             ParseError::Unsuitable);
20545   FormatStyle BinPackedTCS = {};
20546   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20547   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20548                                "InsertTrailingCommas: Wrapped",
20549                                &BinPackedTCS),
20550             ParseError::BinPackTrailingCommaConflict);
20551   EXPECT_EQ(12u, Style.IndentWidth);
20552   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20553   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20554 
20555   Style.Language = FormatStyle::LK_JavaScript;
20556   CHECK_PARSE("Language: JavaScript\n"
20557               "IndentWidth: 12",
20558               IndentWidth, 12u);
20559   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20560   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20561                                "IndentWidth: 34",
20562                                &Style),
20563             ParseError::Unsuitable);
20564   EXPECT_EQ(23u, Style.IndentWidth);
20565   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20566   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20567 
20568   CHECK_PARSE("BasedOnStyle: LLVM\n"
20569               "IndentWidth: 67",
20570               IndentWidth, 67u);
20571 
20572   CHECK_PARSE("---\n"
20573               "Language: JavaScript\n"
20574               "IndentWidth: 12\n"
20575               "---\n"
20576               "Language: Cpp\n"
20577               "IndentWidth: 34\n"
20578               "...\n",
20579               IndentWidth, 12u);
20580 
20581   Style.Language = FormatStyle::LK_Cpp;
20582   CHECK_PARSE("---\n"
20583               "Language: JavaScript\n"
20584               "IndentWidth: 12\n"
20585               "---\n"
20586               "Language: Cpp\n"
20587               "IndentWidth: 34\n"
20588               "...\n",
20589               IndentWidth, 34u);
20590   CHECK_PARSE("---\n"
20591               "IndentWidth: 78\n"
20592               "---\n"
20593               "Language: JavaScript\n"
20594               "IndentWidth: 56\n"
20595               "...\n",
20596               IndentWidth, 78u);
20597 
20598   Style.ColumnLimit = 123;
20599   Style.IndentWidth = 234;
20600   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20601   Style.TabWidth = 345;
20602   EXPECT_FALSE(parseConfiguration("---\n"
20603                                   "IndentWidth: 456\n"
20604                                   "BreakBeforeBraces: Allman\n"
20605                                   "---\n"
20606                                   "Language: JavaScript\n"
20607                                   "IndentWidth: 111\n"
20608                                   "TabWidth: 111\n"
20609                                   "---\n"
20610                                   "Language: Cpp\n"
20611                                   "BreakBeforeBraces: Stroustrup\n"
20612                                   "TabWidth: 789\n"
20613                                   "...\n",
20614                                   &Style));
20615   EXPECT_EQ(123u, Style.ColumnLimit);
20616   EXPECT_EQ(456u, Style.IndentWidth);
20617   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20618   EXPECT_EQ(789u, Style.TabWidth);
20619 
20620   EXPECT_EQ(parseConfiguration("---\n"
20621                                "Language: JavaScript\n"
20622                                "IndentWidth: 56\n"
20623                                "---\n"
20624                                "IndentWidth: 78\n"
20625                                "...\n",
20626                                &Style),
20627             ParseError::Error);
20628   EXPECT_EQ(parseConfiguration("---\n"
20629                                "Language: JavaScript\n"
20630                                "IndentWidth: 56\n"
20631                                "---\n"
20632                                "Language: JavaScript\n"
20633                                "IndentWidth: 78\n"
20634                                "...\n",
20635                                &Style),
20636             ParseError::Error);
20637 
20638   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20639 }
20640 
20641 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20642   FormatStyle Style = {};
20643   Style.Language = FormatStyle::LK_JavaScript;
20644   Style.BreakBeforeTernaryOperators = true;
20645   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20646   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20647 
20648   Style.BreakBeforeTernaryOperators = true;
20649   EXPECT_EQ(0, parseConfiguration("---\n"
20650                                   "BasedOnStyle: Google\n"
20651                                   "---\n"
20652                                   "Language: JavaScript\n"
20653                                   "IndentWidth: 76\n"
20654                                   "...\n",
20655                                   &Style)
20656                    .value());
20657   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20658   EXPECT_EQ(76u, Style.IndentWidth);
20659   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20660 }
20661 
20662 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20663   FormatStyle Style = getLLVMStyle();
20664   std::string YAML = configurationAsText(Style);
20665   FormatStyle ParsedStyle = {};
20666   ParsedStyle.Language = FormatStyle::LK_Cpp;
20667   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20668   EXPECT_EQ(Style, ParsedStyle);
20669 }
20670 
20671 TEST_F(FormatTest, WorksFor8bitEncodings) {
20672   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20673             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20674             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20675             "\"\xef\xee\xf0\xf3...\"",
20676             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20677                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20678                    "\xef\xee\xf0\xf3...\"",
20679                    getLLVMStyleWithColumns(12)));
20680 }
20681 
20682 TEST_F(FormatTest, HandlesUTF8BOM) {
20683   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20684   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20685             format("\xef\xbb\xbf#include <iostream>"));
20686   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20687             format("\xef\xbb\xbf\n#include <iostream>"));
20688 }
20689 
20690 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20691 #if !defined(_MSC_VER)
20692 
20693 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20694   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20695                getLLVMStyleWithColumns(35));
20696   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20697                getLLVMStyleWithColumns(31));
20698   verifyFormat("// Однажды в студёную зимнюю пору...",
20699                getLLVMStyleWithColumns(36));
20700   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20701   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20702                getLLVMStyleWithColumns(39));
20703   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20704                getLLVMStyleWithColumns(35));
20705 }
20706 
20707 TEST_F(FormatTest, SplitsUTF8Strings) {
20708   // Non-printable characters' width is currently considered to be the length in
20709   // bytes in UTF8. The characters can be displayed in very different manner
20710   // (zero-width, single width with a substitution glyph, expanded to their code
20711   // (e.g. "<8d>"), so there's no single correct way to handle them.
20712   EXPECT_EQ("\"aaaaÄ\"\n"
20713             "\"\xc2\x8d\";",
20714             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20715   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20716             "\"\xc2\x8d\";",
20717             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20718   EXPECT_EQ("\"Однажды, в \"\n"
20719             "\"студёную \"\n"
20720             "\"зимнюю \"\n"
20721             "\"пору,\"",
20722             format("\"Однажды, в студёную зимнюю пору,\"",
20723                    getLLVMStyleWithColumns(13)));
20724   EXPECT_EQ(
20725       "\"一 二 三 \"\n"
20726       "\"四 五六 \"\n"
20727       "\"七 八 九 \"\n"
20728       "\"十\"",
20729       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20730   EXPECT_EQ("\"一\t\"\n"
20731             "\"二 \t\"\n"
20732             "\"三 四 \"\n"
20733             "\"五\t\"\n"
20734             "\"六 \t\"\n"
20735             "\"七 \"\n"
20736             "\"八九十\tqq\"",
20737             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20738                    getLLVMStyleWithColumns(11)));
20739 
20740   // UTF8 character in an escape sequence.
20741   EXPECT_EQ("\"aaaaaa\"\n"
20742             "\"\\\xC2\x8D\"",
20743             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20744 }
20745 
20746 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20747   EXPECT_EQ("const char *sssss =\n"
20748             "    \"一二三四五六七八\\\n"
20749             " 九 十\";",
20750             format("const char *sssss = \"一二三四五六七八\\\n"
20751                    " 九 十\";",
20752                    getLLVMStyleWithColumns(30)));
20753 }
20754 
20755 TEST_F(FormatTest, SplitsUTF8LineComments) {
20756   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20757             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20758   EXPECT_EQ("// Я из лесу\n"
20759             "// вышел; был\n"
20760             "// сильный\n"
20761             "// мороз.",
20762             format("// Я из лесу вышел; был сильный мороз.",
20763                    getLLVMStyleWithColumns(13)));
20764   EXPECT_EQ("// 一二三\n"
20765             "// 四五六七\n"
20766             "// 八  九\n"
20767             "// 十",
20768             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20769 }
20770 
20771 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20772   EXPECT_EQ("/* Гляжу,\n"
20773             " * поднимается\n"
20774             " * медленно в\n"
20775             " * гору\n"
20776             " * Лошадка,\n"
20777             " * везущая\n"
20778             " * хворосту\n"
20779             " * воз. */",
20780             format("/* Гляжу, поднимается медленно в гору\n"
20781                    " * Лошадка, везущая хворосту воз. */",
20782                    getLLVMStyleWithColumns(13)));
20783   EXPECT_EQ(
20784       "/* 一二三\n"
20785       " * 四五六七\n"
20786       " * 八  九\n"
20787       " * 十  */",
20788       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20789   EXPECT_EQ("/* �������� ��������\n"
20790             " * ��������\n"
20791             " * ������-�� */",
20792             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20793 }
20794 
20795 #endif // _MSC_VER
20796 
20797 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
20798   FormatStyle Style = getLLVMStyle();
20799 
20800   Style.ConstructorInitializerIndentWidth = 4;
20801   verifyFormat(
20802       "SomeClass::Constructor()\n"
20803       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20804       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20805       Style);
20806 
20807   Style.ConstructorInitializerIndentWidth = 2;
20808   verifyFormat(
20809       "SomeClass::Constructor()\n"
20810       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20811       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20812       Style);
20813 
20814   Style.ConstructorInitializerIndentWidth = 0;
20815   verifyFormat(
20816       "SomeClass::Constructor()\n"
20817       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20818       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20819       Style);
20820   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20821   verifyFormat(
20822       "SomeLongTemplateVariableName<\n"
20823       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
20824       Style);
20825   verifyFormat("bool smaller = 1 < "
20826                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
20827                "                       "
20828                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
20829                Style);
20830 
20831   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
20832   verifyFormat("SomeClass::Constructor() :\n"
20833                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
20834                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
20835                Style);
20836 }
20837 
20838 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
20839   FormatStyle Style = getLLVMStyle();
20840   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20841   Style.ConstructorInitializerIndentWidth = 4;
20842   verifyFormat("SomeClass::Constructor()\n"
20843                "    : a(a)\n"
20844                "    , b(b)\n"
20845                "    , c(c) {}",
20846                Style);
20847   verifyFormat("SomeClass::Constructor()\n"
20848                "    : a(a) {}",
20849                Style);
20850 
20851   Style.ColumnLimit = 0;
20852   verifyFormat("SomeClass::Constructor()\n"
20853                "    : a(a) {}",
20854                Style);
20855   verifyFormat("SomeClass::Constructor() noexcept\n"
20856                "    : a(a) {}",
20857                Style);
20858   verifyFormat("SomeClass::Constructor()\n"
20859                "    : a(a)\n"
20860                "    , b(b)\n"
20861                "    , c(c) {}",
20862                Style);
20863   verifyFormat("SomeClass::Constructor()\n"
20864                "    : a(a) {\n"
20865                "  foo();\n"
20866                "  bar();\n"
20867                "}",
20868                Style);
20869 
20870   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20871   verifyFormat("SomeClass::Constructor()\n"
20872                "    : a(a)\n"
20873                "    , b(b)\n"
20874                "    , c(c) {\n}",
20875                Style);
20876   verifyFormat("SomeClass::Constructor()\n"
20877                "    : a(a) {\n}",
20878                Style);
20879 
20880   Style.ColumnLimit = 80;
20881   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
20882   Style.ConstructorInitializerIndentWidth = 2;
20883   verifyFormat("SomeClass::Constructor()\n"
20884                "  : a(a)\n"
20885                "  , b(b)\n"
20886                "  , c(c) {}",
20887                Style);
20888 
20889   Style.ConstructorInitializerIndentWidth = 0;
20890   verifyFormat("SomeClass::Constructor()\n"
20891                ": a(a)\n"
20892                ", b(b)\n"
20893                ", c(c) {}",
20894                Style);
20895 
20896   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20897   Style.ConstructorInitializerIndentWidth = 4;
20898   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20899   verifyFormat(
20900       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20901       Style);
20902   verifyFormat(
20903       "SomeClass::Constructor()\n"
20904       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20905       Style);
20906   Style.ConstructorInitializerIndentWidth = 4;
20907   Style.ColumnLimit = 60;
20908   verifyFormat("SomeClass::Constructor()\n"
20909                "    : aaaaaaaa(aaaaaaaa)\n"
20910                "    , aaaaaaaa(aaaaaaaa)\n"
20911                "    , aaaaaaaa(aaaaaaaa) {}",
20912                Style);
20913 }
20914 
20915 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20916   FormatStyle Style = getLLVMStyle();
20917   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20918   Style.ConstructorInitializerIndentWidth = 4;
20919   verifyFormat("SomeClass::Constructor()\n"
20920                "    : a{a}\n"
20921                "    , b{b} {}",
20922                Style);
20923   verifyFormat("SomeClass::Constructor()\n"
20924                "    : a{a}\n"
20925                "#if CONDITION\n"
20926                "    , b{b}\n"
20927                "#endif\n"
20928                "{\n}",
20929                Style);
20930   Style.ConstructorInitializerIndentWidth = 2;
20931   verifyFormat("SomeClass::Constructor()\n"
20932                "#if CONDITION\n"
20933                "  : a{a}\n"
20934                "#endif\n"
20935                "  , b{b}\n"
20936                "  , c{c} {\n}",
20937                Style);
20938   Style.ConstructorInitializerIndentWidth = 0;
20939   verifyFormat("SomeClass::Constructor()\n"
20940                ": a{a}\n"
20941                "#ifdef CONDITION\n"
20942                ", b{b}\n"
20943                "#else\n"
20944                ", c{c}\n"
20945                "#endif\n"
20946                ", d{d} {\n}",
20947                Style);
20948   Style.ConstructorInitializerIndentWidth = 4;
20949   verifyFormat("SomeClass::Constructor()\n"
20950                "    : a{a}\n"
20951                "#if WINDOWS\n"
20952                "#if DEBUG\n"
20953                "    , b{0}\n"
20954                "#else\n"
20955                "    , b{1}\n"
20956                "#endif\n"
20957                "#else\n"
20958                "#if DEBUG\n"
20959                "    , b{2}\n"
20960                "#else\n"
20961                "    , b{3}\n"
20962                "#endif\n"
20963                "#endif\n"
20964                "{\n}",
20965                Style);
20966   verifyFormat("SomeClass::Constructor()\n"
20967                "    : a{a}\n"
20968                "#if WINDOWS\n"
20969                "    , b{0}\n"
20970                "#if DEBUG\n"
20971                "    , c{0}\n"
20972                "#else\n"
20973                "    , c{1}\n"
20974                "#endif\n"
20975                "#else\n"
20976                "#if DEBUG\n"
20977                "    , c{2}\n"
20978                "#else\n"
20979                "    , c{3}\n"
20980                "#endif\n"
20981                "    , b{1}\n"
20982                "#endif\n"
20983                "{\n}",
20984                Style);
20985 }
20986 
20987 TEST_F(FormatTest, Destructors) {
20988   verifyFormat("void F(int &i) { i.~int(); }");
20989   verifyFormat("void F(int &i) { i->~int(); }");
20990 }
20991 
20992 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20993   FormatStyle Style = getWebKitStyle();
20994 
20995   // Don't indent in outer namespaces.
20996   verifyFormat("namespace outer {\n"
20997                "int i;\n"
20998                "namespace inner {\n"
20999                "    int i;\n"
21000                "} // namespace inner\n"
21001                "} // namespace outer\n"
21002                "namespace other_outer {\n"
21003                "int i;\n"
21004                "}",
21005                Style);
21006 
21007   // Don't indent case labels.
21008   verifyFormat("switch (variable) {\n"
21009                "case 1:\n"
21010                "case 2:\n"
21011                "    doSomething();\n"
21012                "    break;\n"
21013                "default:\n"
21014                "    ++variable;\n"
21015                "}",
21016                Style);
21017 
21018   // Wrap before binary operators.
21019   EXPECT_EQ("void f()\n"
21020             "{\n"
21021             "    if (aaaaaaaaaaaaaaaa\n"
21022             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
21023             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21024             "        return;\n"
21025             "}",
21026             format("void f() {\n"
21027                    "if (aaaaaaaaaaaaaaaa\n"
21028                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
21029                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21030                    "return;\n"
21031                    "}",
21032                    Style));
21033 
21034   // Allow functions on a single line.
21035   verifyFormat("void f() { return; }", Style);
21036 
21037   // Allow empty blocks on a single line and insert a space in empty blocks.
21038   EXPECT_EQ("void f() { }", format("void f() {}", Style));
21039   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
21040   // However, don't merge non-empty short loops.
21041   EXPECT_EQ("while (true) {\n"
21042             "    continue;\n"
21043             "}",
21044             format("while (true) { continue; }", Style));
21045 
21046   // Constructor initializers are formatted one per line with the "," on the
21047   // new line.
21048   verifyFormat("Constructor()\n"
21049                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
21050                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
21051                "          aaaaaaaaaaaaaa)\n"
21052                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
21053                "{\n"
21054                "}",
21055                Style);
21056   verifyFormat("SomeClass::Constructor()\n"
21057                "    : a(a)\n"
21058                "{\n"
21059                "}",
21060                Style);
21061   EXPECT_EQ("SomeClass::Constructor()\n"
21062             "    : a(a)\n"
21063             "{\n"
21064             "}",
21065             format("SomeClass::Constructor():a(a){}", Style));
21066   verifyFormat("SomeClass::Constructor()\n"
21067                "    : a(a)\n"
21068                "    , b(b)\n"
21069                "    , c(c)\n"
21070                "{\n"
21071                "}",
21072                Style);
21073   verifyFormat("SomeClass::Constructor()\n"
21074                "    : a(a)\n"
21075                "{\n"
21076                "    foo();\n"
21077                "    bar();\n"
21078                "}",
21079                Style);
21080 
21081   // Access specifiers should be aligned left.
21082   verifyFormat("class C {\n"
21083                "public:\n"
21084                "    int i;\n"
21085                "};",
21086                Style);
21087 
21088   // Do not align comments.
21089   verifyFormat("int a; // Do not\n"
21090                "double b; // align comments.",
21091                Style);
21092 
21093   // Do not align operands.
21094   EXPECT_EQ("ASSERT(aaaa\n"
21095             "    || bbbb);",
21096             format("ASSERT ( aaaa\n||bbbb);", Style));
21097 
21098   // Accept input's line breaks.
21099   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
21100             "    || bbbbbbbbbbbbbbb) {\n"
21101             "    i++;\n"
21102             "}",
21103             format("if (aaaaaaaaaaaaaaa\n"
21104                    "|| bbbbbbbbbbbbbbb) { i++; }",
21105                    Style));
21106   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
21107             "    i++;\n"
21108             "}",
21109             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
21110 
21111   // Don't automatically break all macro definitions (llvm.org/PR17842).
21112   verifyFormat("#define aNumber 10", Style);
21113   // However, generally keep the line breaks that the user authored.
21114   EXPECT_EQ("#define aNumber \\\n"
21115             "    10",
21116             format("#define aNumber \\\n"
21117                    " 10",
21118                    Style));
21119 
21120   // Keep empty and one-element array literals on a single line.
21121   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
21122             "                                  copyItems:YES];",
21123             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
21124                    "copyItems:YES];",
21125                    Style));
21126   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
21127             "                                  copyItems:YES];",
21128             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
21129                    "             copyItems:YES];",
21130                    Style));
21131   // FIXME: This does not seem right, there should be more indentation before
21132   // the array literal's entries. Nested blocks have the same problem.
21133   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21134             "    @\"a\",\n"
21135             "    @\"a\"\n"
21136             "]\n"
21137             "                                  copyItems:YES];",
21138             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21139                    "     @\"a\",\n"
21140                    "     @\"a\"\n"
21141                    "     ]\n"
21142                    "       copyItems:YES];",
21143                    Style));
21144   EXPECT_EQ(
21145       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21146       "                                  copyItems:YES];",
21147       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21148              "   copyItems:YES];",
21149              Style));
21150 
21151   verifyFormat("[self.a b:c c:d];", Style);
21152   EXPECT_EQ("[self.a b:c\n"
21153             "        c:d];",
21154             format("[self.a b:c\n"
21155                    "c:d];",
21156                    Style));
21157 }
21158 
21159 TEST_F(FormatTest, FormatsLambdas) {
21160   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
21161   verifyFormat(
21162       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
21163   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
21164   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
21165   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
21166   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
21167   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
21168   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
21169   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
21170   verifyFormat("int x = f(*+[] {});");
21171   verifyFormat("void f() {\n"
21172                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
21173                "}\n");
21174   verifyFormat("void f() {\n"
21175                "  other(x.begin(), //\n"
21176                "        x.end(),   //\n"
21177                "        [&](int, int) { return 1; });\n"
21178                "}\n");
21179   verifyFormat("void f() {\n"
21180                "  other.other.other.other.other(\n"
21181                "      x.begin(), x.end(),\n"
21182                "      [something, rather](int, int, int, int, int, int, int) { "
21183                "return 1; });\n"
21184                "}\n");
21185   verifyFormat(
21186       "void f() {\n"
21187       "  other.other.other.other.other(\n"
21188       "      x.begin(), x.end(),\n"
21189       "      [something, rather](int, int, int, int, int, int, int) {\n"
21190       "        //\n"
21191       "      });\n"
21192       "}\n");
21193   verifyFormat("SomeFunction([]() { // A cool function...\n"
21194                "  return 43;\n"
21195                "});");
21196   EXPECT_EQ("SomeFunction([]() {\n"
21197             "#define A a\n"
21198             "  return 43;\n"
21199             "});",
21200             format("SomeFunction([](){\n"
21201                    "#define A a\n"
21202                    "return 43;\n"
21203                    "});"));
21204   verifyFormat("void f() {\n"
21205                "  SomeFunction([](decltype(x), A *a) {});\n"
21206                "  SomeFunction([](typeof(x), A *a) {});\n"
21207                "  SomeFunction([](_Atomic(x), A *a) {});\n"
21208                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
21209                "}");
21210   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21211                "    [](const aaaaaaaaaa &a) { return a; });");
21212   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
21213                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
21214                "});");
21215   verifyFormat("Constructor()\n"
21216                "    : Field([] { // comment\n"
21217                "        int i;\n"
21218                "      }) {}");
21219   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
21220                "  return some_parameter.size();\n"
21221                "};");
21222   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
21223                "    [](const string &s) { return s; };");
21224   verifyFormat("int i = aaaaaa ? 1 //\n"
21225                "               : [] {\n"
21226                "                   return 2; //\n"
21227                "                 }();");
21228   verifyFormat("llvm::errs() << \"number of twos is \"\n"
21229                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
21230                "                  return x == 2; // force break\n"
21231                "                });");
21232   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21233                "    [=](int iiiiiiiiiiii) {\n"
21234                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
21235                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
21236                "    });",
21237                getLLVMStyleWithColumns(60));
21238 
21239   verifyFormat("SomeFunction({[&] {\n"
21240                "                // comment\n"
21241                "              },\n"
21242                "              [&] {\n"
21243                "                // comment\n"
21244                "              }});");
21245   verifyFormat("SomeFunction({[&] {\n"
21246                "  // comment\n"
21247                "}});");
21248   verifyFormat(
21249       "virtual aaaaaaaaaaaaaaaa(\n"
21250       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
21251       "    aaaaa aaaaaaaaa);");
21252 
21253   // Lambdas with return types.
21254   verifyFormat("int c = []() -> int { return 2; }();\n");
21255   verifyFormat("int c = []() -> int * { return 2; }();\n");
21256   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
21257   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
21258   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
21259   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
21260   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
21261   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
21262   verifyFormat("[a, a]() -> a<1> {};");
21263   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
21264   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
21265   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
21266   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
21267   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
21268   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
21269   verifyFormat("[]() -> foo<!5> { return {}; };");
21270   verifyFormat("[]() -> foo<~5> { return {}; };");
21271   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
21272   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
21273   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
21274   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
21275   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
21276   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
21277   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
21278   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
21279   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
21280   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
21281   verifyFormat("namespace bar {\n"
21282                "// broken:\n"
21283                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
21284                "} // namespace bar");
21285   verifyFormat("namespace bar {\n"
21286                "// broken:\n"
21287                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
21288                "} // namespace bar");
21289   verifyFormat("namespace bar {\n"
21290                "// broken:\n"
21291                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
21292                "} // namespace bar");
21293   verifyFormat("namespace bar {\n"
21294                "// broken:\n"
21295                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
21296                "} // namespace bar");
21297   verifyFormat("namespace bar {\n"
21298                "// broken:\n"
21299                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
21300                "} // namespace bar");
21301   verifyFormat("namespace bar {\n"
21302                "// broken:\n"
21303                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
21304                "} // namespace bar");
21305   verifyFormat("namespace bar {\n"
21306                "// broken:\n"
21307                "auto foo{[]() -> foo<!5> { return {}; }};\n"
21308                "} // namespace bar");
21309   verifyFormat("namespace bar {\n"
21310                "// broken:\n"
21311                "auto foo{[]() -> foo<~5> { return {}; }};\n"
21312                "} // namespace bar");
21313   verifyFormat("namespace bar {\n"
21314                "// broken:\n"
21315                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
21316                "} // namespace bar");
21317   verifyFormat("namespace bar {\n"
21318                "// broken:\n"
21319                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
21320                "} // namespace bar");
21321   verifyFormat("namespace bar {\n"
21322                "// broken:\n"
21323                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
21324                "} // namespace bar");
21325   verifyFormat("namespace bar {\n"
21326                "// broken:\n"
21327                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
21328                "} // namespace bar");
21329   verifyFormat("namespace bar {\n"
21330                "// broken:\n"
21331                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
21332                "} // namespace bar");
21333   verifyFormat("namespace bar {\n"
21334                "// broken:\n"
21335                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
21336                "} // namespace bar");
21337   verifyFormat("namespace bar {\n"
21338                "// broken:\n"
21339                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
21340                "} // namespace bar");
21341   verifyFormat("namespace bar {\n"
21342                "// broken:\n"
21343                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
21344                "} // namespace bar");
21345   verifyFormat("namespace bar {\n"
21346                "// broken:\n"
21347                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
21348                "} // namespace bar");
21349   verifyFormat("namespace bar {\n"
21350                "// broken:\n"
21351                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21352                "} // namespace bar");
21353   verifyFormat("[]() -> a<1> {};");
21354   verifyFormat("[]() -> a<1> { ; };");
21355   verifyFormat("[]() -> a<1> { ; }();");
21356   verifyFormat("[a, a]() -> a<true> {};");
21357   verifyFormat("[]() -> a<true> {};");
21358   verifyFormat("[]() -> a<true> { ; };");
21359   verifyFormat("[]() -> a<true> { ; }();");
21360   verifyFormat("[a, a]() -> a<false> {};");
21361   verifyFormat("[]() -> a<false> {};");
21362   verifyFormat("[]() -> a<false> { ; };");
21363   verifyFormat("[]() -> a<false> { ; }();");
21364   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21365   verifyFormat("namespace bar {\n"
21366                "auto foo{[]() -> foo<false> { ; }};\n"
21367                "} // namespace bar");
21368   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21369                "                   int j) -> int {\n"
21370                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21371                "};");
21372   verifyFormat(
21373       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21374       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21375       "      return aaaaaaaaaaaaaaaaa;\n"
21376       "    });",
21377       getLLVMStyleWithColumns(70));
21378   verifyFormat("[]() //\n"
21379                "    -> int {\n"
21380                "  return 1; //\n"
21381                "};");
21382   verifyFormat("[]() -> Void<T...> {};");
21383   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21384   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21385   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21386   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21387   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21388   verifyFormat("return int{[x = x]() { return x; }()};");
21389 
21390   // Lambdas with explicit template argument lists.
21391   verifyFormat(
21392       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21393   verifyFormat("auto L = []<class T>(T) {\n"
21394                "  {\n"
21395                "    f();\n"
21396                "    g();\n"
21397                "  }\n"
21398                "};\n");
21399   verifyFormat("auto L = []<class... T>(T...) {\n"
21400                "  {\n"
21401                "    f();\n"
21402                "    g();\n"
21403                "  }\n"
21404                "};\n");
21405   verifyFormat("auto L = []<typename... T>(T...) {\n"
21406                "  {\n"
21407                "    f();\n"
21408                "    g();\n"
21409                "  }\n"
21410                "};\n");
21411   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21412                "  {\n"
21413                "    f();\n"
21414                "    g();\n"
21415                "  }\n"
21416                "};\n");
21417   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21418                "  {\n"
21419                "    f();\n"
21420                "    g();\n"
21421                "  }\n"
21422                "};\n");
21423 
21424   // Multiple lambdas in the same parentheses change indentation rules. These
21425   // lambdas are forced to start on new lines.
21426   verifyFormat("SomeFunction(\n"
21427                "    []() {\n"
21428                "      //\n"
21429                "    },\n"
21430                "    []() {\n"
21431                "      //\n"
21432                "    });");
21433 
21434   // A lambda passed as arg0 is always pushed to the next line.
21435   verifyFormat("SomeFunction(\n"
21436                "    [this] {\n"
21437                "      //\n"
21438                "    },\n"
21439                "    1);\n");
21440 
21441   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21442   // the arg0 case above.
21443   auto Style = getGoogleStyle();
21444   Style.BinPackArguments = false;
21445   verifyFormat("SomeFunction(\n"
21446                "    a,\n"
21447                "    [this] {\n"
21448                "      //\n"
21449                "    },\n"
21450                "    b);\n",
21451                Style);
21452   verifyFormat("SomeFunction(\n"
21453                "    a,\n"
21454                "    [this] {\n"
21455                "      //\n"
21456                "    },\n"
21457                "    b);\n");
21458 
21459   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21460   // the BinPackArguments value (as long as the code is wide enough).
21461   verifyFormat(
21462       "something->SomeFunction(\n"
21463       "    a,\n"
21464       "    [this] {\n"
21465       "      "
21466       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21467       "    },\n"
21468       "    b);\n");
21469 
21470   // A multi-line lambda is pulled up as long as the introducer fits on the
21471   // previous line and there are no further args.
21472   verifyFormat("function(1, [this, that] {\n"
21473                "  //\n"
21474                "});\n");
21475   verifyFormat("function([this, that] {\n"
21476                "  //\n"
21477                "});\n");
21478   // FIXME: this format is not ideal and we should consider forcing the first
21479   // arg onto its own line.
21480   verifyFormat("function(a, b, c, //\n"
21481                "         d, [this, that] {\n"
21482                "           //\n"
21483                "         });\n");
21484 
21485   // Multiple lambdas are treated correctly even when there is a short arg0.
21486   verifyFormat("SomeFunction(\n"
21487                "    1,\n"
21488                "    [this] {\n"
21489                "      //\n"
21490                "    },\n"
21491                "    [this] {\n"
21492                "      //\n"
21493                "    },\n"
21494                "    1);\n");
21495 
21496   // More complex introducers.
21497   verifyFormat("return [i, args...] {};");
21498 
21499   // Not lambdas.
21500   verifyFormat("constexpr char hello[]{\"hello\"};");
21501   verifyFormat("double &operator[](int i) { return 0; }\n"
21502                "int i;");
21503   verifyFormat("std::unique_ptr<int[]> foo() {}");
21504   verifyFormat("int i = a[a][a]->f();");
21505   verifyFormat("int i = (*b)[a]->f();");
21506 
21507   // Other corner cases.
21508   verifyFormat("void f() {\n"
21509                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21510                "  );\n"
21511                "}");
21512   verifyFormat("auto k = *[](int *j) { return j; }(&i);");
21513 
21514   // Lambdas created through weird macros.
21515   verifyFormat("void f() {\n"
21516                "  MACRO((const AA &a) { return 1; });\n"
21517                "  MACRO((AA &a) { return 1; });\n"
21518                "}");
21519 
21520   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21521                "      doo_dah();\n"
21522                "      doo_dah();\n"
21523                "    })) {\n"
21524                "}");
21525   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21526                "                doo_dah();\n"
21527                "                doo_dah();\n"
21528                "              })) {\n"
21529                "}");
21530   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21531                "                doo_dah();\n"
21532                "                doo_dah();\n"
21533                "              })) {\n"
21534                "}");
21535   verifyFormat("auto lambda = []() {\n"
21536                "  int a = 2\n"
21537                "#if A\n"
21538                "          + 2\n"
21539                "#endif\n"
21540                "      ;\n"
21541                "};");
21542 
21543   // Lambdas with complex multiline introducers.
21544   verifyFormat(
21545       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21546       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21547       "        -> ::std::unordered_set<\n"
21548       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21549       "      //\n"
21550       "    });");
21551 
21552   FormatStyle DoNotMerge = getLLVMStyle();
21553   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21554   verifyFormat("auto c = []() {\n"
21555                "  return b;\n"
21556                "};",
21557                "auto c = []() { return b; };", DoNotMerge);
21558   verifyFormat("auto c = []() {\n"
21559                "};",
21560                " auto c = []() {};", DoNotMerge);
21561 
21562   FormatStyle MergeEmptyOnly = getLLVMStyle();
21563   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21564   verifyFormat("auto c = []() {\n"
21565                "  return b;\n"
21566                "};",
21567                "auto c = []() {\n"
21568                "  return b;\n"
21569                " };",
21570                MergeEmptyOnly);
21571   verifyFormat("auto c = []() {};",
21572                "auto c = []() {\n"
21573                "};",
21574                MergeEmptyOnly);
21575 
21576   FormatStyle MergeInline = getLLVMStyle();
21577   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21578   verifyFormat("auto c = []() {\n"
21579                "  return b;\n"
21580                "};",
21581                "auto c = []() { return b; };", MergeInline);
21582   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21583                MergeInline);
21584   verifyFormat("function([]() { return b; }, a)",
21585                "function([]() { return b; }, a)", MergeInline);
21586   verifyFormat("function(a, []() { return b; })",
21587                "function(a, []() { return b; })", MergeInline);
21588 
21589   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21590   // AllowShortLambdasOnASingleLine
21591   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21592   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21593   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21594   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21595       FormatStyle::ShortLambdaStyle::SLS_None;
21596   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21597                "    []()\n"
21598                "    {\n"
21599                "      return 17;\n"
21600                "    });",
21601                LLVMWithBeforeLambdaBody);
21602   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21603                "    []()\n"
21604                "    {\n"
21605                "    });",
21606                LLVMWithBeforeLambdaBody);
21607   verifyFormat("auto fct_SLS_None = []()\n"
21608                "{\n"
21609                "  return 17;\n"
21610                "};",
21611                LLVMWithBeforeLambdaBody);
21612   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21613                "    []()\n"
21614                "    {\n"
21615                "      return Call(\n"
21616                "          []()\n"
21617                "          {\n"
21618                "            return 17;\n"
21619                "          });\n"
21620                "    });",
21621                LLVMWithBeforeLambdaBody);
21622   verifyFormat("void Fct() {\n"
21623                "  return {[]()\n"
21624                "          {\n"
21625                "            return 17;\n"
21626                "          }};\n"
21627                "}",
21628                LLVMWithBeforeLambdaBody);
21629 
21630   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21631       FormatStyle::ShortLambdaStyle::SLS_Empty;
21632   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21633                "    []()\n"
21634                "    {\n"
21635                "      return 17;\n"
21636                "    });",
21637                LLVMWithBeforeLambdaBody);
21638   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21639                LLVMWithBeforeLambdaBody);
21640   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21641                "ongFunctionName_SLS_Empty(\n"
21642                "    []() {});",
21643                LLVMWithBeforeLambdaBody);
21644   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21645                "                                []()\n"
21646                "                                {\n"
21647                "                                  return 17;\n"
21648                "                                });",
21649                LLVMWithBeforeLambdaBody);
21650   verifyFormat("auto fct_SLS_Empty = []()\n"
21651                "{\n"
21652                "  return 17;\n"
21653                "};",
21654                LLVMWithBeforeLambdaBody);
21655   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21656                "    []()\n"
21657                "    {\n"
21658                "      return Call([]() {});\n"
21659                "    });",
21660                LLVMWithBeforeLambdaBody);
21661   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21662                "                           []()\n"
21663                "                           {\n"
21664                "                             return Call([]() {});\n"
21665                "                           });",
21666                LLVMWithBeforeLambdaBody);
21667   verifyFormat(
21668       "FctWithLongLineInLambda_SLS_Empty(\n"
21669       "    []()\n"
21670       "    {\n"
21671       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21672       "                               AndShouldNotBeConsiderAsInline,\n"
21673       "                               LambdaBodyMustBeBreak);\n"
21674       "    });",
21675       LLVMWithBeforeLambdaBody);
21676 
21677   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21678       FormatStyle::ShortLambdaStyle::SLS_Inline;
21679   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21680                LLVMWithBeforeLambdaBody);
21681   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21682                LLVMWithBeforeLambdaBody);
21683   verifyFormat("auto fct_SLS_Inline = []()\n"
21684                "{\n"
21685                "  return 17;\n"
21686                "};",
21687                LLVMWithBeforeLambdaBody);
21688   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21689                "17; }); });",
21690                LLVMWithBeforeLambdaBody);
21691   verifyFormat(
21692       "FctWithLongLineInLambda_SLS_Inline(\n"
21693       "    []()\n"
21694       "    {\n"
21695       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21696       "                               AndShouldNotBeConsiderAsInline,\n"
21697       "                               LambdaBodyMustBeBreak);\n"
21698       "    });",
21699       LLVMWithBeforeLambdaBody);
21700   verifyFormat("FctWithMultipleParams_SLS_Inline("
21701                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21702                "                                 []() { return 17; });",
21703                LLVMWithBeforeLambdaBody);
21704   verifyFormat(
21705       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21706       LLVMWithBeforeLambdaBody);
21707 
21708   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21709       FormatStyle::ShortLambdaStyle::SLS_All;
21710   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21711                LLVMWithBeforeLambdaBody);
21712   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21713                LLVMWithBeforeLambdaBody);
21714   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21715                LLVMWithBeforeLambdaBody);
21716   verifyFormat("FctWithOneParam_SLS_All(\n"
21717                "    []()\n"
21718                "    {\n"
21719                "      // A cool function...\n"
21720                "      return 43;\n"
21721                "    });",
21722                LLVMWithBeforeLambdaBody);
21723   verifyFormat("FctWithMultipleParams_SLS_All("
21724                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21725                "                              []() { return 17; });",
21726                LLVMWithBeforeLambdaBody);
21727   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21728                LLVMWithBeforeLambdaBody);
21729   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21730                LLVMWithBeforeLambdaBody);
21731   verifyFormat(
21732       "FctWithLongLineInLambda_SLS_All(\n"
21733       "    []()\n"
21734       "    {\n"
21735       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21736       "                               AndShouldNotBeConsiderAsInline,\n"
21737       "                               LambdaBodyMustBeBreak);\n"
21738       "    });",
21739       LLVMWithBeforeLambdaBody);
21740   verifyFormat(
21741       "auto fct_SLS_All = []()\n"
21742       "{\n"
21743       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21744       "                           AndShouldNotBeConsiderAsInline,\n"
21745       "                           LambdaBodyMustBeBreak);\n"
21746       "};",
21747       LLVMWithBeforeLambdaBody);
21748   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21749   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21750                LLVMWithBeforeLambdaBody);
21751   verifyFormat(
21752       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21753       "                                FirstParam,\n"
21754       "                                SecondParam,\n"
21755       "                                ThirdParam,\n"
21756       "                                FourthParam);",
21757       LLVMWithBeforeLambdaBody);
21758   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21759                "    []() { return "
21760                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21761                "    FirstParam,\n"
21762                "    SecondParam,\n"
21763                "    ThirdParam,\n"
21764                "    FourthParam);",
21765                LLVMWithBeforeLambdaBody);
21766   verifyFormat(
21767       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21768       "                                SecondParam,\n"
21769       "                                ThirdParam,\n"
21770       "                                FourthParam,\n"
21771       "                                []() { return SomeValueNotSoLong; });",
21772       LLVMWithBeforeLambdaBody);
21773   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21774                "    []()\n"
21775                "    {\n"
21776                "      return "
21777                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21778                "eConsiderAsInline;\n"
21779                "    });",
21780                LLVMWithBeforeLambdaBody);
21781   verifyFormat(
21782       "FctWithLongLineInLambda_SLS_All(\n"
21783       "    []()\n"
21784       "    {\n"
21785       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21786       "                               AndShouldNotBeConsiderAsInline,\n"
21787       "                               LambdaBodyMustBeBreak);\n"
21788       "    });",
21789       LLVMWithBeforeLambdaBody);
21790   verifyFormat("FctWithTwoParams_SLS_All(\n"
21791                "    []()\n"
21792                "    {\n"
21793                "      // A cool function...\n"
21794                "      return 43;\n"
21795                "    },\n"
21796                "    87);",
21797                LLVMWithBeforeLambdaBody);
21798   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
21799                LLVMWithBeforeLambdaBody);
21800   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
21801                LLVMWithBeforeLambdaBody);
21802   verifyFormat(
21803       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
21804       LLVMWithBeforeLambdaBody);
21805   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
21806                "}); }, x);",
21807                LLVMWithBeforeLambdaBody);
21808   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21809                "    []()\n"
21810                "    {\n"
21811                "      // A cool function...\n"
21812                "      return Call([]() { return 17; });\n"
21813                "    });",
21814                LLVMWithBeforeLambdaBody);
21815   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21816                "    []()\n"
21817                "    {\n"
21818                "      return Call(\n"
21819                "          []()\n"
21820                "          {\n"
21821                "            // A cool function...\n"
21822                "            return 17;\n"
21823                "          });\n"
21824                "    });",
21825                LLVMWithBeforeLambdaBody);
21826 
21827   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21828       FormatStyle::ShortLambdaStyle::SLS_None;
21829 
21830   verifyFormat("auto select = [this]() -> const Library::Object *\n"
21831                "{\n"
21832                "  return MyAssignment::SelectFromList(this);\n"
21833                "};\n",
21834                LLVMWithBeforeLambdaBody);
21835 
21836   verifyFormat("auto select = [this]() -> const Library::Object &\n"
21837                "{\n"
21838                "  return MyAssignment::SelectFromList(this);\n"
21839                "};\n",
21840                LLVMWithBeforeLambdaBody);
21841 
21842   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
21843                "{\n"
21844                "  return MyAssignment::SelectFromList(this);\n"
21845                "};\n",
21846                LLVMWithBeforeLambdaBody);
21847 
21848   verifyFormat("namespace test {\n"
21849                "class Test {\n"
21850                "public:\n"
21851                "  Test() = default;\n"
21852                "};\n"
21853                "} // namespace test",
21854                LLVMWithBeforeLambdaBody);
21855 
21856   // Lambdas with different indentation styles.
21857   Style = getLLVMStyleWithColumns(100);
21858   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21859             "  return promise.then(\n"
21860             "      [this, &someVariable, someObject = "
21861             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21862             "        return someObject.startAsyncAction().then(\n"
21863             "            [this, &someVariable](AsyncActionResult result) "
21864             "mutable { result.processMore(); });\n"
21865             "      });\n"
21866             "}\n",
21867             format("SomeResult doSomething(SomeObject promise) {\n"
21868                    "  return promise.then([this, &someVariable, someObject = "
21869                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21870                    "    return someObject.startAsyncAction().then([this, "
21871                    "&someVariable](AsyncActionResult result) mutable {\n"
21872                    "      result.processMore();\n"
21873                    "    });\n"
21874                    "  });\n"
21875                    "}\n",
21876                    Style));
21877   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21878   verifyFormat("test() {\n"
21879                "  ([]() -> {\n"
21880                "    int b = 32;\n"
21881                "    return 3;\n"
21882                "  }).foo();\n"
21883                "}",
21884                Style);
21885   verifyFormat("test() {\n"
21886                "  []() -> {\n"
21887                "    int b = 32;\n"
21888                "    return 3;\n"
21889                "  }\n"
21890                "}",
21891                Style);
21892   verifyFormat("std::sort(v.begin(), v.end(),\n"
21893                "          [](const auto &someLongArgumentName, const auto "
21894                "&someOtherLongArgumentName) {\n"
21895                "  return someLongArgumentName.someMemberVariable < "
21896                "someOtherLongArgumentName.someMemberVariable;\n"
21897                "});",
21898                Style);
21899   verifyFormat("test() {\n"
21900                "  (\n"
21901                "      []() -> {\n"
21902                "        int b = 32;\n"
21903                "        return 3;\n"
21904                "      },\n"
21905                "      foo, bar)\n"
21906                "      .foo();\n"
21907                "}",
21908                Style);
21909   verifyFormat("test() {\n"
21910                "  ([]() -> {\n"
21911                "    int b = 32;\n"
21912                "    return 3;\n"
21913                "  })\n"
21914                "      .foo()\n"
21915                "      .bar();\n"
21916                "}",
21917                Style);
21918   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21919             "  return promise.then(\n"
21920             "      [this, &someVariable, someObject = "
21921             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21922             "    return someObject.startAsyncAction().then(\n"
21923             "        [this, &someVariable](AsyncActionResult result) mutable { "
21924             "result.processMore(); });\n"
21925             "  });\n"
21926             "}\n",
21927             format("SomeResult doSomething(SomeObject promise) {\n"
21928                    "  return promise.then([this, &someVariable, someObject = "
21929                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21930                    "    return someObject.startAsyncAction().then([this, "
21931                    "&someVariable](AsyncActionResult result) mutable {\n"
21932                    "      result.processMore();\n"
21933                    "    });\n"
21934                    "  });\n"
21935                    "}\n",
21936                    Style));
21937   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21938             "  return promise.then([this, &someVariable] {\n"
21939             "    return someObject.startAsyncAction().then(\n"
21940             "        [this, &someVariable](AsyncActionResult result) mutable { "
21941             "result.processMore(); });\n"
21942             "  });\n"
21943             "}\n",
21944             format("SomeResult doSomething(SomeObject promise) {\n"
21945                    "  return promise.then([this, &someVariable] {\n"
21946                    "    return someObject.startAsyncAction().then([this, "
21947                    "&someVariable](AsyncActionResult result) mutable {\n"
21948                    "      result.processMore();\n"
21949                    "    });\n"
21950                    "  });\n"
21951                    "}\n",
21952                    Style));
21953   Style = getGoogleStyle();
21954   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21955   EXPECT_EQ("#define A                                       \\\n"
21956             "  [] {                                          \\\n"
21957             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
21958             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
21959             "      }",
21960             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
21961                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
21962                    Style));
21963   // TODO: The current formatting has a minor issue that's not worth fixing
21964   // right now whereby the closing brace is indented relative to the signature
21965   // instead of being aligned. This only happens with macros.
21966 }
21967 
21968 TEST_F(FormatTest, LambdaWithLineComments) {
21969   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21970   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21971   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21972   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21973       FormatStyle::ShortLambdaStyle::SLS_All;
21974 
21975   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
21976   verifyFormat("auto k = []() // comment\n"
21977                "{ return; }",
21978                LLVMWithBeforeLambdaBody);
21979   verifyFormat("auto k = []() /* comment */ { return; }",
21980                LLVMWithBeforeLambdaBody);
21981   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
21982                LLVMWithBeforeLambdaBody);
21983   verifyFormat("auto k = []() // X\n"
21984                "{ return; }",
21985                LLVMWithBeforeLambdaBody);
21986   verifyFormat(
21987       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
21988       "{ return; }",
21989       LLVMWithBeforeLambdaBody);
21990 
21991   LLVMWithBeforeLambdaBody.ColumnLimit = 0;
21992 
21993   verifyFormat("foo([]()\n"
21994                "    {\n"
21995                "      bar();    //\n"
21996                "      return 1; // comment\n"
21997                "    }());",
21998                "foo([]() {\n"
21999                "  bar(); //\n"
22000                "  return 1; // comment\n"
22001                "}());",
22002                LLVMWithBeforeLambdaBody);
22003   verifyFormat("foo(\n"
22004                "    1, MACRO {\n"
22005                "      baz();\n"
22006                "      bar(); // comment\n"
22007                "    },\n"
22008                "    []() {});",
22009                "foo(\n"
22010                "  1, MACRO { baz(); bar(); // comment\n"
22011                "  }, []() {}\n"
22012                ");",
22013                LLVMWithBeforeLambdaBody);
22014 }
22015 
22016 TEST_F(FormatTest, EmptyLinesInLambdas) {
22017   verifyFormat("auto lambda = []() {\n"
22018                "  x(); //\n"
22019                "};",
22020                "auto lambda = []() {\n"
22021                "\n"
22022                "  x(); //\n"
22023                "\n"
22024                "};");
22025 }
22026 
22027 TEST_F(FormatTest, FormatsBlocks) {
22028   FormatStyle ShortBlocks = getLLVMStyle();
22029   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22030   verifyFormat("int (^Block)(int, int);", ShortBlocks);
22031   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
22032   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
22033   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
22034   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
22035   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
22036 
22037   verifyFormat("foo(^{ bar(); });", ShortBlocks);
22038   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
22039   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
22040 
22041   verifyFormat("[operation setCompletionBlock:^{\n"
22042                "  [self onOperationDone];\n"
22043                "}];");
22044   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
22045                "  [self onOperationDone];\n"
22046                "}]};");
22047   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
22048                "  f();\n"
22049                "}];");
22050   verifyFormat("int a = [operation block:^int(int *i) {\n"
22051                "  return 1;\n"
22052                "}];");
22053   verifyFormat("[myObject doSomethingWith:arg1\n"
22054                "                      aaa:^int(int *a) {\n"
22055                "                        return 1;\n"
22056                "                      }\n"
22057                "                      bbb:f(a * bbbbbbbb)];");
22058 
22059   verifyFormat("[operation setCompletionBlock:^{\n"
22060                "  [self.delegate newDataAvailable];\n"
22061                "}];",
22062                getLLVMStyleWithColumns(60));
22063   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
22064                "  NSString *path = [self sessionFilePath];\n"
22065                "  if (path) {\n"
22066                "    // ...\n"
22067                "  }\n"
22068                "});");
22069   verifyFormat("[[SessionService sharedService]\n"
22070                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22071                "      if (window) {\n"
22072                "        [self windowDidLoad:window];\n"
22073                "      } else {\n"
22074                "        [self errorLoadingWindow];\n"
22075                "      }\n"
22076                "    }];");
22077   verifyFormat("void (^largeBlock)(void) = ^{\n"
22078                "  // ...\n"
22079                "};\n",
22080                getLLVMStyleWithColumns(40));
22081   verifyFormat("[[SessionService sharedService]\n"
22082                "    loadWindowWithCompletionBlock: //\n"
22083                "        ^(SessionWindow *window) {\n"
22084                "          if (window) {\n"
22085                "            [self windowDidLoad:window];\n"
22086                "          } else {\n"
22087                "            [self errorLoadingWindow];\n"
22088                "          }\n"
22089                "        }];",
22090                getLLVMStyleWithColumns(60));
22091   verifyFormat("[myObject doSomethingWith:arg1\n"
22092                "    firstBlock:^(Foo *a) {\n"
22093                "      // ...\n"
22094                "      int i;\n"
22095                "    }\n"
22096                "    secondBlock:^(Bar *b) {\n"
22097                "      // ...\n"
22098                "      int i;\n"
22099                "    }\n"
22100                "    thirdBlock:^Foo(Bar *b) {\n"
22101                "      // ...\n"
22102                "      int i;\n"
22103                "    }];");
22104   verifyFormat("[myObject doSomethingWith:arg1\n"
22105                "               firstBlock:-1\n"
22106                "              secondBlock:^(Bar *b) {\n"
22107                "                // ...\n"
22108                "                int i;\n"
22109                "              }];");
22110 
22111   verifyFormat("f(^{\n"
22112                "  @autoreleasepool {\n"
22113                "    if (a) {\n"
22114                "      g();\n"
22115                "    }\n"
22116                "  }\n"
22117                "});");
22118   verifyFormat("Block b = ^int *(A *a, B *b) {}");
22119   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
22120                "};");
22121 
22122   FormatStyle FourIndent = getLLVMStyle();
22123   FourIndent.ObjCBlockIndentWidth = 4;
22124   verifyFormat("[operation setCompletionBlock:^{\n"
22125                "    [self onOperationDone];\n"
22126                "}];",
22127                FourIndent);
22128 }
22129 
22130 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
22131   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
22132 
22133   verifyFormat("[[SessionService sharedService] "
22134                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22135                "  if (window) {\n"
22136                "    [self windowDidLoad:window];\n"
22137                "  } else {\n"
22138                "    [self errorLoadingWindow];\n"
22139                "  }\n"
22140                "}];",
22141                ZeroColumn);
22142   EXPECT_EQ("[[SessionService sharedService]\n"
22143             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22144             "      if (window) {\n"
22145             "        [self windowDidLoad:window];\n"
22146             "      } else {\n"
22147             "        [self errorLoadingWindow];\n"
22148             "      }\n"
22149             "    }];",
22150             format("[[SessionService sharedService]\n"
22151                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22152                    "                if (window) {\n"
22153                    "    [self windowDidLoad:window];\n"
22154                    "  } else {\n"
22155                    "    [self errorLoadingWindow];\n"
22156                    "  }\n"
22157                    "}];",
22158                    ZeroColumn));
22159   verifyFormat("[myObject doSomethingWith:arg1\n"
22160                "    firstBlock:^(Foo *a) {\n"
22161                "      // ...\n"
22162                "      int i;\n"
22163                "    }\n"
22164                "    secondBlock:^(Bar *b) {\n"
22165                "      // ...\n"
22166                "      int i;\n"
22167                "    }\n"
22168                "    thirdBlock:^Foo(Bar *b) {\n"
22169                "      // ...\n"
22170                "      int i;\n"
22171                "    }];",
22172                ZeroColumn);
22173   verifyFormat("f(^{\n"
22174                "  @autoreleasepool {\n"
22175                "    if (a) {\n"
22176                "      g();\n"
22177                "    }\n"
22178                "  }\n"
22179                "});",
22180                ZeroColumn);
22181   verifyFormat("void (^largeBlock)(void) = ^{\n"
22182                "  // ...\n"
22183                "};",
22184                ZeroColumn);
22185 
22186   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22187   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
22188             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22189   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22190   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
22191             "  int i;\n"
22192             "};",
22193             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22194 }
22195 
22196 TEST_F(FormatTest, SupportsCRLF) {
22197   EXPECT_EQ("int a;\r\n"
22198             "int b;\r\n"
22199             "int c;\r\n",
22200             format("int a;\r\n"
22201                    "  int b;\r\n"
22202                    "    int c;\r\n",
22203                    getLLVMStyle()));
22204   EXPECT_EQ("int a;\r\n"
22205             "int b;\r\n"
22206             "int c;\r\n",
22207             format("int a;\r\n"
22208                    "  int b;\n"
22209                    "    int c;\r\n",
22210                    getLLVMStyle()));
22211   EXPECT_EQ("int a;\n"
22212             "int b;\n"
22213             "int c;\n",
22214             format("int a;\r\n"
22215                    "  int b;\n"
22216                    "    int c;\n",
22217                    getLLVMStyle()));
22218   EXPECT_EQ("\"aaaaaaa \"\r\n"
22219             "\"bbbbbbb\";\r\n",
22220             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
22221   EXPECT_EQ("#define A \\\r\n"
22222             "  b;      \\\r\n"
22223             "  c;      \\\r\n"
22224             "  d;\r\n",
22225             format("#define A \\\r\n"
22226                    "  b; \\\r\n"
22227                    "  c; d; \r\n",
22228                    getGoogleStyle()));
22229 
22230   EXPECT_EQ("/*\r\n"
22231             "multi line block comments\r\n"
22232             "should not introduce\r\n"
22233             "an extra carriage return\r\n"
22234             "*/\r\n",
22235             format("/*\r\n"
22236                    "multi line block comments\r\n"
22237                    "should not introduce\r\n"
22238                    "an extra carriage return\r\n"
22239                    "*/\r\n"));
22240   EXPECT_EQ("/*\r\n"
22241             "\r\n"
22242             "*/",
22243             format("/*\r\n"
22244                    "    \r\r\r\n"
22245                    "*/"));
22246 
22247   FormatStyle style = getLLVMStyle();
22248 
22249   style.DeriveLineEnding = true;
22250   style.UseCRLF = false;
22251   EXPECT_EQ("union FooBarBazQux {\n"
22252             "  int foo;\n"
22253             "  int bar;\n"
22254             "  int baz;\n"
22255             "};",
22256             format("union FooBarBazQux {\r\n"
22257                    "  int foo;\n"
22258                    "  int bar;\r\n"
22259                    "  int baz;\n"
22260                    "};",
22261                    style));
22262   style.UseCRLF = true;
22263   EXPECT_EQ("union FooBarBazQux {\r\n"
22264             "  int foo;\r\n"
22265             "  int bar;\r\n"
22266             "  int baz;\r\n"
22267             "};",
22268             format("union FooBarBazQux {\r\n"
22269                    "  int foo;\n"
22270                    "  int bar;\r\n"
22271                    "  int baz;\n"
22272                    "};",
22273                    style));
22274 
22275   style.DeriveLineEnding = false;
22276   style.UseCRLF = false;
22277   EXPECT_EQ("union FooBarBazQux {\n"
22278             "  int foo;\n"
22279             "  int bar;\n"
22280             "  int baz;\n"
22281             "  int qux;\n"
22282             "};",
22283             format("union FooBarBazQux {\r\n"
22284                    "  int foo;\n"
22285                    "  int bar;\r\n"
22286                    "  int baz;\n"
22287                    "  int qux;\r\n"
22288                    "};",
22289                    style));
22290   style.UseCRLF = true;
22291   EXPECT_EQ("union FooBarBazQux {\r\n"
22292             "  int foo;\r\n"
22293             "  int bar;\r\n"
22294             "  int baz;\r\n"
22295             "  int qux;\r\n"
22296             "};",
22297             format("union FooBarBazQux {\r\n"
22298                    "  int foo;\n"
22299                    "  int bar;\r\n"
22300                    "  int baz;\n"
22301                    "  int qux;\n"
22302                    "};",
22303                    style));
22304 
22305   style.DeriveLineEnding = true;
22306   style.UseCRLF = false;
22307   EXPECT_EQ("union FooBarBazQux {\r\n"
22308             "  int foo;\r\n"
22309             "  int bar;\r\n"
22310             "  int baz;\r\n"
22311             "  int qux;\r\n"
22312             "};",
22313             format("union FooBarBazQux {\r\n"
22314                    "  int foo;\n"
22315                    "  int bar;\r\n"
22316                    "  int baz;\n"
22317                    "  int qux;\r\n"
22318                    "};",
22319                    style));
22320   style.UseCRLF = true;
22321   EXPECT_EQ("union FooBarBazQux {\n"
22322             "  int foo;\n"
22323             "  int bar;\n"
22324             "  int baz;\n"
22325             "  int qux;\n"
22326             "};",
22327             format("union FooBarBazQux {\r\n"
22328                    "  int foo;\n"
22329                    "  int bar;\r\n"
22330                    "  int baz;\n"
22331                    "  int qux;\n"
22332                    "};",
22333                    style));
22334 }
22335 
22336 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
22337   verifyFormat("MY_CLASS(C) {\n"
22338                "  int i;\n"
22339                "  int j;\n"
22340                "};");
22341 }
22342 
22343 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
22344   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
22345   TwoIndent.ContinuationIndentWidth = 2;
22346 
22347   EXPECT_EQ("int i =\n"
22348             "  longFunction(\n"
22349             "    arg);",
22350             format("int i = longFunction(arg);", TwoIndent));
22351 
22352   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
22353   SixIndent.ContinuationIndentWidth = 6;
22354 
22355   EXPECT_EQ("int i =\n"
22356             "      longFunction(\n"
22357             "            arg);",
22358             format("int i = longFunction(arg);", SixIndent));
22359 }
22360 
22361 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
22362   FormatStyle Style = getLLVMStyle();
22363   verifyFormat("int Foo::getter(\n"
22364                "    //\n"
22365                ") const {\n"
22366                "  return foo;\n"
22367                "}",
22368                Style);
22369   verifyFormat("void Foo::setter(\n"
22370                "    //\n"
22371                ") {\n"
22372                "  foo = 1;\n"
22373                "}",
22374                Style);
22375 }
22376 
22377 TEST_F(FormatTest, SpacesInAngles) {
22378   FormatStyle Spaces = getLLVMStyle();
22379   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22380 
22381   verifyFormat("vector< ::std::string > x1;", Spaces);
22382   verifyFormat("Foo< int, Bar > x2;", Spaces);
22383   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22384 
22385   verifyFormat("static_cast< int >(arg);", Spaces);
22386   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22387   verifyFormat("f< int, float >();", Spaces);
22388   verifyFormat("template <> g() {}", Spaces);
22389   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22390   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22391   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22392                Spaces);
22393 
22394   Spaces.Standard = FormatStyle::LS_Cpp03;
22395   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22396   verifyFormat("A< A< int > >();", Spaces);
22397 
22398   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22399   verifyFormat("A<A<int> >();", Spaces);
22400 
22401   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22402   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22403                Spaces);
22404   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22405                Spaces);
22406 
22407   verifyFormat("A<A<int> >();", Spaces);
22408   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22409   verifyFormat("A< A< int > >();", Spaces);
22410 
22411   Spaces.Standard = FormatStyle::LS_Cpp11;
22412   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22413   verifyFormat("A< A< int > >();", Spaces);
22414 
22415   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22416   verifyFormat("vector<::std::string> x4;", Spaces);
22417   verifyFormat("vector<int> x5;", Spaces);
22418   verifyFormat("Foo<int, Bar> x6;", Spaces);
22419   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22420 
22421   verifyFormat("A<A<int>>();", Spaces);
22422 
22423   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22424   verifyFormat("vector<::std::string> x4;", Spaces);
22425   verifyFormat("vector< ::std::string > x4;", Spaces);
22426   verifyFormat("vector<int> x5;", Spaces);
22427   verifyFormat("vector< int > x5;", Spaces);
22428   verifyFormat("Foo<int, Bar> x6;", Spaces);
22429   verifyFormat("Foo< int, Bar > x6;", Spaces);
22430   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22431   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22432 
22433   verifyFormat("A<A<int>>();", Spaces);
22434   verifyFormat("A< A< int > >();", Spaces);
22435   verifyFormat("A<A<int > >();", Spaces);
22436   verifyFormat("A< A< int>>();", Spaces);
22437 
22438   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22439   verifyFormat("// clang-format off\n"
22440                "foo<<<1, 1>>>();\n"
22441                "// clang-format on\n",
22442                Spaces);
22443   verifyFormat("// clang-format off\n"
22444                "foo< < <1, 1> > >();\n"
22445                "// clang-format on\n",
22446                Spaces);
22447 }
22448 
22449 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22450   FormatStyle Style = getLLVMStyle();
22451   Style.SpaceAfterTemplateKeyword = false;
22452   verifyFormat("template<int> void foo();", Style);
22453 }
22454 
22455 TEST_F(FormatTest, TripleAngleBrackets) {
22456   verifyFormat("f<<<1, 1>>>();");
22457   verifyFormat("f<<<1, 1, 1, s>>>();");
22458   verifyFormat("f<<<a, b, c, d>>>();");
22459   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22460   verifyFormat("f<param><<<1, 1>>>();");
22461   verifyFormat("f<1><<<1, 1>>>();");
22462   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22463   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22464                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22465   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22466                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22467 }
22468 
22469 TEST_F(FormatTest, MergeLessLessAtEnd) {
22470   verifyFormat("<<");
22471   EXPECT_EQ("< < <", format("\\\n<<<"));
22472   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22473                "aaallvm::outs() <<");
22474   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22475                "aaaallvm::outs()\n    <<");
22476 }
22477 
22478 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22479   std::string code = "#if A\n"
22480                      "#if B\n"
22481                      "a.\n"
22482                      "#endif\n"
22483                      "    a = 1;\n"
22484                      "#else\n"
22485                      "#endif\n"
22486                      "#if C\n"
22487                      "#else\n"
22488                      "#endif\n";
22489   EXPECT_EQ(code, format(code));
22490 }
22491 
22492 TEST_F(FormatTest, HandleConflictMarkers) {
22493   // Git/SVN conflict markers.
22494   EXPECT_EQ("int a;\n"
22495             "void f() {\n"
22496             "  callme(some(parameter1,\n"
22497             "<<<<<<< text by the vcs\n"
22498             "              parameter2),\n"
22499             "||||||| text by the vcs\n"
22500             "              parameter2),\n"
22501             "         parameter3,\n"
22502             "======= text by the vcs\n"
22503             "              parameter2, parameter3),\n"
22504             ">>>>>>> text by the vcs\n"
22505             "         otherparameter);\n",
22506             format("int a;\n"
22507                    "void f() {\n"
22508                    "  callme(some(parameter1,\n"
22509                    "<<<<<<< text by the vcs\n"
22510                    "  parameter2),\n"
22511                    "||||||| text by the vcs\n"
22512                    "  parameter2),\n"
22513                    "  parameter3,\n"
22514                    "======= text by the vcs\n"
22515                    "  parameter2,\n"
22516                    "  parameter3),\n"
22517                    ">>>>>>> text by the vcs\n"
22518                    "  otherparameter);\n"));
22519 
22520   // Perforce markers.
22521   EXPECT_EQ("void f() {\n"
22522             "  function(\n"
22523             ">>>> text by the vcs\n"
22524             "      parameter,\n"
22525             "==== text by the vcs\n"
22526             "      parameter,\n"
22527             "==== text by the vcs\n"
22528             "      parameter,\n"
22529             "<<<< text by the vcs\n"
22530             "      parameter);\n",
22531             format("void f() {\n"
22532                    "  function(\n"
22533                    ">>>> text by the vcs\n"
22534                    "  parameter,\n"
22535                    "==== text by the vcs\n"
22536                    "  parameter,\n"
22537                    "==== text by the vcs\n"
22538                    "  parameter,\n"
22539                    "<<<< text by the vcs\n"
22540                    "  parameter);\n"));
22541 
22542   EXPECT_EQ("<<<<<<<\n"
22543             "|||||||\n"
22544             "=======\n"
22545             ">>>>>>>",
22546             format("<<<<<<<\n"
22547                    "|||||||\n"
22548                    "=======\n"
22549                    ">>>>>>>"));
22550 
22551   EXPECT_EQ("<<<<<<<\n"
22552             "|||||||\n"
22553             "int i;\n"
22554             "=======\n"
22555             ">>>>>>>",
22556             format("<<<<<<<\n"
22557                    "|||||||\n"
22558                    "int i;\n"
22559                    "=======\n"
22560                    ">>>>>>>"));
22561 
22562   // FIXME: Handle parsing of macros around conflict markers correctly:
22563   EXPECT_EQ("#define Macro \\\n"
22564             "<<<<<<<\n"
22565             "Something \\\n"
22566             "|||||||\n"
22567             "Else \\\n"
22568             "=======\n"
22569             "Other \\\n"
22570             ">>>>>>>\n"
22571             "    End int i;\n",
22572             format("#define Macro \\\n"
22573                    "<<<<<<<\n"
22574                    "  Something \\\n"
22575                    "|||||||\n"
22576                    "  Else \\\n"
22577                    "=======\n"
22578                    "  Other \\\n"
22579                    ">>>>>>>\n"
22580                    "  End\n"
22581                    "int i;\n"));
22582 
22583   verifyFormat(R"(====
22584 #ifdef A
22585 a
22586 #else
22587 b
22588 #endif
22589 )");
22590 }
22591 
22592 TEST_F(FormatTest, DisableRegions) {
22593   EXPECT_EQ("int i;\n"
22594             "// clang-format off\n"
22595             "  int j;\n"
22596             "// clang-format on\n"
22597             "int k;",
22598             format(" int  i;\n"
22599                    "   // clang-format off\n"
22600                    "  int j;\n"
22601                    " // clang-format on\n"
22602                    "   int   k;"));
22603   EXPECT_EQ("int i;\n"
22604             "/* clang-format off */\n"
22605             "  int j;\n"
22606             "/* clang-format on */\n"
22607             "int k;",
22608             format(" int  i;\n"
22609                    "   /* clang-format off */\n"
22610                    "  int j;\n"
22611                    " /* clang-format on */\n"
22612                    "   int   k;"));
22613 
22614   // Don't reflow comments within disabled regions.
22615   EXPECT_EQ("// clang-format off\n"
22616             "// long long long long long long line\n"
22617             "/* clang-format on */\n"
22618             "/* long long long\n"
22619             " * long long long\n"
22620             " * line */\n"
22621             "int i;\n"
22622             "/* clang-format off */\n"
22623             "/* long long long long long long line */\n",
22624             format("// clang-format off\n"
22625                    "// long long long long long long line\n"
22626                    "/* clang-format on */\n"
22627                    "/* long long long long long long line */\n"
22628                    "int i;\n"
22629                    "/* clang-format off */\n"
22630                    "/* long long long long long long line */\n",
22631                    getLLVMStyleWithColumns(20)));
22632 }
22633 
22634 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22635   format("? ) =");
22636   verifyNoCrash("#define a\\\n /**/}");
22637 }
22638 
22639 TEST_F(FormatTest, FormatsTableGenCode) {
22640   FormatStyle Style = getLLVMStyle();
22641   Style.Language = FormatStyle::LK_TableGen;
22642   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22643 }
22644 
22645 TEST_F(FormatTest, ArrayOfTemplates) {
22646   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22647             format("auto a = new unique_ptr<int > [ 10];"));
22648 
22649   FormatStyle Spaces = getLLVMStyle();
22650   Spaces.SpacesInSquareBrackets = true;
22651   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22652             format("auto a = new unique_ptr<int > [10];", Spaces));
22653 }
22654 
22655 TEST_F(FormatTest, ArrayAsTemplateType) {
22656   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22657             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22658 
22659   FormatStyle Spaces = getLLVMStyle();
22660   Spaces.SpacesInSquareBrackets = true;
22661   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22662             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22663 }
22664 
22665 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22666 
22667 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22668   llvm::vfs::InMemoryFileSystem FS;
22669   auto Style1 = getStyle("file", "", "Google", "", &FS);
22670   ASSERT_TRUE((bool)Style1);
22671   ASSERT_EQ(*Style1, getGoogleStyle());
22672 }
22673 
22674 TEST(FormatStyle, GetStyleOfFile) {
22675   llvm::vfs::InMemoryFileSystem FS;
22676   // Test 1: format file in the same directory.
22677   ASSERT_TRUE(
22678       FS.addFile("/a/.clang-format", 0,
22679                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22680   ASSERT_TRUE(
22681       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22682   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22683   ASSERT_TRUE((bool)Style1);
22684   ASSERT_EQ(*Style1, getLLVMStyle());
22685 
22686   // Test 2.1: fallback to default.
22687   ASSERT_TRUE(
22688       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22689   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22690   ASSERT_TRUE((bool)Style2);
22691   ASSERT_EQ(*Style2, getMozillaStyle());
22692 
22693   // Test 2.2: no format on 'none' fallback style.
22694   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22695   ASSERT_TRUE((bool)Style2);
22696   ASSERT_EQ(*Style2, getNoStyle());
22697 
22698   // Test 2.3: format if config is found with no based style while fallback is
22699   // 'none'.
22700   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22701                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22702   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22703   ASSERT_TRUE((bool)Style2);
22704   ASSERT_EQ(*Style2, getLLVMStyle());
22705 
22706   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22707   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22708   ASSERT_TRUE((bool)Style2);
22709   ASSERT_EQ(*Style2, getLLVMStyle());
22710 
22711   // Test 3: format file in parent directory.
22712   ASSERT_TRUE(
22713       FS.addFile("/c/.clang-format", 0,
22714                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22715   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22716                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22717   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22718   ASSERT_TRUE((bool)Style3);
22719   ASSERT_EQ(*Style3, getGoogleStyle());
22720 
22721   // Test 4: error on invalid fallback style
22722   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22723   ASSERT_FALSE((bool)Style4);
22724   llvm::consumeError(Style4.takeError());
22725 
22726   // Test 5: error on invalid yaml on command line
22727   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22728   ASSERT_FALSE((bool)Style5);
22729   llvm::consumeError(Style5.takeError());
22730 
22731   // Test 6: error on invalid style
22732   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22733   ASSERT_FALSE((bool)Style6);
22734   llvm::consumeError(Style6.takeError());
22735 
22736   // Test 7: found config file, error on parsing it
22737   ASSERT_TRUE(
22738       FS.addFile("/d/.clang-format", 0,
22739                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22740                                                   "InvalidKey: InvalidValue")));
22741   ASSERT_TRUE(
22742       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22743   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22744   ASSERT_FALSE((bool)Style7a);
22745   llvm::consumeError(Style7a.takeError());
22746 
22747   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22748   ASSERT_TRUE((bool)Style7b);
22749 
22750   // Test 8: inferred per-language defaults apply.
22751   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22752   ASSERT_TRUE((bool)StyleTd);
22753   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22754 
22755   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22756   // fallback style.
22757   ASSERT_TRUE(FS.addFile(
22758       "/e/sub/.clang-format", 0,
22759       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22760                                        "ColumnLimit: 20")));
22761   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22762                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22763   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22764   ASSERT_TRUE(static_cast<bool>(Style9));
22765   ASSERT_EQ(*Style9, [] {
22766     auto Style = getNoStyle();
22767     Style.ColumnLimit = 20;
22768     return Style;
22769   }());
22770 
22771   // Test 9.1.2: propagate more than one level with no parent file.
22772   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22773                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22774   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22775                          llvm::MemoryBuffer::getMemBuffer(
22776                              "BasedOnStyle: InheritParentConfig\n"
22777                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22778   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22779 
22780   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22781   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22782   ASSERT_TRUE(static_cast<bool>(Style9));
22783   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22784     auto Style = getNoStyle();
22785     Style.ColumnLimit = 20;
22786     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22787     return Style;
22788   }());
22789 
22790   // Test 9.2: with LLVM fallback style
22791   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22792   ASSERT_TRUE(static_cast<bool>(Style9));
22793   ASSERT_EQ(*Style9, [] {
22794     auto Style = getLLVMStyle();
22795     Style.ColumnLimit = 20;
22796     return Style;
22797   }());
22798 
22799   // Test 9.3: with a parent file
22800   ASSERT_TRUE(
22801       FS.addFile("/e/.clang-format", 0,
22802                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
22803                                                   "UseTab: Always")));
22804   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22805   ASSERT_TRUE(static_cast<bool>(Style9));
22806   ASSERT_EQ(*Style9, [] {
22807     auto Style = getGoogleStyle();
22808     Style.ColumnLimit = 20;
22809     Style.UseTab = FormatStyle::UT_Always;
22810     return Style;
22811   }());
22812 
22813   // Test 9.4: propagate more than one level with a parent file.
22814   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
22815     auto Style = getGoogleStyle();
22816     Style.ColumnLimit = 20;
22817     Style.UseTab = FormatStyle::UT_Always;
22818     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22819     return Style;
22820   }();
22821 
22822   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22823   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22824   ASSERT_TRUE(static_cast<bool>(Style9));
22825   ASSERT_EQ(*Style9, SubSubStyle);
22826 
22827   // Test 9.5: use InheritParentConfig as style name
22828   Style9 =
22829       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
22830   ASSERT_TRUE(static_cast<bool>(Style9));
22831   ASSERT_EQ(*Style9, SubSubStyle);
22832 
22833   // Test 9.6: use command line style with inheritance
22834   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
22835                     "none", "", &FS);
22836   ASSERT_TRUE(static_cast<bool>(Style9));
22837   ASSERT_EQ(*Style9, SubSubStyle);
22838 
22839   // Test 9.7: use command line style with inheritance and own config
22840   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
22841                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
22842                     "/e/sub/code.cpp", "none", "", &FS);
22843   ASSERT_TRUE(static_cast<bool>(Style9));
22844   ASSERT_EQ(*Style9, SubSubStyle);
22845 
22846   // Test 9.8: use inheritance from a file without BasedOnStyle
22847   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
22848                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
22849   ASSERT_TRUE(
22850       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
22851                  llvm::MemoryBuffer::getMemBuffer(
22852                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
22853   // Make sure we do not use the fallback style
22854   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
22855   ASSERT_TRUE(static_cast<bool>(Style9));
22856   ASSERT_EQ(*Style9, [] {
22857     auto Style = getLLVMStyle();
22858     Style.ColumnLimit = 123;
22859     return Style;
22860   }());
22861 
22862   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
22863   ASSERT_TRUE(static_cast<bool>(Style9));
22864   ASSERT_EQ(*Style9, [] {
22865     auto Style = getLLVMStyle();
22866     Style.ColumnLimit = 123;
22867     Style.IndentWidth = 7;
22868     return Style;
22869   }());
22870 
22871   // Test 9.9: use inheritance from a specific config file.
22872   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
22873                     "none", "", &FS);
22874   ASSERT_TRUE(static_cast<bool>(Style9));
22875   ASSERT_EQ(*Style9, SubSubStyle);
22876 }
22877 
22878 TEST(FormatStyle, GetStyleOfSpecificFile) {
22879   llvm::vfs::InMemoryFileSystem FS;
22880   // Specify absolute path to a format file in a parent directory.
22881   ASSERT_TRUE(
22882       FS.addFile("/e/.clang-format", 0,
22883                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22884   ASSERT_TRUE(
22885       FS.addFile("/e/explicit.clang-format", 0,
22886                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22887   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
22888                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22889   auto Style = getStyle("file:/e/explicit.clang-format",
22890                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22891   ASSERT_TRUE(static_cast<bool>(Style));
22892   ASSERT_EQ(*Style, getGoogleStyle());
22893 
22894   // Specify relative path to a format file.
22895   ASSERT_TRUE(
22896       FS.addFile("../../e/explicit.clang-format", 0,
22897                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22898   Style = getStyle("file:../../e/explicit.clang-format",
22899                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22900   ASSERT_TRUE(static_cast<bool>(Style));
22901   ASSERT_EQ(*Style, getGoogleStyle());
22902 
22903   // Specify path to a format file that does not exist.
22904   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
22905                    "LLVM", "", &FS);
22906   ASSERT_FALSE(static_cast<bool>(Style));
22907   llvm::consumeError(Style.takeError());
22908 
22909   // Specify path to a file on the filesystem.
22910   SmallString<128> FormatFilePath;
22911   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
22912       "FormatFileTest", "tpl", FormatFilePath);
22913   EXPECT_FALSE((bool)ECF);
22914   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
22915   EXPECT_FALSE((bool)ECF);
22916   FormatFileTest << "BasedOnStyle: Google\n";
22917   FormatFileTest.close();
22918 
22919   SmallString<128> TestFilePath;
22920   std::error_code ECT =
22921       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
22922   EXPECT_FALSE((bool)ECT);
22923   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
22924   CodeFileTest << "int i;\n";
22925   CodeFileTest.close();
22926 
22927   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
22928   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
22929 
22930   llvm::sys::fs::remove(FormatFilePath.c_str());
22931   llvm::sys::fs::remove(TestFilePath.c_str());
22932   ASSERT_TRUE(static_cast<bool>(Style));
22933   ASSERT_EQ(*Style, getGoogleStyle());
22934 }
22935 
22936 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
22937   // Column limit is 20.
22938   std::string Code = "Type *a =\n"
22939                      "    new Type();\n"
22940                      "g(iiiii, 0, jjjjj,\n"
22941                      "  0, kkkkk, 0, mm);\n"
22942                      "int  bad     = format   ;";
22943   std::string Expected = "auto a = new Type();\n"
22944                          "g(iiiii, nullptr,\n"
22945                          "  jjjjj, nullptr,\n"
22946                          "  kkkkk, nullptr,\n"
22947                          "  mm);\n"
22948                          "int  bad     = format   ;";
22949   FileID ID = Context.createInMemoryFile("format.cpp", Code);
22950   tooling::Replacements Replaces = toReplacements(
22951       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
22952                             "auto "),
22953        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
22954                             "nullptr"),
22955        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
22956                             "nullptr"),
22957        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
22958                             "nullptr")});
22959 
22960   FormatStyle Style = getLLVMStyle();
22961   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
22962   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22963   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22964       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22965   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22966   EXPECT_TRUE(static_cast<bool>(Result));
22967   EXPECT_EQ(Expected, *Result);
22968 }
22969 
22970 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
22971   std::string Code = "#include \"a.h\"\n"
22972                      "#include \"c.h\"\n"
22973                      "\n"
22974                      "int main() {\n"
22975                      "  return 0;\n"
22976                      "}";
22977   std::string Expected = "#include \"a.h\"\n"
22978                          "#include \"b.h\"\n"
22979                          "#include \"c.h\"\n"
22980                          "\n"
22981                          "int main() {\n"
22982                          "  return 0;\n"
22983                          "}";
22984   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
22985   tooling::Replacements Replaces = toReplacements(
22986       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
22987                             "#include \"b.h\"\n")});
22988 
22989   FormatStyle Style = getLLVMStyle();
22990   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
22991   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22992   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22993       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22994   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22995   EXPECT_TRUE(static_cast<bool>(Result));
22996   EXPECT_EQ(Expected, *Result);
22997 }
22998 
22999 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
23000   EXPECT_EQ("using std::cin;\n"
23001             "using std::cout;",
23002             format("using std::cout;\n"
23003                    "using std::cin;",
23004                    getGoogleStyle()));
23005 }
23006 
23007 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
23008   FormatStyle Style = getLLVMStyle();
23009   Style.Standard = FormatStyle::LS_Cpp03;
23010   // cpp03 recognize this string as identifier u8 and literal character 'a'
23011   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
23012 }
23013 
23014 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
23015   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
23016   // all modes, including C++11, C++14 and C++17
23017   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
23018 }
23019 
23020 TEST_F(FormatTest, DoNotFormatLikelyXml) {
23021   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
23022   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
23023 }
23024 
23025 TEST_F(FormatTest, StructuredBindings) {
23026   // Structured bindings is a C++17 feature.
23027   // all modes, including C++11, C++14 and C++17
23028   verifyFormat("auto [a, b] = f();");
23029   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
23030   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
23031   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
23032   EXPECT_EQ("auto const volatile [a, b] = f();",
23033             format("auto  const   volatile[a, b] = f();"));
23034   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
23035   EXPECT_EQ("auto &[a, b, c] = f();",
23036             format("auto   &[  a  ,  b,c   ] = f();"));
23037   EXPECT_EQ("auto &&[a, b, c] = f();",
23038             format("auto   &&[  a  ,  b,c   ] = f();"));
23039   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
23040   EXPECT_EQ("auto const volatile &&[a, b] = f();",
23041             format("auto  const  volatile  &&[a, b] = f();"));
23042   EXPECT_EQ("auto const &&[a, b] = f();",
23043             format("auto  const   &&  [a, b] = f();"));
23044   EXPECT_EQ("const auto &[a, b] = f();",
23045             format("const  auto  &  [a, b] = f();"));
23046   EXPECT_EQ("const auto volatile &&[a, b] = f();",
23047             format("const  auto   volatile  &&[a, b] = f();"));
23048   EXPECT_EQ("volatile const auto &&[a, b] = f();",
23049             format("volatile  const  auto   &&[a, b] = f();"));
23050   EXPECT_EQ("const auto &&[a, b] = f();",
23051             format("const  auto  &&  [a, b] = f();"));
23052 
23053   // Make sure we don't mistake structured bindings for lambdas.
23054   FormatStyle PointerMiddle = getLLVMStyle();
23055   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
23056   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
23057   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
23058   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
23059   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
23060   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
23061   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
23062   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
23063   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
23064   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
23065   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
23066   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
23067   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
23068 
23069   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
23070             format("for (const auto   &&   [a, b] : some_range) {\n}"));
23071   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
23072             format("for (const auto   &   [a, b] : some_range) {\n}"));
23073   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
23074             format("for (const auto[a, b] : some_range) {\n}"));
23075   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
23076   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
23077   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
23078   EXPECT_EQ("auto const &[x, y](expr);",
23079             format("auto  const  &  [x,y]  (expr);"));
23080   EXPECT_EQ("auto const &&[x, y](expr);",
23081             format("auto  const  &&  [x,y]  (expr);"));
23082   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
23083   EXPECT_EQ("auto const &[x, y]{expr};",
23084             format("auto  const  &  [x,y]  {expr};"));
23085   EXPECT_EQ("auto const &&[x, y]{expr};",
23086             format("auto  const  &&  [x,y]  {expr};"));
23087 
23088   FormatStyle Spaces = getLLVMStyle();
23089   Spaces.SpacesInSquareBrackets = true;
23090   verifyFormat("auto [ a, b ] = f();", Spaces);
23091   verifyFormat("auto &&[ a, b ] = f();", Spaces);
23092   verifyFormat("auto &[ a, b ] = f();", Spaces);
23093   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
23094   verifyFormat("auto const &[ a, b ] = f();", Spaces);
23095 }
23096 
23097 TEST_F(FormatTest, FileAndCode) {
23098   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
23099   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
23100   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
23101   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
23102   EXPECT_EQ(FormatStyle::LK_ObjC,
23103             guessLanguage("foo.h", "@interface Foo\n@end\n"));
23104   EXPECT_EQ(
23105       FormatStyle::LK_ObjC,
23106       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
23107   EXPECT_EQ(FormatStyle::LK_ObjC,
23108             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
23109   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
23110   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
23111   EXPECT_EQ(FormatStyle::LK_ObjC,
23112             guessLanguage("foo", "@interface Foo\n@end\n"));
23113   EXPECT_EQ(FormatStyle::LK_ObjC,
23114             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
23115   EXPECT_EQ(
23116       FormatStyle::LK_ObjC,
23117       guessLanguage("foo.h",
23118                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
23119   EXPECT_EQ(
23120       FormatStyle::LK_Cpp,
23121       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
23122   // Only one of the two preprocessor regions has ObjC-like code.
23123   EXPECT_EQ(FormatStyle::LK_ObjC,
23124             guessLanguage("foo.h", "#if A\n"
23125                                    "#define B() C\n"
23126                                    "#else\n"
23127                                    "#define B() [NSString a:@\"\"]\n"
23128                                    "#endif\n"));
23129 }
23130 
23131 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
23132   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
23133   EXPECT_EQ(FormatStyle::LK_ObjC,
23134             guessLanguage("foo.h", "array[[calculator getIndex]];"));
23135   EXPECT_EQ(FormatStyle::LK_Cpp,
23136             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
23137   EXPECT_EQ(
23138       FormatStyle::LK_Cpp,
23139       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
23140   EXPECT_EQ(FormatStyle::LK_ObjC,
23141             guessLanguage("foo.h", "[[noreturn foo] bar];"));
23142   EXPECT_EQ(FormatStyle::LK_Cpp,
23143             guessLanguage("foo.h", "[[clang::fallthrough]];"));
23144   EXPECT_EQ(FormatStyle::LK_ObjC,
23145             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
23146   EXPECT_EQ(FormatStyle::LK_Cpp,
23147             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
23148   EXPECT_EQ(FormatStyle::LK_Cpp,
23149             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
23150   EXPECT_EQ(FormatStyle::LK_ObjC,
23151             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
23152   EXPECT_EQ(FormatStyle::LK_Cpp,
23153             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
23154   EXPECT_EQ(
23155       FormatStyle::LK_Cpp,
23156       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
23157   EXPECT_EQ(
23158       FormatStyle::LK_Cpp,
23159       guessLanguage("foo.h",
23160                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
23161   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
23162 }
23163 
23164 TEST_F(FormatTest, GuessLanguageWithCaret) {
23165   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
23166   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
23167   EXPECT_EQ(FormatStyle::LK_ObjC,
23168             guessLanguage("foo.h", "int(^)(char, float);"));
23169   EXPECT_EQ(FormatStyle::LK_ObjC,
23170             guessLanguage("foo.h", "int(^foo)(char, float);"));
23171   EXPECT_EQ(FormatStyle::LK_ObjC,
23172             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
23173   EXPECT_EQ(FormatStyle::LK_ObjC,
23174             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
23175   EXPECT_EQ(
23176       FormatStyle::LK_ObjC,
23177       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
23178 }
23179 
23180 TEST_F(FormatTest, GuessLanguageWithPragmas) {
23181   EXPECT_EQ(FormatStyle::LK_Cpp,
23182             guessLanguage("foo.h", "__pragma(warning(disable:))"));
23183   EXPECT_EQ(FormatStyle::LK_Cpp,
23184             guessLanguage("foo.h", "#pragma(warning(disable:))"));
23185   EXPECT_EQ(FormatStyle::LK_Cpp,
23186             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
23187 }
23188 
23189 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
23190   // ASM symbolic names are identifiers that must be surrounded by [] without
23191   // space in between:
23192   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
23193 
23194   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
23195   verifyFormat(R"(//
23196 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
23197 )");
23198 
23199   // A list of several ASM symbolic names.
23200   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
23201 
23202   // ASM symbolic names in inline ASM with inputs and outputs.
23203   verifyFormat(R"(//
23204 asm("cmoveq %1, %2, %[result]"
23205     : [result] "=r"(result)
23206     : "r"(test), "r"(new), "[result]"(old));
23207 )");
23208 
23209   // ASM symbolic names in inline ASM with no outputs.
23210   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
23211 }
23212 
23213 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
23214   EXPECT_EQ(FormatStyle::LK_Cpp,
23215             guessLanguage("foo.h", "void f() {\n"
23216                                    "  asm (\"mov %[e], %[d]\"\n"
23217                                    "     : [d] \"=rm\" (d)\n"
23218                                    "       [e] \"rm\" (*e));\n"
23219                                    "}"));
23220   EXPECT_EQ(FormatStyle::LK_Cpp,
23221             guessLanguage("foo.h", "void f() {\n"
23222                                    "  _asm (\"mov %[e], %[d]\"\n"
23223                                    "     : [d] \"=rm\" (d)\n"
23224                                    "       [e] \"rm\" (*e));\n"
23225                                    "}"));
23226   EXPECT_EQ(FormatStyle::LK_Cpp,
23227             guessLanguage("foo.h", "void f() {\n"
23228                                    "  __asm (\"mov %[e], %[d]\"\n"
23229                                    "     : [d] \"=rm\" (d)\n"
23230                                    "       [e] \"rm\" (*e));\n"
23231                                    "}"));
23232   EXPECT_EQ(FormatStyle::LK_Cpp,
23233             guessLanguage("foo.h", "void f() {\n"
23234                                    "  __asm__ (\"mov %[e], %[d]\"\n"
23235                                    "     : [d] \"=rm\" (d)\n"
23236                                    "       [e] \"rm\" (*e));\n"
23237                                    "}"));
23238   EXPECT_EQ(FormatStyle::LK_Cpp,
23239             guessLanguage("foo.h", "void f() {\n"
23240                                    "  asm (\"mov %[e], %[d]\"\n"
23241                                    "     : [d] \"=rm\" (d),\n"
23242                                    "       [e] \"rm\" (*e));\n"
23243                                    "}"));
23244   EXPECT_EQ(FormatStyle::LK_Cpp,
23245             guessLanguage("foo.h", "void f() {\n"
23246                                    "  asm volatile (\"mov %[e], %[d]\"\n"
23247                                    "     : [d] \"=rm\" (d)\n"
23248                                    "       [e] \"rm\" (*e));\n"
23249                                    "}"));
23250 }
23251 
23252 TEST_F(FormatTest, GuessLanguageWithChildLines) {
23253   EXPECT_EQ(FormatStyle::LK_Cpp,
23254             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
23255   EXPECT_EQ(FormatStyle::LK_ObjC,
23256             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
23257   EXPECT_EQ(
23258       FormatStyle::LK_Cpp,
23259       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
23260   EXPECT_EQ(
23261       FormatStyle::LK_ObjC,
23262       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
23263 }
23264 
23265 TEST_F(FormatTest, TypenameMacros) {
23266   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
23267 
23268   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
23269   FormatStyle Google = getGoogleStyleWithColumns(0);
23270   Google.TypenameMacros = TypenameMacros;
23271   verifyFormat("struct foo {\n"
23272                "  int bar;\n"
23273                "  TAILQ_ENTRY(a) bleh;\n"
23274                "};",
23275                Google);
23276 
23277   FormatStyle Macros = getLLVMStyle();
23278   Macros.TypenameMacros = TypenameMacros;
23279 
23280   verifyFormat("STACK_OF(int) a;", Macros);
23281   verifyFormat("STACK_OF(int) *a;", Macros);
23282   verifyFormat("STACK_OF(int const *) *a;", Macros);
23283   verifyFormat("STACK_OF(int *const) *a;", Macros);
23284   verifyFormat("STACK_OF(int, string) a;", Macros);
23285   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
23286   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
23287   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
23288   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
23289   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
23290   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
23291 
23292   Macros.PointerAlignment = FormatStyle::PAS_Left;
23293   verifyFormat("STACK_OF(int)* a;", Macros);
23294   verifyFormat("STACK_OF(int*)* a;", Macros);
23295   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
23296   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
23297   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
23298 }
23299 
23300 TEST_F(FormatTest, AtomicQualifier) {
23301   // Check that we treate _Atomic as a type and not a function call
23302   FormatStyle Google = getGoogleStyleWithColumns(0);
23303   verifyFormat("struct foo {\n"
23304                "  int a1;\n"
23305                "  _Atomic(a) a2;\n"
23306                "  _Atomic(_Atomic(int) *const) a3;\n"
23307                "};",
23308                Google);
23309   verifyFormat("_Atomic(uint64_t) a;");
23310   verifyFormat("_Atomic(uint64_t) *a;");
23311   verifyFormat("_Atomic(uint64_t const *) *a;");
23312   verifyFormat("_Atomic(uint64_t *const) *a;");
23313   verifyFormat("_Atomic(const uint64_t *) *a;");
23314   verifyFormat("_Atomic(uint64_t) a;");
23315   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
23316   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
23317   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
23318   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
23319 
23320   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
23321   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
23322   FormatStyle Style = getLLVMStyle();
23323   Style.PointerAlignment = FormatStyle::PAS_Left;
23324   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
23325   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
23326   verifyFormat("_Atomic(int)* a;", Style);
23327   verifyFormat("_Atomic(int*)* a;", Style);
23328   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
23329 
23330   Style.SpacesInCStyleCastParentheses = true;
23331   Style.SpacesInParentheses = false;
23332   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
23333   Style.SpacesInCStyleCastParentheses = false;
23334   Style.SpacesInParentheses = true;
23335   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
23336   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
23337 }
23338 
23339 TEST_F(FormatTest, AmbersandInLamda) {
23340   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
23341   FormatStyle AlignStyle = getLLVMStyle();
23342   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
23343   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23344   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
23345   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23346 }
23347 
23348 TEST_F(FormatTest, SpacesInConditionalStatement) {
23349   FormatStyle Spaces = getLLVMStyle();
23350   Spaces.IfMacros.clear();
23351   Spaces.IfMacros.push_back("MYIF");
23352   Spaces.SpacesInConditionalStatement = true;
23353   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
23354   verifyFormat("if ( !a )\n  return;", Spaces);
23355   verifyFormat("if ( a )\n  return;", Spaces);
23356   verifyFormat("if constexpr ( a )\n  return;", Spaces);
23357   verifyFormat("MYIF ( a )\n  return;", Spaces);
23358   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
23359   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
23360   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
23361   verifyFormat("while ( a )\n  return;", Spaces);
23362   verifyFormat("while ( (a && b) )\n  return;", Spaces);
23363   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
23364   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
23365   // Check that space on the left of "::" is inserted as expected at beginning
23366   // of condition.
23367   verifyFormat("while ( ::func() )\n  return;", Spaces);
23368 
23369   // Check impact of ControlStatementsExceptControlMacros is honored.
23370   Spaces.SpaceBeforeParens =
23371       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
23372   verifyFormat("MYIF( a )\n  return;", Spaces);
23373   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
23374   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
23375 }
23376 
23377 TEST_F(FormatTest, AlternativeOperators) {
23378   // Test case for ensuring alternate operators are not
23379   // combined with their right most neighbour.
23380   verifyFormat("int a and b;");
23381   verifyFormat("int a and_eq b;");
23382   verifyFormat("int a bitand b;");
23383   verifyFormat("int a bitor b;");
23384   verifyFormat("int a compl b;");
23385   verifyFormat("int a not b;");
23386   verifyFormat("int a not_eq b;");
23387   verifyFormat("int a or b;");
23388   verifyFormat("int a xor b;");
23389   verifyFormat("int a xor_eq b;");
23390   verifyFormat("return this not_eq bitand other;");
23391   verifyFormat("bool operator not_eq(const X bitand other)");
23392 
23393   verifyFormat("int a and 5;");
23394   verifyFormat("int a and_eq 5;");
23395   verifyFormat("int a bitand 5;");
23396   verifyFormat("int a bitor 5;");
23397   verifyFormat("int a compl 5;");
23398   verifyFormat("int a not 5;");
23399   verifyFormat("int a not_eq 5;");
23400   verifyFormat("int a or 5;");
23401   verifyFormat("int a xor 5;");
23402   verifyFormat("int a xor_eq 5;");
23403 
23404   verifyFormat("int a compl(5);");
23405   verifyFormat("int a not(5);");
23406 
23407   /* FIXME handle alternate tokens
23408    * https://en.cppreference.com/w/cpp/language/operator_alternative
23409   // alternative tokens
23410   verifyFormat("compl foo();");     //  ~foo();
23411   verifyFormat("foo() <%%>;");      // foo();
23412   verifyFormat("void foo() <%%>;"); // void foo(){}
23413   verifyFormat("int a <:1:>;");     // int a[1];[
23414   verifyFormat("%:define ABC abc"); // #define ABC abc
23415   verifyFormat("%:%:");             // ##
23416   */
23417 }
23418 
23419 TEST_F(FormatTest, STLWhileNotDefineChed) {
23420   verifyFormat("#if defined(while)\n"
23421                "#define while EMIT WARNING C4005\n"
23422                "#endif // while");
23423 }
23424 
23425 TEST_F(FormatTest, OperatorSpacing) {
23426   FormatStyle Style = getLLVMStyle();
23427   Style.PointerAlignment = FormatStyle::PAS_Right;
23428   verifyFormat("Foo::operator*();", Style);
23429   verifyFormat("Foo::operator void *();", Style);
23430   verifyFormat("Foo::operator void **();", Style);
23431   verifyFormat("Foo::operator void *&();", Style);
23432   verifyFormat("Foo::operator void *&&();", Style);
23433   verifyFormat("Foo::operator void const *();", Style);
23434   verifyFormat("Foo::operator void const **();", Style);
23435   verifyFormat("Foo::operator void const *&();", Style);
23436   verifyFormat("Foo::operator void const *&&();", Style);
23437   verifyFormat("Foo::operator()(void *);", Style);
23438   verifyFormat("Foo::operator*(void *);", Style);
23439   verifyFormat("Foo::operator*();", Style);
23440   verifyFormat("Foo::operator**();", Style);
23441   verifyFormat("Foo::operator&();", Style);
23442   verifyFormat("Foo::operator<int> *();", Style);
23443   verifyFormat("Foo::operator<Foo> *();", Style);
23444   verifyFormat("Foo::operator<int> **();", Style);
23445   verifyFormat("Foo::operator<Foo> **();", Style);
23446   verifyFormat("Foo::operator<int> &();", Style);
23447   verifyFormat("Foo::operator<Foo> &();", Style);
23448   verifyFormat("Foo::operator<int> &&();", Style);
23449   verifyFormat("Foo::operator<Foo> &&();", Style);
23450   verifyFormat("Foo::operator<int> *&();", Style);
23451   verifyFormat("Foo::operator<Foo> *&();", Style);
23452   verifyFormat("Foo::operator<int> *&&();", Style);
23453   verifyFormat("Foo::operator<Foo> *&&();", Style);
23454   verifyFormat("operator*(int (*)(), class Foo);", Style);
23455 
23456   verifyFormat("Foo::operator&();", Style);
23457   verifyFormat("Foo::operator void &();", Style);
23458   verifyFormat("Foo::operator void const &();", Style);
23459   verifyFormat("Foo::operator()(void &);", Style);
23460   verifyFormat("Foo::operator&(void &);", Style);
23461   verifyFormat("Foo::operator&();", Style);
23462   verifyFormat("operator&(int (&)(), class Foo);", Style);
23463   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23464 
23465   verifyFormat("Foo::operator&&();", Style);
23466   verifyFormat("Foo::operator**();", Style);
23467   verifyFormat("Foo::operator void &&();", Style);
23468   verifyFormat("Foo::operator void const &&();", Style);
23469   verifyFormat("Foo::operator()(void &&);", Style);
23470   verifyFormat("Foo::operator&&(void &&);", Style);
23471   verifyFormat("Foo::operator&&();", Style);
23472   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23473   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23474   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23475                Style);
23476   verifyFormat("operator void **()", Style);
23477   verifyFormat("operator const FooRight<Object> &()", Style);
23478   verifyFormat("operator const FooRight<Object> *()", Style);
23479   verifyFormat("operator const FooRight<Object> **()", Style);
23480   verifyFormat("operator const FooRight<Object> *&()", Style);
23481   verifyFormat("operator const FooRight<Object> *&&()", Style);
23482 
23483   Style.PointerAlignment = FormatStyle::PAS_Left;
23484   verifyFormat("Foo::operator*();", Style);
23485   verifyFormat("Foo::operator**();", Style);
23486   verifyFormat("Foo::operator void*();", Style);
23487   verifyFormat("Foo::operator void**();", Style);
23488   verifyFormat("Foo::operator void*&();", Style);
23489   verifyFormat("Foo::operator void*&&();", Style);
23490   verifyFormat("Foo::operator void const*();", Style);
23491   verifyFormat("Foo::operator void const**();", Style);
23492   verifyFormat("Foo::operator void const*&();", Style);
23493   verifyFormat("Foo::operator void const*&&();", Style);
23494   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23495   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23496   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23497   verifyFormat("Foo::operator()(void*);", Style);
23498   verifyFormat("Foo::operator*(void*);", Style);
23499   verifyFormat("Foo::operator*();", Style);
23500   verifyFormat("Foo::operator<int>*();", Style);
23501   verifyFormat("Foo::operator<Foo>*();", Style);
23502   verifyFormat("Foo::operator<int>**();", Style);
23503   verifyFormat("Foo::operator<Foo>**();", Style);
23504   verifyFormat("Foo::operator<Foo>*&();", Style);
23505   verifyFormat("Foo::operator<int>&();", Style);
23506   verifyFormat("Foo::operator<Foo>&();", Style);
23507   verifyFormat("Foo::operator<int>&&();", Style);
23508   verifyFormat("Foo::operator<Foo>&&();", Style);
23509   verifyFormat("Foo::operator<int>*&();", Style);
23510   verifyFormat("Foo::operator<Foo>*&();", Style);
23511   verifyFormat("operator*(int (*)(), class Foo);", Style);
23512 
23513   verifyFormat("Foo::operator&();", Style);
23514   verifyFormat("Foo::operator void&();", Style);
23515   verifyFormat("Foo::operator void const&();", Style);
23516   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23517   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23518   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", 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   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23524   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23525 
23526   verifyFormat("Foo::operator&&();", Style);
23527   verifyFormat("Foo::operator void&&();", Style);
23528   verifyFormat("Foo::operator void const&&();", Style);
23529   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23530   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23531   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23532   verifyFormat("Foo::operator()(void&&);", Style);
23533   verifyFormat("Foo::operator&&(void&&);", Style);
23534   verifyFormat("Foo::operator&&();", Style);
23535   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23536   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23537   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23538                Style);
23539   verifyFormat("operator void**()", Style);
23540   verifyFormat("operator const FooLeft<Object>&()", Style);
23541   verifyFormat("operator const FooLeft<Object>*()", Style);
23542   verifyFormat("operator const FooLeft<Object>**()", Style);
23543   verifyFormat("operator const FooLeft<Object>*&()", Style);
23544   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23545 
23546   // PR45107
23547   verifyFormat("operator Vector<String>&();", Style);
23548   verifyFormat("operator const Vector<String>&();", Style);
23549   verifyFormat("operator foo::Bar*();", Style);
23550   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23551   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23552                Style);
23553 
23554   Style.PointerAlignment = FormatStyle::PAS_Middle;
23555   verifyFormat("Foo::operator*();", Style);
23556   verifyFormat("Foo::operator void *();", Style);
23557   verifyFormat("Foo::operator()(void *);", Style);
23558   verifyFormat("Foo::operator*(void *);", Style);
23559   verifyFormat("Foo::operator*();", Style);
23560   verifyFormat("operator*(int (*)(), class Foo);", Style);
23561 
23562   verifyFormat("Foo::operator&();", Style);
23563   verifyFormat("Foo::operator void &();", Style);
23564   verifyFormat("Foo::operator void const &();", Style);
23565   verifyFormat("Foo::operator()(void &);", Style);
23566   verifyFormat("Foo::operator&(void &);", Style);
23567   verifyFormat("Foo::operator&();", Style);
23568   verifyFormat("operator&(int (&)(), class Foo);", Style);
23569 
23570   verifyFormat("Foo::operator&&();", Style);
23571   verifyFormat("Foo::operator void &&();", Style);
23572   verifyFormat("Foo::operator void const &&();", Style);
23573   verifyFormat("Foo::operator()(void &&);", Style);
23574   verifyFormat("Foo::operator&&(void &&);", Style);
23575   verifyFormat("Foo::operator&&();", Style);
23576   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23577 }
23578 
23579 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23580   FormatStyle Style = getLLVMStyle();
23581   // PR46157
23582   verifyFormat("foo(operator+, -42);", Style);
23583   verifyFormat("foo(operator++, -42);", Style);
23584   verifyFormat("foo(operator--, -42);", Style);
23585   verifyFormat("foo(-42, operator--);", Style);
23586   verifyFormat("foo(-42, operator, );", Style);
23587   verifyFormat("foo(operator, , -42);", Style);
23588 }
23589 
23590 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23591   FormatStyle Style = getLLVMStyle();
23592   Style.WhitespaceSensitiveMacros.push_back("FOO");
23593 
23594   // Don't use the helpers here, since 'mess up' will change the whitespace
23595   // and these are all whitespace sensitive by definition
23596   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23597             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23598   EXPECT_EQ(
23599       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23600       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23601   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23602             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23603   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23604             "       Still=Intentional);",
23605             format("FOO(String-ized&Messy+But,: :\n"
23606                    "       Still=Intentional);",
23607                    Style));
23608   Style.AlignConsecutiveAssignments.Enabled = true;
23609   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23610             "       Still=Intentional);",
23611             format("FOO(String-ized=&Messy+But,: :\n"
23612                    "       Still=Intentional);",
23613                    Style));
23614 
23615   Style.ColumnLimit = 21;
23616   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23617             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23618 }
23619 
23620 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23621   // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
23622   // test its interaction with line wrapping
23623   FormatStyle Style = getLLVMStyleWithColumns(80);
23624   verifyFormat("namespace {\n"
23625                "int i;\n"
23626                "int j;\n"
23627                "} // namespace",
23628                Style);
23629 
23630   verifyFormat("namespace AAA {\n"
23631                "int i;\n"
23632                "int j;\n"
23633                "} // namespace AAA",
23634                Style);
23635 
23636   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23637             "int i;\n"
23638             "int j;\n"
23639             "} // namespace Averyveryveryverylongnamespace",
23640             format("namespace Averyveryveryverylongnamespace {\n"
23641                    "int i;\n"
23642                    "int j;\n"
23643                    "}",
23644                    Style));
23645 
23646   EXPECT_EQ(
23647       "namespace "
23648       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23649       "    went::mad::now {\n"
23650       "int i;\n"
23651       "int j;\n"
23652       "} // namespace\n"
23653       "  // "
23654       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23655       "went::mad::now",
23656       format("namespace "
23657              "would::it::save::you::a::lot::of::time::if_::i::"
23658              "just::gave::up::and_::went::mad::now {\n"
23659              "int i;\n"
23660              "int j;\n"
23661              "}",
23662              Style));
23663 
23664   // This used to duplicate the comment again and again on subsequent runs
23665   EXPECT_EQ(
23666       "namespace "
23667       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23668       "    went::mad::now {\n"
23669       "int i;\n"
23670       "int j;\n"
23671       "} // namespace\n"
23672       "  // "
23673       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23674       "went::mad::now",
23675       format("namespace "
23676              "would::it::save::you::a::lot::of::time::if_::i::"
23677              "just::gave::up::and_::went::mad::now {\n"
23678              "int i;\n"
23679              "int j;\n"
23680              "} // namespace\n"
23681              "  // "
23682              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23683              "and_::went::mad::now",
23684              Style));
23685 }
23686 
23687 TEST_F(FormatTest, LikelyUnlikely) {
23688   FormatStyle Style = getLLVMStyle();
23689 
23690   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23691                "  return 29;\n"
23692                "}",
23693                Style);
23694 
23695   verifyFormat("if (argc > 5) [[likely]] {\n"
23696                "  return 29;\n"
23697                "}",
23698                Style);
23699 
23700   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23701                "  return 29;\n"
23702                "} else [[likely]] {\n"
23703                "  return 42;\n"
23704                "}\n",
23705                Style);
23706 
23707   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23708                "  return 29;\n"
23709                "} else if (argc > 10) [[likely]] {\n"
23710                "  return 99;\n"
23711                "} else {\n"
23712                "  return 42;\n"
23713                "}\n",
23714                Style);
23715 
23716   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23717                "  return 29;\n"
23718                "}",
23719                Style);
23720 
23721   verifyFormat("if (argc > 5) [[unlikely]]\n"
23722                "  return 29;\n",
23723                Style);
23724   verifyFormat("if (argc > 5) [[likely]]\n"
23725                "  return 29;\n",
23726                Style);
23727 
23728   Style.AttributeMacros.push_back("UNLIKELY");
23729   Style.AttributeMacros.push_back("LIKELY");
23730   verifyFormat("if (argc > 5) UNLIKELY\n"
23731                "  return 29;\n",
23732                Style);
23733 
23734   verifyFormat("if (argc > 5) UNLIKELY {\n"
23735                "  return 29;\n"
23736                "}",
23737                Style);
23738   verifyFormat("if (argc > 5) UNLIKELY {\n"
23739                "  return 29;\n"
23740                "} else [[likely]] {\n"
23741                "  return 42;\n"
23742                "}\n",
23743                Style);
23744   verifyFormat("if (argc > 5) UNLIKELY {\n"
23745                "  return 29;\n"
23746                "} else LIKELY {\n"
23747                "  return 42;\n"
23748                "}\n",
23749                Style);
23750   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23751                "  return 29;\n"
23752                "} else LIKELY {\n"
23753                "  return 42;\n"
23754                "}\n",
23755                Style);
23756 }
23757 
23758 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23759   verifyFormat("Constructor()\n"
23760                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23761                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23762                "aaaaaaaaaaaaaaaaaat))");
23763   verifyFormat("Constructor()\n"
23764                "    : aaaaaaaaaaaaa(aaaaaa), "
23765                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
23766 
23767   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
23768   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
23769   verifyFormat("Constructor()\n"
23770                "    : aaaaaa(aaaaaa),\n"
23771                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23772                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
23773                StyleWithWhitespacePenalty);
23774   verifyFormat("Constructor()\n"
23775                "    : aaaaaaaaaaaaa(aaaaaa), "
23776                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
23777                StyleWithWhitespacePenalty);
23778 }
23779 
23780 TEST_F(FormatTest, LLVMDefaultStyle) {
23781   FormatStyle Style = getLLVMStyle();
23782   verifyFormat("extern \"C\" {\n"
23783                "int foo();\n"
23784                "}",
23785                Style);
23786 }
23787 TEST_F(FormatTest, GNUDefaultStyle) {
23788   FormatStyle Style = getGNUStyle();
23789   verifyFormat("extern \"C\"\n"
23790                "{\n"
23791                "  int foo ();\n"
23792                "}",
23793                Style);
23794 }
23795 TEST_F(FormatTest, MozillaDefaultStyle) {
23796   FormatStyle Style = getMozillaStyle();
23797   verifyFormat("extern \"C\"\n"
23798                "{\n"
23799                "  int foo();\n"
23800                "}",
23801                Style);
23802 }
23803 TEST_F(FormatTest, GoogleDefaultStyle) {
23804   FormatStyle Style = getGoogleStyle();
23805   verifyFormat("extern \"C\" {\n"
23806                "int foo();\n"
23807                "}",
23808                Style);
23809 }
23810 TEST_F(FormatTest, ChromiumDefaultStyle) {
23811   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
23812   verifyFormat("extern \"C\" {\n"
23813                "int foo();\n"
23814                "}",
23815                Style);
23816 }
23817 TEST_F(FormatTest, MicrosoftDefaultStyle) {
23818   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
23819   verifyFormat("extern \"C\"\n"
23820                "{\n"
23821                "    int foo();\n"
23822                "}",
23823                Style);
23824 }
23825 TEST_F(FormatTest, WebKitDefaultStyle) {
23826   FormatStyle Style = getWebKitStyle();
23827   verifyFormat("extern \"C\" {\n"
23828                "int foo();\n"
23829                "}",
23830                Style);
23831 }
23832 
23833 TEST_F(FormatTest, Concepts) {
23834   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
23835             FormatStyle::BBCDS_Always);
23836   verifyFormat("template <typename T>\n"
23837                "concept True = true;");
23838 
23839   verifyFormat("template <typename T>\n"
23840                "concept C = ((false || foo()) && C2<T>) ||\n"
23841                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
23842                getLLVMStyleWithColumns(60));
23843 
23844   verifyFormat("template <typename T>\n"
23845                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
23846                "sizeof(T) <= 8;");
23847 
23848   verifyFormat("template <typename T>\n"
23849                "concept DelayedCheck = true && requires(T t) {\n"
23850                "                                 t.bar();\n"
23851                "                                 t.baz();\n"
23852                "                               } && sizeof(T) <= 8;");
23853 
23854   verifyFormat("template <typename T>\n"
23855                "concept DelayedCheck = true && requires(T t) { // Comment\n"
23856                "                                 t.bar();\n"
23857                "                                 t.baz();\n"
23858                "                               } && sizeof(T) <= 8;");
23859 
23860   verifyFormat("template <typename T>\n"
23861                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
23862                "sizeof(T) <= 8;");
23863 
23864   verifyFormat("template <typename T>\n"
23865                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
23866                "&& sizeof(T) <= 8;");
23867 
23868   verifyFormat(
23869       "template <typename T>\n"
23870       "concept DelayedCheck = static_cast<bool>(0) ||\n"
23871       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23872 
23873   verifyFormat("template <typename T>\n"
23874                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
23875                "&& sizeof(T) <= 8;");
23876 
23877   verifyFormat(
23878       "template <typename T>\n"
23879       "concept DelayedCheck = (bool)(0) ||\n"
23880       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23881 
23882   verifyFormat("template <typename T>\n"
23883                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
23884                "&& sizeof(T) <= 8;");
23885 
23886   verifyFormat("template <typename T>\n"
23887                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
23888                "sizeof(T) <= 8;");
23889 
23890   verifyFormat("template <typename T>\n"
23891                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
23892                "               requires(T t) {\n"
23893                "                 t.bar();\n"
23894                "                 t.baz();\n"
23895                "               } && sizeof(T) <= 8 && !(4 < 3);",
23896                getLLVMStyleWithColumns(60));
23897 
23898   verifyFormat("template <typename T>\n"
23899                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
23900 
23901   verifyFormat("template <typename T>\n"
23902                "concept C = foo();");
23903 
23904   verifyFormat("template <typename T>\n"
23905                "concept C = foo(T());");
23906 
23907   verifyFormat("template <typename T>\n"
23908                "concept C = foo(T{});");
23909 
23910   verifyFormat("template <typename T>\n"
23911                "concept Size = V<sizeof(T)>::Value > 5;");
23912 
23913   verifyFormat("template <typename T>\n"
23914                "concept True = S<T>::Value;");
23915 
23916   verifyFormat(
23917       "template <typename T>\n"
23918       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
23919       "            sizeof(T) <= 8;");
23920 
23921   // FIXME: This is misformatted because the fake l paren starts at bool, not at
23922   // the lambda l square.
23923   verifyFormat("template <typename T>\n"
23924                "concept C = [] -> bool { return true; }() && requires(T t) { "
23925                "t.bar(); } &&\n"
23926                "                      sizeof(T) <= 8;");
23927 
23928   verifyFormat(
23929       "template <typename T>\n"
23930       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
23931       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23932 
23933   verifyFormat("template <typename T>\n"
23934                "concept C = decltype([]() { return std::true_type{}; "
23935                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
23936                getLLVMStyleWithColumns(120));
23937 
23938   verifyFormat("template <typename T>\n"
23939                "concept C = decltype([]() -> std::true_type { return {}; "
23940                "}())::value &&\n"
23941                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23942 
23943   verifyFormat("template <typename T>\n"
23944                "concept C = true;\n"
23945                "Foo Bar;");
23946 
23947   verifyFormat("template <typename T>\n"
23948                "concept Hashable = requires(T a) {\n"
23949                "                     { std::hash<T>{}(a) } -> "
23950                "std::convertible_to<std::size_t>;\n"
23951                "                   };");
23952 
23953   verifyFormat(
23954       "template <typename T>\n"
23955       "concept EqualityComparable = requires(T a, T b) {\n"
23956       "                               { a == b } -> std::same_as<bool>;\n"
23957       "                             };");
23958 
23959   verifyFormat(
23960       "template <typename T>\n"
23961       "concept EqualityComparable = requires(T a, T b) {\n"
23962       "                               { a == b } -> std::same_as<bool>;\n"
23963       "                               { a != b } -> std::same_as<bool>;\n"
23964       "                             };");
23965 
23966   verifyFormat("template <typename T>\n"
23967                "concept WeakEqualityComparable = requires(T a, T b) {\n"
23968                "                                   { a == b };\n"
23969                "                                   { a != b };\n"
23970                "                                 };");
23971 
23972   verifyFormat("template <typename T>\n"
23973                "concept HasSizeT = requires { typename T::size_t; };");
23974 
23975   verifyFormat("template <typename T>\n"
23976                "concept Semiregular =\n"
23977                "    DefaultConstructible<T> && CopyConstructible<T> && "
23978                "CopyAssignable<T> &&\n"
23979                "    requires(T a, std::size_t n) {\n"
23980                "      requires Same<T *, decltype(&a)>;\n"
23981                "      { a.~T() } noexcept;\n"
23982                "      requires Same<T *, decltype(new T)>;\n"
23983                "      requires Same<T *, decltype(new T[n])>;\n"
23984                "      { delete new T; };\n"
23985                "      { delete new T[n]; };\n"
23986                "    };");
23987 
23988   verifyFormat("template <typename T>\n"
23989                "concept Semiregular =\n"
23990                "    requires(T a, std::size_t n) {\n"
23991                "      requires Same<T *, decltype(&a)>;\n"
23992                "      { a.~T() } noexcept;\n"
23993                "      requires Same<T *, decltype(new T)>;\n"
23994                "      requires Same<T *, decltype(new T[n])>;\n"
23995                "      { delete new T; };\n"
23996                "      { delete new T[n]; };\n"
23997                "      { new T } -> std::same_as<T *>;\n"
23998                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
23999                "CopyAssignable<T>;");
24000 
24001   verifyFormat(
24002       "template <typename T>\n"
24003       "concept Semiregular =\n"
24004       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
24005       "                                 requires Same<T *, decltype(&a)>;\n"
24006       "                                 { a.~T() } noexcept;\n"
24007       "                                 requires Same<T *, decltype(new T)>;\n"
24008       "                                 requires Same<T *, decltype(new "
24009       "T[n])>;\n"
24010       "                                 { delete new T; };\n"
24011       "                                 { delete new T[n]; };\n"
24012       "                               } && CopyConstructible<T> && "
24013       "CopyAssignable<T>;");
24014 
24015   verifyFormat("template <typename T>\n"
24016                "concept Two = requires(T t) {\n"
24017                "                { t.foo() } -> std::same_as<Bar>;\n"
24018                "              } && requires(T &&t) {\n"
24019                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
24020                "                   };");
24021 
24022   verifyFormat(
24023       "template <typename T>\n"
24024       "concept C = requires(T x) {\n"
24025       "              { *x } -> std::convertible_to<typename T::inner>;\n"
24026       "              { x + 1 } noexcept -> std::same_as<int>;\n"
24027       "              { x * 1 } -> std::convertible_to<T>;\n"
24028       "            };");
24029 
24030   verifyFormat(
24031       "template <typename T, typename U = T>\n"
24032       "concept Swappable = requires(T &&t, U &&u) {\n"
24033       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
24034       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
24035       "                    };");
24036 
24037   verifyFormat("template <typename T, typename U>\n"
24038                "concept Common = requires(T &&t, U &&u) {\n"
24039                "                   typename CommonType<T, U>;\n"
24040                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
24041                "                 };");
24042 
24043   verifyFormat("template <typename T, typename U>\n"
24044                "concept Common = requires(T &&t, U &&u) {\n"
24045                "                   typename CommonType<T, U>;\n"
24046                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
24047                "                 };");
24048 
24049   verifyFormat(
24050       "template <typename T>\n"
24051       "concept C = requires(T t) {\n"
24052       "              requires Bar<T> && Foo<T>;\n"
24053       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24054       "            };");
24055 
24056   verifyFormat("template <typename T>\n"
24057                "concept HasFoo = requires(T t) {\n"
24058                "                   { t.foo() };\n"
24059                "                   t.foo();\n"
24060                "                 };\n"
24061                "template <typename T>\n"
24062                "concept HasBar = requires(T t) {\n"
24063                "                   { t.bar() };\n"
24064                "                   t.bar();\n"
24065                "                 };");
24066 
24067   verifyFormat("template <typename T>\n"
24068                "concept Large = sizeof(T) > 10;");
24069 
24070   verifyFormat("template <typename T, typename U>\n"
24071                "concept FooableWith = requires(T t, U u) {\n"
24072                "                        typename T::foo_type;\n"
24073                "                        { t.foo(u) } -> typename T::foo_type;\n"
24074                "                        t++;\n"
24075                "                      };\n"
24076                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
24077 
24078   verifyFormat("template <typename T>\n"
24079                "concept Context = is_specialization_of_v<context, T>;");
24080 
24081   verifyFormat("template <typename T>\n"
24082                "concept Node = std::is_object_v<T>;");
24083 
24084   verifyFormat("template <class T>\n"
24085                "concept integral = __is_integral(T);");
24086 
24087   verifyFormat("template <class T>\n"
24088                "concept is2D = __array_extent(T, 1) == 2;");
24089 
24090   verifyFormat("template <class T>\n"
24091                "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
24092 
24093   verifyFormat("template <class T, class T2>\n"
24094                "concept Same = __is_same_as<T, T2>;");
24095 
24096   auto Style = getLLVMStyle();
24097   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
24098 
24099   verifyFormat(
24100       "template <typename T>\n"
24101       "concept C = requires(T t) {\n"
24102       "              requires Bar<T> && Foo<T>;\n"
24103       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24104       "            };",
24105       Style);
24106 
24107   verifyFormat("template <typename T>\n"
24108                "concept HasFoo = requires(T t) {\n"
24109                "                   { t.foo() };\n"
24110                "                   t.foo();\n"
24111                "                 };\n"
24112                "template <typename T>\n"
24113                "concept HasBar = requires(T t) {\n"
24114                "                   { t.bar() };\n"
24115                "                   t.bar();\n"
24116                "                 };",
24117                Style);
24118 
24119   verifyFormat("template <typename T> concept True = true;", Style);
24120 
24121   verifyFormat("template <typename T>\n"
24122                "concept C = decltype([]() -> std::true_type { return {}; "
24123                "}())::value &&\n"
24124                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24125                Style);
24126 
24127   verifyFormat("template <typename T>\n"
24128                "concept Semiregular =\n"
24129                "    DefaultConstructible<T> && CopyConstructible<T> && "
24130                "CopyAssignable<T> &&\n"
24131                "    requires(T a, std::size_t n) {\n"
24132                "      requires Same<T *, decltype(&a)>;\n"
24133                "      { a.~T() } noexcept;\n"
24134                "      requires Same<T *, decltype(new T)>;\n"
24135                "      requires Same<T *, decltype(new T[n])>;\n"
24136                "      { delete new T; };\n"
24137                "      { delete new T[n]; };\n"
24138                "    };",
24139                Style);
24140 
24141   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
24142 
24143   verifyFormat("template <typename T> concept C =\n"
24144                "    requires(T t) {\n"
24145                "      requires Bar<T> && Foo<T>;\n"
24146                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24147                "    };",
24148                Style);
24149 
24150   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
24151                "                                         { t.foo() };\n"
24152                "                                         t.foo();\n"
24153                "                                       };\n"
24154                "template <typename T> concept HasBar = requires(T t) {\n"
24155                "                                         { t.bar() };\n"
24156                "                                         t.bar();\n"
24157                "                                       };",
24158                Style);
24159 
24160   verifyFormat("template <typename T> concept True = true;", Style);
24161 
24162   verifyFormat(
24163       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
24164       "                                    return {};\n"
24165       "                                  }())::value &&\n"
24166       "                                  requires(T t) { t.bar(); } && "
24167       "sizeof(T) <= 8;",
24168       Style);
24169 
24170   verifyFormat("template <typename T> concept Semiregular =\n"
24171                "    DefaultConstructible<T> && CopyConstructible<T> && "
24172                "CopyAssignable<T> &&\n"
24173                "    requires(T a, std::size_t n) {\n"
24174                "      requires Same<T *, decltype(&a)>;\n"
24175                "      { a.~T() } noexcept;\n"
24176                "      requires Same<T *, decltype(new T)>;\n"
24177                "      requires Same<T *, decltype(new T[n])>;\n"
24178                "      { delete new T; };\n"
24179                "      { delete new T[n]; };\n"
24180                "    };",
24181                Style);
24182 
24183   // The following tests are invalid C++, we just want to make sure we don't
24184   // assert.
24185   verifyFormat("template <typename T>\n"
24186                "concept C = requires C2<T>;");
24187 
24188   verifyFormat("template <typename T>\n"
24189                "concept C = 5 + 4;");
24190 
24191   verifyFormat("template <typename T>\n"
24192                "concept C =\n"
24193                "class X;");
24194 
24195   verifyFormat("template <typename T>\n"
24196                "concept C = [] && true;");
24197 
24198   verifyFormat("template <typename T>\n"
24199                "concept C = [] && requires(T t) { typename T::size_type; };");
24200 }
24201 
24202 TEST_F(FormatTest, RequiresClausesPositions) {
24203   auto Style = getLLVMStyle();
24204   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
24205   EXPECT_EQ(Style.IndentRequiresClause, true);
24206 
24207   verifyFormat("template <typename T>\n"
24208                "  requires(Foo<T> && std::trait<T>)\n"
24209                "struct Bar;",
24210                Style);
24211 
24212   verifyFormat("template <typename T>\n"
24213                "  requires(Foo<T> && std::trait<T>)\n"
24214                "class Bar {\n"
24215                "public:\n"
24216                "  Bar(T t);\n"
24217                "  bool baz();\n"
24218                "};",
24219                Style);
24220 
24221   verifyFormat(
24222       "template <typename T>\n"
24223       "  requires requires(T &&t) {\n"
24224       "             typename T::I;\n"
24225       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
24226       "           }\n"
24227       "Bar(T) -> Bar<typename T::I>;",
24228       Style);
24229 
24230   verifyFormat("template <typename T>\n"
24231                "  requires(Foo<T> && std::trait<T>)\n"
24232                "constexpr T MyGlobal;",
24233                Style);
24234 
24235   verifyFormat("template <typename T>\n"
24236                "  requires Foo<T> && requires(T t) {\n"
24237                "                       { t.baz() } -> std::same_as<bool>;\n"
24238                "                       requires std::same_as<T::Factor, int>;\n"
24239                "                     }\n"
24240                "inline int bar(T t) {\n"
24241                "  return t.baz() ? T::Factor : 5;\n"
24242                "}",
24243                Style);
24244 
24245   verifyFormat("template <typename T>\n"
24246                "inline int bar(T t)\n"
24247                "  requires Foo<T> && requires(T t) {\n"
24248                "                       { t.baz() } -> std::same_as<bool>;\n"
24249                "                       requires std::same_as<T::Factor, int>;\n"
24250                "                     }\n"
24251                "{\n"
24252                "  return t.baz() ? T::Factor : 5;\n"
24253                "}",
24254                Style);
24255 
24256   verifyFormat("template <typename T>\n"
24257                "  requires F<T>\n"
24258                "int bar(T t) {\n"
24259                "  return 5;\n"
24260                "}",
24261                Style);
24262 
24263   verifyFormat("template <typename T>\n"
24264                "int bar(T t)\n"
24265                "  requires F<T>\n"
24266                "{\n"
24267                "  return 5;\n"
24268                "}",
24269                Style);
24270 
24271   verifyFormat("template <typename T>\n"
24272                "int bar(T t)\n"
24273                "  requires F<T>;",
24274                Style);
24275 
24276   Style.IndentRequiresClause = false;
24277   verifyFormat("template <typename T>\n"
24278                "requires F<T>\n"
24279                "int bar(T t) {\n"
24280                "  return 5;\n"
24281                "}",
24282                Style);
24283 
24284   verifyFormat("template <typename T>\n"
24285                "int bar(T t)\n"
24286                "requires F<T>\n"
24287                "{\n"
24288                "  return 5;\n"
24289                "}",
24290                Style);
24291 
24292   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
24293   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
24294                "template <typename T> requires Foo<T> void bar() {}\n"
24295                "template <typename T> void bar() requires Foo<T> {}\n"
24296                "template <typename T> void bar() requires Foo<T>;\n"
24297                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
24298                Style);
24299 
24300   auto ColumnStyle = Style;
24301   ColumnStyle.ColumnLimit = 40;
24302   verifyFormat("template <typename AAAAAAA>\n"
24303                "requires Foo<T> struct Bar {};\n"
24304                "template <typename AAAAAAA>\n"
24305                "requires Foo<T> void bar() {}\n"
24306                "template <typename AAAAAAA>\n"
24307                "void bar() requires Foo<T> {}\n"
24308                "template <typename AAAAAAA>\n"
24309                "requires Foo<T> Baz(T) -> Baz<T>;",
24310                ColumnStyle);
24311 
24312   verifyFormat("template <typename T>\n"
24313                "requires Foo<AAAAAAA> struct Bar {};\n"
24314                "template <typename T>\n"
24315                "requires Foo<AAAAAAA> void bar() {}\n"
24316                "template <typename T>\n"
24317                "void bar() requires Foo<AAAAAAA> {}\n"
24318                "template <typename T>\n"
24319                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
24320                ColumnStyle);
24321 
24322   verifyFormat("template <typename AAAAAAA>\n"
24323                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24324                "struct Bar {};\n"
24325                "template <typename AAAAAAA>\n"
24326                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24327                "void bar() {}\n"
24328                "template <typename AAAAAAA>\n"
24329                "void bar()\n"
24330                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24331                "template <typename AAAAAAA>\n"
24332                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24333                "template <typename AAAAAAA>\n"
24334                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24335                "Bar(T) -> Bar<T>;",
24336                ColumnStyle);
24337 
24338   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24339   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24340 
24341   verifyFormat("template <typename T>\n"
24342                "requires Foo<T> struct Bar {};\n"
24343                "template <typename T>\n"
24344                "requires Foo<T> void bar() {}\n"
24345                "template <typename T>\n"
24346                "void bar()\n"
24347                "requires Foo<T> {}\n"
24348                "template <typename T>\n"
24349                "void bar()\n"
24350                "requires Foo<T>;\n"
24351                "template <typename T>\n"
24352                "requires Foo<T> Bar(T) -> Bar<T>;",
24353                Style);
24354 
24355   verifyFormat("template <typename AAAAAAA>\n"
24356                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24357                "struct Bar {};\n"
24358                "template <typename AAAAAAA>\n"
24359                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24360                "void bar() {}\n"
24361                "template <typename AAAAAAA>\n"
24362                "void bar()\n"
24363                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24364                "template <typename AAAAAAA>\n"
24365                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24366                "template <typename AAAAAAA>\n"
24367                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24368                "Bar(T) -> Bar<T>;",
24369                ColumnStyle);
24370 
24371   Style.IndentRequiresClause = true;
24372   ColumnStyle.IndentRequiresClause = true;
24373 
24374   verifyFormat("template <typename T>\n"
24375                "  requires Foo<T> struct Bar {};\n"
24376                "template <typename T>\n"
24377                "  requires Foo<T> void bar() {}\n"
24378                "template <typename T>\n"
24379                "void bar()\n"
24380                "  requires Foo<T> {}\n"
24381                "template <typename T>\n"
24382                "  requires Foo<T> Bar(T) -> Bar<T>;",
24383                Style);
24384 
24385   verifyFormat("template <typename AAAAAAA>\n"
24386                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24387                "struct Bar {};\n"
24388                "template <typename AAAAAAA>\n"
24389                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24390                "void bar() {}\n"
24391                "template <typename AAAAAAA>\n"
24392                "void bar()\n"
24393                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24394                "template <typename AAAAAAA>\n"
24395                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24396                "template <typename AAAAAAA>\n"
24397                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24398                "Bar(T) -> Bar<T>;",
24399                ColumnStyle);
24400 
24401   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24402   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24403 
24404   verifyFormat("template <typename T> requires Foo<T>\n"
24405                "struct Bar {};\n"
24406                "template <typename T> requires Foo<T>\n"
24407                "void bar() {}\n"
24408                "template <typename T>\n"
24409                "void bar() requires Foo<T>\n"
24410                "{}\n"
24411                "template <typename T> void bar() requires Foo<T>;\n"
24412                "template <typename T> requires Foo<T>\n"
24413                "Bar(T) -> Bar<T>;",
24414                Style);
24415 
24416   verifyFormat("template <typename AAAAAAA>\n"
24417                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24418                "struct Bar {};\n"
24419                "template <typename AAAAAAA>\n"
24420                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24421                "void bar() {}\n"
24422                "template <typename AAAAAAA>\n"
24423                "void bar()\n"
24424                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24425                "{}\n"
24426                "template <typename AAAAAAA>\n"
24427                "requires Foo<AAAAAAAA>\n"
24428                "Bar(T) -> Bar<T>;\n"
24429                "template <typename AAAAAAA>\n"
24430                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24431                "Bar(T) -> Bar<T>;",
24432                ColumnStyle);
24433 }
24434 
24435 TEST_F(FormatTest, RequiresClauses) {
24436   verifyFormat("struct [[nodiscard]] zero_t {\n"
24437                "  template <class T>\n"
24438                "    requires requires { number_zero_v<T>; }\n"
24439                "  [[nodiscard]] constexpr operator T() const {\n"
24440                "    return number_zero_v<T>;\n"
24441                "  }\n"
24442                "};");
24443 
24444   auto Style = getLLVMStyle();
24445 
24446   verifyFormat(
24447       "template <typename T>\n"
24448       "  requires is_default_constructible_v<hash<T>> and\n"
24449       "           is_copy_constructible_v<hash<T>> and\n"
24450       "           is_move_constructible_v<hash<T>> and\n"
24451       "           is_copy_assignable_v<hash<T>> and "
24452       "is_move_assignable_v<hash<T>> and\n"
24453       "           is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
24454       "           is_callable_v<hash<T>(T)> and\n"
24455       "           is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
24456       "           is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
24457       "           is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
24458       "struct S {};",
24459       Style);
24460 
24461   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
24462   verifyFormat(
24463       "template <typename T>\n"
24464       "  requires is_default_constructible_v<hash<T>>\n"
24465       "           and is_copy_constructible_v<hash<T>>\n"
24466       "           and is_move_constructible_v<hash<T>>\n"
24467       "           and is_copy_assignable_v<hash<T>> and "
24468       "is_move_assignable_v<hash<T>>\n"
24469       "           and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
24470       "           and is_callable_v<hash<T>(T)>\n"
24471       "           and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
24472       "           and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
24473       "           and is_same_v<size_t, decltype(hash<T>(declval<const T "
24474       "&>()))>\n"
24475       "struct S {};",
24476       Style);
24477 
24478   // Not a clause, but we once hit an assert.
24479   verifyFormat("#if 0\n"
24480                "#else\n"
24481                "foo();\n"
24482                "#endif\n"
24483                "bar(requires);");
24484 }
24485 
24486 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24487   FormatStyle Style = getLLVMStyle();
24488   StringRef Source = "void Foo::slot() {\n"
24489                      "  unsigned char MyChar = 'x';\n"
24490                      "  emit signal(MyChar);\n"
24491                      "  Q_EMIT signal(MyChar);\n"
24492                      "}";
24493 
24494   EXPECT_EQ(Source, format(Source, Style));
24495 
24496   Style.AlignConsecutiveDeclarations.Enabled = true;
24497   EXPECT_EQ("void Foo::slot() {\n"
24498             "  unsigned char MyChar = 'x';\n"
24499             "  emit          signal(MyChar);\n"
24500             "  Q_EMIT signal(MyChar);\n"
24501             "}",
24502             format(Source, Style));
24503 
24504   Style.StatementAttributeLikeMacros.push_back("emit");
24505   EXPECT_EQ(Source, format(Source, Style));
24506 
24507   Style.StatementAttributeLikeMacros = {};
24508   EXPECT_EQ("void Foo::slot() {\n"
24509             "  unsigned char MyChar = 'x';\n"
24510             "  emit          signal(MyChar);\n"
24511             "  Q_EMIT        signal(MyChar);\n"
24512             "}",
24513             format(Source, Style));
24514 }
24515 
24516 TEST_F(FormatTest, IndentAccessModifiers) {
24517   FormatStyle Style = getLLVMStyle();
24518   Style.IndentAccessModifiers = true;
24519   // Members are *two* levels below the record;
24520   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24521   verifyFormat("class C {\n"
24522                "    int i;\n"
24523                "};\n",
24524                Style);
24525   verifyFormat("union C {\n"
24526                "    int i;\n"
24527                "    unsigned u;\n"
24528                "};\n",
24529                Style);
24530   // Access modifiers should be indented one level below the record.
24531   verifyFormat("class C {\n"
24532                "  public:\n"
24533                "    int i;\n"
24534                "};\n",
24535                Style);
24536   verifyFormat("struct S {\n"
24537                "  private:\n"
24538                "    class C {\n"
24539                "        int j;\n"
24540                "\n"
24541                "      public:\n"
24542                "        C();\n"
24543                "    };\n"
24544                "\n"
24545                "  public:\n"
24546                "    int i;\n"
24547                "};\n",
24548                Style);
24549   // Enumerations are not records and should be unaffected.
24550   Style.AllowShortEnumsOnASingleLine = false;
24551   verifyFormat("enum class E {\n"
24552                "  A,\n"
24553                "  B\n"
24554                "};\n",
24555                Style);
24556   // Test with a different indentation width;
24557   // also proves that the result is Style.AccessModifierOffset agnostic.
24558   Style.IndentWidth = 3;
24559   verifyFormat("class C {\n"
24560                "   public:\n"
24561                "      int i;\n"
24562                "};\n",
24563                Style);
24564 }
24565 
24566 TEST_F(FormatTest, LimitlessStringsAndComments) {
24567   auto Style = getLLVMStyleWithColumns(0);
24568   constexpr StringRef Code =
24569       "/**\n"
24570       " * This is a multiline comment with quite some long lines, at least for "
24571       "the LLVM Style.\n"
24572       " * We will redo this with strings and line comments. Just to  check if "
24573       "everything is working.\n"
24574       " */\n"
24575       "bool foo() {\n"
24576       "  /* Single line multi line comment. */\n"
24577       "  const std::string String = \"This is a multiline string with quite "
24578       "some long lines, at least for the LLVM Style.\"\n"
24579       "                             \"We already did it with multi line "
24580       "comments, and we will do it with line comments. Just to check if "
24581       "everything is working.\";\n"
24582       "  // This is a line comment (block) with quite some long lines, at "
24583       "least for the LLVM Style.\n"
24584       "  // We already did this with multi line comments and strings. Just to "
24585       "check if everything is working.\n"
24586       "  const std::string SmallString = \"Hello World\";\n"
24587       "  // Small line comment\n"
24588       "  return String.size() > SmallString.size();\n"
24589       "}";
24590   EXPECT_EQ(Code, format(Code, Style));
24591 }
24592 
24593 TEST_F(FormatTest, FormatDecayCopy) {
24594   // error cases from unit tests
24595   verifyFormat("foo(auto())");
24596   verifyFormat("foo(auto{})");
24597   verifyFormat("foo(auto({}))");
24598   verifyFormat("foo(auto{{}})");
24599 
24600   verifyFormat("foo(auto(1))");
24601   verifyFormat("foo(auto{1})");
24602   verifyFormat("foo(new auto(1))");
24603   verifyFormat("foo(new auto{1})");
24604   verifyFormat("decltype(auto(1)) x;");
24605   verifyFormat("decltype(auto{1}) x;");
24606   verifyFormat("auto(x);");
24607   verifyFormat("auto{x};");
24608   verifyFormat("new auto{x};");
24609   verifyFormat("auto{x} = y;");
24610   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24611                                 // the user's own fault
24612   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24613                                          // clearly the user's own fault
24614   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24615 }
24616 
24617 TEST_F(FormatTest, Cpp20ModulesSupport) {
24618   FormatStyle Style = getLLVMStyle();
24619   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24620   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24621 
24622   verifyFormat("export import foo;", Style);
24623   verifyFormat("export import foo:bar;", Style);
24624   verifyFormat("export import foo.bar;", Style);
24625   verifyFormat("export import foo.bar:baz;", Style);
24626   verifyFormat("export import :bar;", Style);
24627   verifyFormat("export module foo:bar;", Style);
24628   verifyFormat("export module foo;", Style);
24629   verifyFormat("export module foo.bar;", Style);
24630   verifyFormat("export module foo.bar:baz;", Style);
24631   verifyFormat("export import <string_view>;", Style);
24632 
24633   verifyFormat("export type_name var;", Style);
24634   verifyFormat("template <class T> export using A = B<T>;", Style);
24635   verifyFormat("export using A = B;", Style);
24636   verifyFormat("export int func() {\n"
24637                "  foo();\n"
24638                "}",
24639                Style);
24640   verifyFormat("export struct {\n"
24641                "  int foo;\n"
24642                "};",
24643                Style);
24644   verifyFormat("export {\n"
24645                "  int foo;\n"
24646                "};",
24647                Style);
24648   verifyFormat("export export char const *hello() { return \"hello\"; }");
24649 
24650   verifyFormat("import bar;", Style);
24651   verifyFormat("import foo.bar;", Style);
24652   verifyFormat("import foo:bar;", Style);
24653   verifyFormat("import :bar;", Style);
24654   verifyFormat("import <ctime>;", Style);
24655   verifyFormat("import \"header\";", Style);
24656 
24657   verifyFormat("module foo;", Style);
24658   verifyFormat("module foo:bar;", Style);
24659   verifyFormat("module foo.bar;", Style);
24660   verifyFormat("module;", Style);
24661 
24662   verifyFormat("export namespace hi {\n"
24663                "const char *sayhi();\n"
24664                "}",
24665                Style);
24666 
24667   verifyFormat("module :private;", Style);
24668   verifyFormat("import <foo/bar.h>;", Style);
24669   verifyFormat("import foo...bar;", Style);
24670   verifyFormat("import ..........;", Style);
24671   verifyFormat("module foo:private;", Style);
24672   verifyFormat("import a", Style);
24673   verifyFormat("module a", Style);
24674   verifyFormat("export import a", Style);
24675   verifyFormat("export module a", Style);
24676 
24677   verifyFormat("import", Style);
24678   verifyFormat("module", Style);
24679   verifyFormat("export", Style);
24680 }
24681 
24682 TEST_F(FormatTest, CoroutineForCoawait) {
24683   FormatStyle Style = getLLVMStyle();
24684   verifyFormat("for co_await (auto x : range())\n  ;");
24685   verifyFormat("for (auto i : arr) {\n"
24686                "}",
24687                Style);
24688   verifyFormat("for co_await (auto i : arr) {\n"
24689                "}",
24690                Style);
24691   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24692                "}",
24693                Style);
24694 }
24695 
24696 TEST_F(FormatTest, CoroutineCoAwait) {
24697   verifyFormat("int x = co_await foo();");
24698   verifyFormat("int x = (co_await foo());");
24699   verifyFormat("co_await (42);");
24700   verifyFormat("void operator co_await(int);");
24701   verifyFormat("void operator co_await(a);");
24702   verifyFormat("co_await a;");
24703   verifyFormat("co_await missing_await_resume{};");
24704   verifyFormat("co_await a; // comment");
24705   verifyFormat("void test0() { co_await a; }");
24706   verifyFormat("co_await co_await co_await foo();");
24707   verifyFormat("co_await foo().bar();");
24708   verifyFormat("co_await [this]() -> Task { co_return x; }");
24709   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24710                "foo(); }(x, y);");
24711 
24712   FormatStyle Style = getLLVMStyleWithColumns(40);
24713   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24714                "  co_return co_await foo();\n"
24715                "}(x, y);",
24716                Style);
24717   verifyFormat("co_await;");
24718 }
24719 
24720 TEST_F(FormatTest, CoroutineCoYield) {
24721   verifyFormat("int x = co_yield foo();");
24722   verifyFormat("int x = (co_yield foo());");
24723   verifyFormat("co_yield (42);");
24724   verifyFormat("co_yield {42};");
24725   verifyFormat("co_yield 42;");
24726   verifyFormat("co_yield n++;");
24727   verifyFormat("co_yield ++n;");
24728   verifyFormat("co_yield;");
24729 }
24730 
24731 TEST_F(FormatTest, CoroutineCoReturn) {
24732   verifyFormat("co_return (42);");
24733   verifyFormat("co_return;");
24734   verifyFormat("co_return {};");
24735   verifyFormat("co_return x;");
24736   verifyFormat("co_return co_await foo();");
24737   verifyFormat("co_return co_yield foo();");
24738 }
24739 
24740 TEST_F(FormatTest, EmptyShortBlock) {
24741   auto Style = getLLVMStyle();
24742   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24743 
24744   verifyFormat("try {\n"
24745                "  doA();\n"
24746                "} catch (Exception &e) {\n"
24747                "  e.printStackTrace();\n"
24748                "}\n",
24749                Style);
24750 
24751   verifyFormat("try {\n"
24752                "  doA();\n"
24753                "} catch (Exception &e) {}\n",
24754                Style);
24755 }
24756 
24757 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
24758   auto Style = getLLVMStyle();
24759 
24760   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
24761   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
24762   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
24763   verifyFormat("struct Y<[] { return 0; }> {};", Style);
24764 
24765   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
24766   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
24767 }
24768 
24769 TEST_F(FormatTest, InsertBraces) {
24770   FormatStyle Style = getLLVMStyle();
24771   Style.InsertBraces = true;
24772 
24773   verifyFormat("// clang-format off\n"
24774                "// comment\n"
24775                "if (a) f();\n"
24776                "// clang-format on\n"
24777                "if (b) {\n"
24778                "  g();\n"
24779                "}",
24780                "// clang-format off\n"
24781                "// comment\n"
24782                "if (a) f();\n"
24783                "// clang-format on\n"
24784                "if (b) g();",
24785                Style);
24786 
24787   verifyFormat("if (a) {\n"
24788                "  switch (b) {\n"
24789                "  case 1:\n"
24790                "    c = 0;\n"
24791                "    break;\n"
24792                "  default:\n"
24793                "    c = 1;\n"
24794                "  }\n"
24795                "}",
24796                "if (a)\n"
24797                "  switch (b) {\n"
24798                "  case 1:\n"
24799                "    c = 0;\n"
24800                "    break;\n"
24801                "  default:\n"
24802                "    c = 1;\n"
24803                "  }",
24804                Style);
24805 
24806   verifyFormat("for (auto node : nodes) {\n"
24807                "  if (node) {\n"
24808                "    break;\n"
24809                "  }\n"
24810                "}",
24811                "for (auto node : nodes)\n"
24812                "  if (node)\n"
24813                "    break;",
24814                Style);
24815 
24816   verifyFormat("for (auto node : nodes) {\n"
24817                "  if (node)\n"
24818                "}",
24819                "for (auto node : nodes)\n"
24820                "  if (node)",
24821                Style);
24822 
24823   verifyFormat("do {\n"
24824                "  --a;\n"
24825                "} while (a);",
24826                "do\n"
24827                "  --a;\n"
24828                "while (a);",
24829                Style);
24830 
24831   verifyFormat("if (i) {\n"
24832                "  ++i;\n"
24833                "} else {\n"
24834                "  --i;\n"
24835                "}",
24836                "if (i)\n"
24837                "  ++i;\n"
24838                "else {\n"
24839                "  --i;\n"
24840                "}",
24841                Style);
24842 
24843   verifyFormat("void f() {\n"
24844                "  while (j--) {\n"
24845                "    while (i) {\n"
24846                "      --i;\n"
24847                "    }\n"
24848                "  }\n"
24849                "}",
24850                "void f() {\n"
24851                "  while (j--)\n"
24852                "    while (i)\n"
24853                "      --i;\n"
24854                "}",
24855                Style);
24856 
24857   verifyFormat("f({\n"
24858                "  if (a) {\n"
24859                "    g();\n"
24860                "  }\n"
24861                "});",
24862                "f({\n"
24863                "  if (a)\n"
24864                "    g();\n"
24865                "});",
24866                Style);
24867 
24868   verifyFormat("if (a) {\n"
24869                "  f();\n"
24870                "} else if (b) {\n"
24871                "  g();\n"
24872                "} else {\n"
24873                "  h();\n"
24874                "}",
24875                "if (a)\n"
24876                "  f();\n"
24877                "else if (b)\n"
24878                "  g();\n"
24879                "else\n"
24880                "  h();",
24881                Style);
24882 
24883   verifyFormat("if (a) {\n"
24884                "  f();\n"
24885                "}\n"
24886                "// comment\n"
24887                "/* comment */",
24888                "if (a)\n"
24889                "  f();\n"
24890                "// comment\n"
24891                "/* comment */",
24892                Style);
24893 
24894   verifyFormat("if (a) {\n"
24895                "  // foo\n"
24896                "  // bar\n"
24897                "  f();\n"
24898                "}",
24899                "if (a)\n"
24900                "  // foo\n"
24901                "  // bar\n"
24902                "  f();",
24903                Style);
24904 
24905   verifyFormat("if (a) { // comment\n"
24906                "  // comment\n"
24907                "  f();\n"
24908                "}",
24909                "if (a) // comment\n"
24910                "  // comment\n"
24911                "  f();",
24912                Style);
24913 
24914   verifyFormat("if (a) {\n"
24915                "  f(); // comment\n"
24916                "}",
24917                "if (a)\n"
24918                "  f(); // comment",
24919                Style);
24920 
24921   verifyFormat("if (a) {\n"
24922                "  f();\n"
24923                "}\n"
24924                "#undef A\n"
24925                "#undef B",
24926                "if (a)\n"
24927                "  f();\n"
24928                "#undef A\n"
24929                "#undef B",
24930                Style);
24931 
24932   verifyFormat("if (a)\n"
24933                "#ifdef A\n"
24934                "  f();\n"
24935                "#else\n"
24936                "  g();\n"
24937                "#endif",
24938                Style);
24939 
24940   verifyFormat("#if 0\n"
24941                "#elif 1\n"
24942                "#endif\n"
24943                "void f() {\n"
24944                "  if (a) {\n"
24945                "    g();\n"
24946                "  }\n"
24947                "}",
24948                "#if 0\n"
24949                "#elif 1\n"
24950                "#endif\n"
24951                "void f() {\n"
24952                "  if (a) g();\n"
24953                "}",
24954                Style);
24955 
24956   Style.ColumnLimit = 15;
24957 
24958   verifyFormat("#define A     \\\n"
24959                "  if (a)      \\\n"
24960                "    f();",
24961                Style);
24962 
24963   verifyFormat("if (a + b >\n"
24964                "    c) {\n"
24965                "  f();\n"
24966                "}",
24967                "if (a + b > c)\n"
24968                "  f();",
24969                Style);
24970 }
24971 
24972 TEST_F(FormatTest, RemoveBraces) {
24973   FormatStyle Style = getLLVMStyle();
24974   Style.RemoveBracesLLVM = true;
24975 
24976   // The following eight test cases are fully-braced versions of the examples at
24977   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
24978   // statement-bodies-of-if-else-loop-statements".
24979 
24980   // 1. Omit the braces, since the body is simple and clearly associated with
24981   // the if.
24982   verifyFormat("if (isa<FunctionDecl>(D))\n"
24983                "  handleFunctionDecl(D);\n"
24984                "else if (isa<VarDecl>(D))\n"
24985                "  handleVarDecl(D);",
24986                "if (isa<FunctionDecl>(D)) {\n"
24987                "  handleFunctionDecl(D);\n"
24988                "} else if (isa<VarDecl>(D)) {\n"
24989                "  handleVarDecl(D);\n"
24990                "}",
24991                Style);
24992 
24993   // 2. Here we document the condition itself and not the body.
24994   verifyFormat("if (isa<VarDecl>(D)) {\n"
24995                "  // It is necessary that we explain the situation with this\n"
24996                "  // surprisingly long comment, so it would be unclear\n"
24997                "  // without the braces whether the following statement is in\n"
24998                "  // the scope of the `if`.\n"
24999                "  // Because the condition is documented, we can't really\n"
25000                "  // hoist this comment that applies to the body above the\n"
25001                "  // if.\n"
25002                "  handleOtherDecl(D);\n"
25003                "}",
25004                Style);
25005 
25006   // 3. Use braces on the outer `if` to avoid a potential dangling else
25007   // situation.
25008   verifyFormat("if (isa<VarDecl>(D)) {\n"
25009                "  for (auto *A : D.attrs())\n"
25010                "    if (shouldProcessAttr(A))\n"
25011                "      handleAttr(A);\n"
25012                "}",
25013                "if (isa<VarDecl>(D)) {\n"
25014                "  for (auto *A : D.attrs()) {\n"
25015                "    if (shouldProcessAttr(A)) {\n"
25016                "      handleAttr(A);\n"
25017                "    }\n"
25018                "  }\n"
25019                "}",
25020                Style);
25021 
25022   // 4. Use braces for the `if` block to keep it uniform with the else block.
25023   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25024                "  handleFunctionDecl(D);\n"
25025                "} else {\n"
25026                "  // In this else case, it is necessary that we explain the\n"
25027                "  // situation with this surprisingly long comment, so it\n"
25028                "  // would be unclear without the braces whether the\n"
25029                "  // following statement is in the scope of the `if`.\n"
25030                "  handleOtherDecl(D);\n"
25031                "}",
25032                Style);
25033 
25034   // 5. This should also omit braces.  The `for` loop contains only a single
25035   // statement, so it shouldn't have braces.  The `if` also only contains a
25036   // single simple statement (the for loop), so it also should omit braces.
25037   verifyFormat("if (isa<FunctionDecl>(D))\n"
25038                "  for (auto *A : D.attrs())\n"
25039                "    handleAttr(A);",
25040                "if (isa<FunctionDecl>(D)) {\n"
25041                "  for (auto *A : D.attrs()) {\n"
25042                "    handleAttr(A);\n"
25043                "  }\n"
25044                "}",
25045                Style);
25046 
25047   // 6. Use braces for the outer `if` since the nested `for` is braced.
25048   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25049                "  for (auto *A : D.attrs()) {\n"
25050                "    // In this for loop body, it is necessary that we explain\n"
25051                "    // the situation with this surprisingly long comment,\n"
25052                "    // forcing braces on the `for` block.\n"
25053                "    handleAttr(A);\n"
25054                "  }\n"
25055                "}",
25056                Style);
25057 
25058   // 7. Use braces on the outer block because there are more than two levels of
25059   // nesting.
25060   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25061                "  for (auto *A : D.attrs())\n"
25062                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
25063                "      handleAttrOnDecl(D, A, i);\n"
25064                "}",
25065                "if (isa<FunctionDecl>(D)) {\n"
25066                "  for (auto *A : D.attrs()) {\n"
25067                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
25068                "      handleAttrOnDecl(D, A, i);\n"
25069                "    }\n"
25070                "  }\n"
25071                "}",
25072                Style);
25073 
25074   // 8. Use braces on the outer block because of a nested `if`, otherwise the
25075   // compiler would warn: `add explicit braces to avoid dangling else`
25076   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25077                "  if (shouldProcess(D))\n"
25078                "    handleVarDecl(D);\n"
25079                "  else\n"
25080                "    markAsIgnored(D);\n"
25081                "}",
25082                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25083                "  if (shouldProcess(D)) {\n"
25084                "    handleVarDecl(D);\n"
25085                "  } else {\n"
25086                "    markAsIgnored(D);\n"
25087                "  }\n"
25088                "}",
25089                Style);
25090 
25091   verifyFormat("// clang-format off\n"
25092                "// comment\n"
25093                "while (i > 0) { --i; }\n"
25094                "// clang-format on\n"
25095                "while (j < 0)\n"
25096                "  ++j;",
25097                "// clang-format off\n"
25098                "// comment\n"
25099                "while (i > 0) { --i; }\n"
25100                "// clang-format on\n"
25101                "while (j < 0) { ++j; }",
25102                Style);
25103 
25104   verifyFormat("if (a)\n"
25105                "  b; // comment\n"
25106                "else if (c)\n"
25107                "  d; /* comment */\n"
25108                "else\n"
25109                "  e;",
25110                "if (a) {\n"
25111                "  b; // comment\n"
25112                "} else if (c) {\n"
25113                "  d; /* comment */\n"
25114                "} else {\n"
25115                "  e;\n"
25116                "}",
25117                Style);
25118 
25119   verifyFormat("if (a) {\n"
25120                "  b;\n"
25121                "  c;\n"
25122                "} else if (d) {\n"
25123                "  e;\n"
25124                "}",
25125                Style);
25126 
25127   verifyFormat("if (a) {\n"
25128                "#undef NDEBUG\n"
25129                "  b;\n"
25130                "} else {\n"
25131                "  c;\n"
25132                "}",
25133                Style);
25134 
25135   verifyFormat("if (a) {\n"
25136                "  // comment\n"
25137                "} else if (b) {\n"
25138                "  c;\n"
25139                "}",
25140                Style);
25141 
25142   verifyFormat("if (a) {\n"
25143                "  b;\n"
25144                "} else {\n"
25145                "  { c; }\n"
25146                "}",
25147                Style);
25148 
25149   verifyFormat("if (a) {\n"
25150                "  if (b) // comment\n"
25151                "    c;\n"
25152                "} else if (d) {\n"
25153                "  e;\n"
25154                "}",
25155                "if (a) {\n"
25156                "  if (b) { // comment\n"
25157                "    c;\n"
25158                "  }\n"
25159                "} else if (d) {\n"
25160                "  e;\n"
25161                "}",
25162                Style);
25163 
25164   verifyFormat("if (a) {\n"
25165                "  if (b) {\n"
25166                "    c;\n"
25167                "    // comment\n"
25168                "  } else if (d) {\n"
25169                "    e;\n"
25170                "  }\n"
25171                "}",
25172                Style);
25173 
25174   verifyFormat("if (a) {\n"
25175                "  if (b)\n"
25176                "    c;\n"
25177                "}",
25178                "if (a) {\n"
25179                "  if (b) {\n"
25180                "    c;\n"
25181                "  }\n"
25182                "}",
25183                Style);
25184 
25185   verifyFormat("if (a)\n"
25186                "  if (b)\n"
25187                "    c;\n"
25188                "  else\n"
25189                "    d;\n"
25190                "else\n"
25191                "  e;",
25192                "if (a) {\n"
25193                "  if (b) {\n"
25194                "    c;\n"
25195                "  } else {\n"
25196                "    d;\n"
25197                "  }\n"
25198                "} else {\n"
25199                "  e;\n"
25200                "}",
25201                Style);
25202 
25203   verifyFormat("if (a) {\n"
25204                "  // comment\n"
25205                "  if (b)\n"
25206                "    c;\n"
25207                "  else if (d)\n"
25208                "    e;\n"
25209                "} else {\n"
25210                "  g;\n"
25211                "}",
25212                "if (a) {\n"
25213                "  // comment\n"
25214                "  if (b) {\n"
25215                "    c;\n"
25216                "  } else if (d) {\n"
25217                "    e;\n"
25218                "  }\n"
25219                "} else {\n"
25220                "  g;\n"
25221                "}",
25222                Style);
25223 
25224   verifyFormat("if (a)\n"
25225                "  b;\n"
25226                "else if (c)\n"
25227                "  d;\n"
25228                "else\n"
25229                "  e;",
25230                "if (a) {\n"
25231                "  b;\n"
25232                "} else {\n"
25233                "  if (c) {\n"
25234                "    d;\n"
25235                "  } else {\n"
25236                "    e;\n"
25237                "  }\n"
25238                "}",
25239                Style);
25240 
25241   verifyFormat("if (a) {\n"
25242                "  if (b)\n"
25243                "    c;\n"
25244                "  else if (d)\n"
25245                "    e;\n"
25246                "} else {\n"
25247                "  g;\n"
25248                "}",
25249                "if (a) {\n"
25250                "  if (b)\n"
25251                "    c;\n"
25252                "  else {\n"
25253                "    if (d)\n"
25254                "      e;\n"
25255                "  }\n"
25256                "} else {\n"
25257                "  g;\n"
25258                "}",
25259                Style);
25260 
25261   verifyFormat("if (a)\n"
25262                "  b;\n"
25263                "else if (c)\n"
25264                "  while (d)\n"
25265                "    e;\n"
25266                "// comment",
25267                "if (a)\n"
25268                "{\n"
25269                "  b;\n"
25270                "} else if (c) {\n"
25271                "  while (d) {\n"
25272                "    e;\n"
25273                "  }\n"
25274                "}\n"
25275                "// comment",
25276                Style);
25277 
25278   verifyFormat("if (a) {\n"
25279                "  b;\n"
25280                "} else if (c) {\n"
25281                "  d;\n"
25282                "} else {\n"
25283                "  e;\n"
25284                "  g;\n"
25285                "}",
25286                Style);
25287 
25288   verifyFormat("if (a) {\n"
25289                "  b;\n"
25290                "} else if (c) {\n"
25291                "  d;\n"
25292                "} else {\n"
25293                "  e;\n"
25294                "} // comment",
25295                Style);
25296 
25297   verifyFormat("int abs = [](int i) {\n"
25298                "  if (i >= 0)\n"
25299                "    return i;\n"
25300                "  return -i;\n"
25301                "};",
25302                "int abs = [](int i) {\n"
25303                "  if (i >= 0) {\n"
25304                "    return i;\n"
25305                "  }\n"
25306                "  return -i;\n"
25307                "};",
25308                Style);
25309 
25310   verifyFormat("if (a)\n"
25311                "  foo();\n"
25312                "else\n"
25313                "  bar();",
25314                "if (a)\n"
25315                "{\n"
25316                "  foo();\n"
25317                "}\n"
25318                "else\n"
25319                "{\n"
25320                "  bar();\n"
25321                "}",
25322                Style);
25323 
25324   verifyFormat("if (a) {\n"
25325                "Label:\n"
25326                "}",
25327                Style);
25328 
25329   verifyFormat("if (a) {\n"
25330                "Label:\n"
25331                "  f();\n"
25332                "}",
25333                Style);
25334 
25335   verifyFormat("if (a) {\n"
25336                "  f();\n"
25337                "Label:\n"
25338                "}",
25339                Style);
25340 
25341   // FIXME: See https://github.com/llvm/llvm-project/issues/53543.
25342 #if 0
25343   Style.ColumnLimit = 65;
25344 
25345   verifyFormat("if (condition) {\n"
25346                "  ff(Indices,\n"
25347                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25348                "} else {\n"
25349                "  ff(Indices,\n"
25350                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25351                "}",
25352                Style);
25353 
25354   Style.ColumnLimit = 20;
25355 
25356   verifyFormat("if (a) {\n"
25357                "  b = c + // 1 -\n"
25358                "      d;\n"
25359                "}",
25360                Style);
25361 
25362   verifyFormat("if (a) {\n"
25363                "  b = c >= 0 ? d\n"
25364                "             : e;\n"
25365                "}",
25366                "if (a) {\n"
25367                "  b = c >= 0 ? d : e;\n"
25368                "}",
25369                Style);
25370 #endif
25371 
25372   Style.ColumnLimit = 20;
25373 
25374   verifyFormat("if (a)\n"
25375                "  b = c > 0 ? d : e;",
25376                "if (a) {\n"
25377                "  b = c > 0 ? d : e;\n"
25378                "}",
25379                Style);
25380 
25381   Style.ColumnLimit = 0;
25382 
25383   verifyFormat("if (a)\n"
25384                "  b234567890223456789032345678904234567890 = "
25385                "c234567890223456789032345678904234567890;",
25386                "if (a) {\n"
25387                "  b234567890223456789032345678904234567890 = "
25388                "c234567890223456789032345678904234567890;\n"
25389                "}",
25390                Style);
25391 }
25392 
25393 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
25394   auto Style = getLLVMStyle();
25395 
25396   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
25397                     "void functionDecl(int a, int b, int c);";
25398 
25399   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25400                      "paramF, paramG, paramH, paramI);\n"
25401                      "void functionDecl(int argumentA, int argumentB, int "
25402                      "argumentC, int argumentD, int argumentE);";
25403 
25404   verifyFormat(Short, Style);
25405 
25406   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25407                       "paramF, paramG, paramH,\n"
25408                       "             paramI);\n"
25409                       "void functionDecl(int argumentA, int argumentB, int "
25410                       "argumentC, int argumentD,\n"
25411                       "                  int argumentE);";
25412 
25413   verifyFormat(NoBreak, Medium, Style);
25414   verifyFormat(NoBreak,
25415                "functionCall(\n"
25416                "    paramA,\n"
25417                "    paramB,\n"
25418                "    paramC,\n"
25419                "    paramD,\n"
25420                "    paramE,\n"
25421                "    paramF,\n"
25422                "    paramG,\n"
25423                "    paramH,\n"
25424                "    paramI\n"
25425                ");\n"
25426                "void functionDecl(\n"
25427                "    int argumentA,\n"
25428                "    int argumentB,\n"
25429                "    int argumentC,\n"
25430                "    int argumentD,\n"
25431                "    int argumentE\n"
25432                ");",
25433                Style);
25434 
25435   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
25436                "                  nestedLongFunctionCall(argument1, "
25437                "argument2, argument3,\n"
25438                "                                         argument4, "
25439                "argument5));",
25440                Style);
25441 
25442   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25443 
25444   verifyFormat(Short, Style);
25445   verifyFormat(
25446       "functionCall(\n"
25447       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25448       "paramI\n"
25449       ");\n"
25450       "void functionDecl(\n"
25451       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25452       "argumentE\n"
25453       ");",
25454       Medium, Style);
25455 
25456   Style.AllowAllArgumentsOnNextLine = false;
25457   Style.AllowAllParametersOfDeclarationOnNextLine = false;
25458 
25459   verifyFormat(Short, Style);
25460   verifyFormat(
25461       "functionCall(\n"
25462       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25463       "paramI\n"
25464       ");\n"
25465       "void functionDecl(\n"
25466       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25467       "argumentE\n"
25468       ");",
25469       Medium, Style);
25470 
25471   Style.BinPackArguments = false;
25472   Style.BinPackParameters = false;
25473 
25474   verifyFormat(Short, Style);
25475 
25476   verifyFormat("functionCall(\n"
25477                "    paramA,\n"
25478                "    paramB,\n"
25479                "    paramC,\n"
25480                "    paramD,\n"
25481                "    paramE,\n"
25482                "    paramF,\n"
25483                "    paramG,\n"
25484                "    paramH,\n"
25485                "    paramI\n"
25486                ");\n"
25487                "void functionDecl(\n"
25488                "    int argumentA,\n"
25489                "    int argumentB,\n"
25490                "    int argumentC,\n"
25491                "    int argumentD,\n"
25492                "    int argumentE\n"
25493                ");",
25494                Medium, Style);
25495 
25496   verifyFormat("outerFunctionCall(\n"
25497                "    nestedFunctionCall(argument1),\n"
25498                "    nestedLongFunctionCall(\n"
25499                "        argument1,\n"
25500                "        argument2,\n"
25501                "        argument3,\n"
25502                "        argument4,\n"
25503                "        argument5\n"
25504                "    )\n"
25505                ");",
25506                Style);
25507 
25508   verifyFormat("int a = (int)b;", Style);
25509   verifyFormat("int a = (int)b;",
25510                "int a = (\n"
25511                "    int\n"
25512                ") b;",
25513                Style);
25514 
25515   verifyFormat("return (true);", Style);
25516   verifyFormat("return (true);",
25517                "return (\n"
25518                "    true\n"
25519                ");",
25520                Style);
25521 
25522   verifyFormat("void foo();", Style);
25523   verifyFormat("void foo();",
25524                "void foo(\n"
25525                ");",
25526                Style);
25527 
25528   verifyFormat("void foo() {}", Style);
25529   verifyFormat("void foo() {}",
25530                "void foo(\n"
25531                ") {\n"
25532                "}",
25533                Style);
25534 
25535   verifyFormat("auto string = std::string();", Style);
25536   verifyFormat("auto string = std::string();",
25537                "auto string = std::string(\n"
25538                ");",
25539                Style);
25540 
25541   verifyFormat("void (*functionPointer)() = nullptr;", Style);
25542   verifyFormat("void (*functionPointer)() = nullptr;",
25543                "void (\n"
25544                "    *functionPointer\n"
25545                ")\n"
25546                "(\n"
25547                ") = nullptr;",
25548                Style);
25549 }
25550 
25551 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
25552   auto Style = getLLVMStyle();
25553 
25554   verifyFormat("if (foo()) {\n"
25555                "  return;\n"
25556                "}",
25557                Style);
25558 
25559   verifyFormat("if (quitelongarg !=\n"
25560                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25561                "comment\n"
25562                "  return;\n"
25563                "}",
25564                Style);
25565 
25566   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25567 
25568   verifyFormat("if (foo()) {\n"
25569                "  return;\n"
25570                "}",
25571                Style);
25572 
25573   verifyFormat("if (quitelongarg !=\n"
25574                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25575                "comment\n"
25576                "  return;\n"
25577                "}",
25578                Style);
25579 }
25580 
25581 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
25582   auto Style = getLLVMStyle();
25583 
25584   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25585                "  doSomething();\n"
25586                "}",
25587                Style);
25588 
25589   verifyFormat("for (int myReallyLongCountVariable = 0; "
25590                "myReallyLongCountVariable < count;\n"
25591                "     myReallyLongCountVariable++) {\n"
25592                "  doSomething();\n"
25593                "}",
25594                Style);
25595 
25596   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25597 
25598   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25599                "  doSomething();\n"
25600                "}",
25601                Style);
25602 
25603   verifyFormat("for (int myReallyLongCountVariable = 0; "
25604                "myReallyLongCountVariable < count;\n"
25605                "     myReallyLongCountVariable++) {\n"
25606                "  doSomething();\n"
25607                "}",
25608                Style);
25609 }
25610 
25611 TEST_F(FormatTest, UnderstandsDigraphs) {
25612   verifyFormat("int arr<:5:> = {};");
25613   verifyFormat("int arr[5] = <%%>;");
25614   verifyFormat("int arr<:::qualified_variable:> = {};");
25615   verifyFormat("int arr[::qualified_variable] = <%%>;");
25616   verifyFormat("%:include <header>");
25617   verifyFormat("%:define A x##y");
25618   verifyFormat("#define A x%:%:y");
25619 }
25620 
25621 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
25622   auto Style = getLLVMStyle();
25623   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
25624   Style.AlignConsecutiveAssignments.Enabled = true;
25625   Style.AlignConsecutiveDeclarations.Enabled = true;
25626 
25627   // The AlignArray code is incorrect for non square Arrays and can cause
25628   // crashes, these tests assert that the array is not changed but will
25629   // also act as regression tests for when it is properly fixed
25630   verifyFormat("struct test demo[] = {\n"
25631                "    {1, 2},\n"
25632                "    {3, 4, 5},\n"
25633                "    {6, 7, 8}\n"
25634                "};",
25635                Style);
25636   verifyFormat("struct test demo[] = {\n"
25637                "    {1, 2, 3, 4, 5},\n"
25638                "    {3, 4, 5},\n"
25639                "    {6, 7, 8}\n"
25640                "};",
25641                Style);
25642   verifyFormat("struct test demo[] = {\n"
25643                "    {1, 2, 3, 4, 5},\n"
25644                "    {3, 4, 5},\n"
25645                "    {6, 7, 8, 9, 10, 11, 12}\n"
25646                "};",
25647                Style);
25648   verifyFormat("struct test demo[] = {\n"
25649                "    {1, 2, 3},\n"
25650                "    {3, 4, 5},\n"
25651                "    {6, 7, 8, 9, 10, 11, 12}\n"
25652                "};",
25653                Style);
25654 
25655   verifyFormat("S{\n"
25656                "    {},\n"
25657                "    {},\n"
25658                "    {a, b}\n"
25659                "};",
25660                Style);
25661   verifyFormat("S{\n"
25662                "    {},\n"
25663                "    {},\n"
25664                "    {a, b},\n"
25665                "};",
25666                Style);
25667   verifyFormat("void foo() {\n"
25668                "  auto thing = test{\n"
25669                "      {\n"
25670                "       {13}, {something}, // A\n"
25671                "      }\n"
25672                "  };\n"
25673                "}",
25674                "void foo() {\n"
25675                "  auto thing = test{\n"
25676                "      {\n"
25677                "       {13},\n"
25678                "       {something}, // A\n"
25679                "      }\n"
25680                "  };\n"
25681                "}",
25682                Style);
25683 }
25684 
25685 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
25686   auto Style = getLLVMStyle();
25687   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
25688   Style.AlignConsecutiveAssignments.Enabled = true;
25689   Style.AlignConsecutiveDeclarations.Enabled = true;
25690 
25691   // The AlignArray code is incorrect for non square Arrays and can cause
25692   // crashes, these tests assert that the array is not changed but will
25693   // also act as regression tests for when it is properly fixed
25694   verifyFormat("struct test demo[] = {\n"
25695                "    {1, 2},\n"
25696                "    {3, 4, 5},\n"
25697                "    {6, 7, 8}\n"
25698                "};",
25699                Style);
25700   verifyFormat("struct test demo[] = {\n"
25701                "    {1, 2, 3, 4, 5},\n"
25702                "    {3, 4, 5},\n"
25703                "    {6, 7, 8}\n"
25704                "};",
25705                Style);
25706   verifyFormat("struct test demo[] = {\n"
25707                "    {1, 2, 3, 4, 5},\n"
25708                "    {3, 4, 5},\n"
25709                "    {6, 7, 8, 9, 10, 11, 12}\n"
25710                "};",
25711                Style);
25712   verifyFormat("struct test demo[] = {\n"
25713                "    {1, 2, 3},\n"
25714                "    {3, 4, 5},\n"
25715                "    {6, 7, 8, 9, 10, 11, 12}\n"
25716                "};",
25717                Style);
25718 
25719   verifyFormat("S{\n"
25720                "    {},\n"
25721                "    {},\n"
25722                "    {a, b}\n"
25723                "};",
25724                Style);
25725   verifyFormat("S{\n"
25726                "    {},\n"
25727                "    {},\n"
25728                "    {a, b},\n"
25729                "};",
25730                Style);
25731   verifyFormat("void foo() {\n"
25732                "  auto thing = test{\n"
25733                "      {\n"
25734                "       {13}, {something}, // A\n"
25735                "      }\n"
25736                "  };\n"
25737                "}",
25738                "void foo() {\n"
25739                "  auto thing = test{\n"
25740                "      {\n"
25741                "       {13},\n"
25742                "       {something}, // A\n"
25743                "      }\n"
25744                "  };\n"
25745                "}",
25746                Style);
25747 }
25748 
25749 TEST_F(FormatTest, FormatsVariableTemplates) {
25750   verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
25751   verifyFormat("template <typename T> "
25752                "inline bool var = is_integral_v<T> && is_signed_v<T>;");
25753 }
25754 
25755 } // namespace
25756 } // namespace format
25757 } // namespace clang
25758