1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Format/Format.h"
10 
11 #include "../Tooling/ReplacementTest.h"
12 #include "FormatTestUtils.h"
13 
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "gtest/gtest.h"
17 
18 #define DEBUG_TYPE "format-test"
19 
20 using clang::tooling::ReplacementTest;
21 using clang::tooling::toReplacements;
22 using testing::ScopedTrace;
23 
24 namespace clang {
25 namespace format {
26 namespace {
27 
28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
29 
30 class FormatTest : public ::testing::Test {
31 protected:
32   enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
33 
34   std::string format(llvm::StringRef Code,
35                      const FormatStyle &Style = getLLVMStyle(),
36                      StatusCheck CheckComplete = SC_ExpectComplete) {
37     LLVM_DEBUG(llvm::errs() << "---\n");
38     LLVM_DEBUG(llvm::errs() << Code << "\n\n");
39     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
40     FormattingAttemptStatus Status;
41     tooling::Replacements Replaces =
42         reformat(Style, Code, Ranges, "<stdin>", &Status);
43     if (CheckComplete != SC_DoNotCheck) {
44       bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
45       EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
46           << Code << "\n\n";
47     }
48     ReplacementCount = Replaces.size();
49     auto Result = applyAllReplacements(Code, Replaces);
50     EXPECT_TRUE(static_cast<bool>(Result));
51     LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
52     return *Result;
53   }
54 
55   FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) {
56     Style.ColumnLimit = ColumnLimit;
57     return Style;
58   }
59 
60   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
61     return getStyleWithColumns(getLLVMStyle(), ColumnLimit);
62   }
63 
64   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
65     return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
66   }
67 
68   void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
69                      llvm::StringRef Code,
70                      const FormatStyle &Style = getLLVMStyle()) {
71     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
72     EXPECT_EQ(Expected.str(), format(Expected, Style))
73         << "Expected code is not stable";
74     EXPECT_EQ(Expected.str(), format(Code, Style));
75     if (Style.Language == FormatStyle::LK_Cpp) {
76       // Objective-C++ is a superset of C++, so everything checked for C++
77       // needs to be checked for Objective-C++ as well.
78       FormatStyle ObjCStyle = Style;
79       ObjCStyle.Language = FormatStyle::LK_ObjC;
80       EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle));
81     }
82   }
83 
84   void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
85                      const FormatStyle &Style = getLLVMStyle()) {
86     _verifyFormat(File, Line, Code, test::messUp(Code), Style);
87   }
88 
89   void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code,
90                                const FormatStyle &Style = getLLVMStyle()) {
91     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
92     EXPECT_EQ(Code.str(),
93               format(test::messUp(Code), Style, SC_ExpectIncomplete));
94   }
95 
96   void _verifyIndependentOfContext(const char *File, int Line,
97                                    llvm::StringRef Text,
98                                    const FormatStyle &Style = getLLVMStyle()) {
99     _verifyFormat(File, Line, Text, Style);
100     _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
101                   Style);
102   }
103 
104   /// \brief Verify that clang-format does not crash on the given input.
105   void verifyNoCrash(llvm::StringRef Code,
106                      const FormatStyle &Style = getLLVMStyle()) {
107     format(Code, Style, SC_DoNotCheck);
108   }
109 
110   int ReplacementCount;
111 };
112 
113 #define verifyIndependentOfContext(...)                                        \
114   _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
115 #define verifyIncompleteFormat(...)                                            \
116   _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
119 
120 TEST_F(FormatTest, MessUp) {
121   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
122   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
123   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
124   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
125   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
126 }
127 
128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
129   EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
130 }
131 
132 TEST_F(FormatTest, LLVMStyleOverride) {
133   EXPECT_EQ(FormatStyle::LK_Proto,
134             getLLVMStyle(FormatStyle::LK_Proto).Language);
135 }
136 
137 //===----------------------------------------------------------------------===//
138 // Basic function tests.
139 //===----------------------------------------------------------------------===//
140 
141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
142   EXPECT_EQ(";", format(";"));
143 }
144 
145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
146   EXPECT_EQ("int i;", format("  int i;"));
147   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
148   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
149   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
150 }
151 
152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
153   EXPECT_EQ("int i;", format("int\ni;"));
154 }
155 
156 TEST_F(FormatTest, FormatsNestedBlockStatements) {
157   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
158 }
159 
160 TEST_F(FormatTest, FormatsNestedCall) {
161   verifyFormat("Method(f1, f2(f3));");
162   verifyFormat("Method(f1(f2, f3()));");
163   verifyFormat("Method(f1(f2, (f3())));");
164 }
165 
166 TEST_F(FormatTest, NestedNameSpecifiers) {
167   verifyFormat("vector<::Type> v;");
168   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
169   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
170   verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
171   verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
172   verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
173   verifyFormat("bool a = 2 < ::SomeFunction();");
174   verifyFormat("ALWAYS_INLINE ::std::string getName();");
175   verifyFormat("some::string getName();");
176 }
177 
178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
179   EXPECT_EQ("if (a) {\n"
180             "  f();\n"
181             "}",
182             format("if(a){f();}"));
183   EXPECT_EQ(4, ReplacementCount);
184   EXPECT_EQ("if (a) {\n"
185             "  f();\n"
186             "}",
187             format("if (a) {\n"
188                    "  f();\n"
189                    "}"));
190   EXPECT_EQ(0, ReplacementCount);
191   EXPECT_EQ("/*\r\n"
192             "\r\n"
193             "*/\r\n",
194             format("/*\r\n"
195                    "\r\n"
196                    "*/\r\n"));
197   EXPECT_EQ(0, ReplacementCount);
198 }
199 
200 TEST_F(FormatTest, RemovesEmptyLines) {
201   EXPECT_EQ("class C {\n"
202             "  int i;\n"
203             "};",
204             format("class C {\n"
205                    " int i;\n"
206                    "\n"
207                    "};"));
208 
209   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
210   EXPECT_EQ("namespace N {\n"
211             "\n"
212             "int i;\n"
213             "}",
214             format("namespace N {\n"
215                    "\n"
216                    "int    i;\n"
217                    "}",
218                    getGoogleStyle()));
219   EXPECT_EQ("/* something */ namespace N {\n"
220             "\n"
221             "int i;\n"
222             "}",
223             format("/* something */ namespace N {\n"
224                    "\n"
225                    "int    i;\n"
226                    "}",
227                    getGoogleStyle()));
228   EXPECT_EQ("inline namespace N {\n"
229             "\n"
230             "int i;\n"
231             "}",
232             format("inline namespace N {\n"
233                    "\n"
234                    "int    i;\n"
235                    "}",
236                    getGoogleStyle()));
237   EXPECT_EQ("/* something */ inline namespace N {\n"
238             "\n"
239             "int i;\n"
240             "}",
241             format("/* something */ inline namespace N {\n"
242                    "\n"
243                    "int    i;\n"
244                    "}",
245                    getGoogleStyle()));
246   EXPECT_EQ("export namespace N {\n"
247             "\n"
248             "int i;\n"
249             "}",
250             format("export namespace N {\n"
251                    "\n"
252                    "int    i;\n"
253                    "}",
254                    getGoogleStyle()));
255   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
256             "\n"
257             "int i;\n"
258             "}",
259             format("extern /**/ \"C\" /**/ {\n"
260                    "\n"
261                    "int    i;\n"
262                    "}",
263                    getGoogleStyle()));
264 
265   auto CustomStyle = getLLVMStyle();
266   CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom;
267   CustomStyle.BraceWrapping.AfterNamespace = true;
268   CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
269   EXPECT_EQ("namespace N\n"
270             "{\n"
271             "\n"
272             "int i;\n"
273             "}",
274             format("namespace N\n"
275                    "{\n"
276                    "\n"
277                    "\n"
278                    "int    i;\n"
279                    "}",
280                    CustomStyle));
281   EXPECT_EQ("/* something */ namespace N\n"
282             "{\n"
283             "\n"
284             "int i;\n"
285             "}",
286             format("/* something */ namespace N {\n"
287                    "\n"
288                    "\n"
289                    "int    i;\n"
290                    "}",
291                    CustomStyle));
292   EXPECT_EQ("inline namespace N\n"
293             "{\n"
294             "\n"
295             "int i;\n"
296             "}",
297             format("inline namespace N\n"
298                    "{\n"
299                    "\n"
300                    "\n"
301                    "int    i;\n"
302                    "}",
303                    CustomStyle));
304   EXPECT_EQ("/* something */ inline namespace N\n"
305             "{\n"
306             "\n"
307             "int i;\n"
308             "}",
309             format("/* something */ inline namespace N\n"
310                    "{\n"
311                    "\n"
312                    "int    i;\n"
313                    "}",
314                    CustomStyle));
315   EXPECT_EQ("export namespace N\n"
316             "{\n"
317             "\n"
318             "int i;\n"
319             "}",
320             format("export namespace N\n"
321                    "{\n"
322                    "\n"
323                    "int    i;\n"
324                    "}",
325                    CustomStyle));
326   EXPECT_EQ("namespace a\n"
327             "{\n"
328             "namespace b\n"
329             "{\n"
330             "\n"
331             "class AA {};\n"
332             "\n"
333             "} // namespace b\n"
334             "} // namespace a\n",
335             format("namespace a\n"
336                    "{\n"
337                    "namespace b\n"
338                    "{\n"
339                    "\n"
340                    "\n"
341                    "class AA {};\n"
342                    "\n"
343                    "\n"
344                    "}\n"
345                    "}\n",
346                    CustomStyle));
347   EXPECT_EQ("namespace A /* comment */\n"
348             "{\n"
349             "class B {}\n"
350             "} // namespace A",
351             format("namespace A /* comment */ { class B {} }", CustomStyle));
352   EXPECT_EQ("namespace A\n"
353             "{ /* comment */\n"
354             "class B {}\n"
355             "} // namespace A",
356             format("namespace A {/* comment */ class B {} }", CustomStyle));
357   EXPECT_EQ("namespace A\n"
358             "{ /* comment */\n"
359             "\n"
360             "class B {}\n"
361             "\n"
362             ""
363             "} // namespace A",
364             format("namespace A { /* comment */\n"
365                    "\n"
366                    "\n"
367                    "class B {}\n"
368                    "\n"
369                    "\n"
370                    "}",
371                    CustomStyle));
372   EXPECT_EQ("namespace A /* comment */\n"
373             "{\n"
374             "\n"
375             "class B {}\n"
376             "\n"
377             "} // namespace A",
378             format("namespace A/* comment */ {\n"
379                    "\n"
380                    "\n"
381                    "class B {}\n"
382                    "\n"
383                    "\n"
384                    "}",
385                    CustomStyle));
386 
387   // ...but do keep inlining and removing empty lines for non-block extern "C"
388   // functions.
389   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
390   EXPECT_EQ("extern \"C\" int f() {\n"
391             "  int i = 42;\n"
392             "  return i;\n"
393             "}",
394             format("extern \"C\" int f() {\n"
395                    "\n"
396                    "  int i = 42;\n"
397                    "  return i;\n"
398                    "}",
399                    getGoogleStyle()));
400 
401   // Remove empty lines at the beginning and end of blocks.
402   EXPECT_EQ("void f() {\n"
403             "\n"
404             "  if (a) {\n"
405             "\n"
406             "    f();\n"
407             "  }\n"
408             "}",
409             format("void f() {\n"
410                    "\n"
411                    "  if (a) {\n"
412                    "\n"
413                    "    f();\n"
414                    "\n"
415                    "  }\n"
416                    "\n"
417                    "}",
418                    getLLVMStyle()));
419   EXPECT_EQ("void f() {\n"
420             "  if (a) {\n"
421             "    f();\n"
422             "  }\n"
423             "}",
424             format("void f() {\n"
425                    "\n"
426                    "  if (a) {\n"
427                    "\n"
428                    "    f();\n"
429                    "\n"
430                    "  }\n"
431                    "\n"
432                    "}",
433                    getGoogleStyle()));
434 
435   // Don't remove empty lines in more complex control statements.
436   EXPECT_EQ("void f() {\n"
437             "  if (a) {\n"
438             "    f();\n"
439             "\n"
440             "  } else if (b) {\n"
441             "    f();\n"
442             "  }\n"
443             "}",
444             format("void f() {\n"
445                    "  if (a) {\n"
446                    "    f();\n"
447                    "\n"
448                    "  } else if (b) {\n"
449                    "    f();\n"
450                    "\n"
451                    "  }\n"
452                    "\n"
453                    "}"));
454 
455   // Don't remove empty lines before namespace endings.
456   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
457   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
458   EXPECT_EQ("namespace {\n"
459             "int i;\n"
460             "\n"
461             "}",
462             format("namespace {\n"
463                    "int i;\n"
464                    "\n"
465                    "}",
466                    LLVMWithNoNamespaceFix));
467   EXPECT_EQ("namespace {\n"
468             "int i;\n"
469             "}",
470             format("namespace {\n"
471                    "int i;\n"
472                    "}",
473                    LLVMWithNoNamespaceFix));
474   EXPECT_EQ("namespace {\n"
475             "int i;\n"
476             "\n"
477             "};",
478             format("namespace {\n"
479                    "int i;\n"
480                    "\n"
481                    "};",
482                    LLVMWithNoNamespaceFix));
483   EXPECT_EQ("namespace {\n"
484             "int i;\n"
485             "};",
486             format("namespace {\n"
487                    "int i;\n"
488                    "};",
489                    LLVMWithNoNamespaceFix));
490   EXPECT_EQ("namespace {\n"
491             "int i;\n"
492             "\n"
493             "}",
494             format("namespace {\n"
495                    "int i;\n"
496                    "\n"
497                    "}"));
498   EXPECT_EQ("namespace {\n"
499             "int i;\n"
500             "\n"
501             "} // namespace",
502             format("namespace {\n"
503                    "int i;\n"
504                    "\n"
505                    "}  // namespace"));
506 
507   FormatStyle Style = getLLVMStyle();
508   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
509   Style.MaxEmptyLinesToKeep = 2;
510   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
511   Style.BraceWrapping.AfterClass = true;
512   Style.BraceWrapping.AfterFunction = true;
513   Style.KeepEmptyLinesAtTheStartOfBlocks = false;
514 
515   EXPECT_EQ("class Foo\n"
516             "{\n"
517             "  Foo() {}\n"
518             "\n"
519             "  void funk() {}\n"
520             "};",
521             format("class Foo\n"
522                    "{\n"
523                    "  Foo()\n"
524                    "  {\n"
525                    "  }\n"
526                    "\n"
527                    "  void funk() {}\n"
528                    "};",
529                    Style));
530 }
531 
532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
533   verifyFormat("x = (a) and (b);");
534   verifyFormat("x = (a) or (b);");
535   verifyFormat("x = (a) bitand (b);");
536   verifyFormat("x = (a) bitor (b);");
537   verifyFormat("x = (a) not_eq (b);");
538   verifyFormat("x = (a) and_eq (b);");
539   verifyFormat("x = (a) or_eq (b);");
540   verifyFormat("x = (a) xor (b);");
541 }
542 
543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
544   verifyFormat("x = compl(a);");
545   verifyFormat("x = not(a);");
546   verifyFormat("x = bitand(a);");
547   // Unary operator must not be merged with the next identifier
548   verifyFormat("x = compl a;");
549   verifyFormat("x = not a;");
550   verifyFormat("x = bitand a;");
551 }
552 
553 //===----------------------------------------------------------------------===//
554 // Tests for control statements.
555 //===----------------------------------------------------------------------===//
556 
557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
558   verifyFormat("if (true)\n  f();\ng();");
559   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
560   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
561   verifyFormat("if constexpr (true)\n"
562                "  f();\ng();");
563   verifyFormat("if CONSTEXPR (true)\n"
564                "  f();\ng();");
565   verifyFormat("if constexpr (a)\n"
566                "  if constexpr (b)\n"
567                "    if constexpr (c)\n"
568                "      g();\n"
569                "h();");
570   verifyFormat("if CONSTEXPR (a)\n"
571                "  if CONSTEXPR (b)\n"
572                "    if CONSTEXPR (c)\n"
573                "      g();\n"
574                "h();");
575   verifyFormat("if constexpr (a)\n"
576                "  if constexpr (b) {\n"
577                "    f();\n"
578                "  }\n"
579                "g();");
580   verifyFormat("if CONSTEXPR (a)\n"
581                "  if CONSTEXPR (b) {\n"
582                "    f();\n"
583                "  }\n"
584                "g();");
585 
586   verifyFormat("if consteval {\n}");
587   verifyFormat("if !consteval {\n}");
588   verifyFormat("if not consteval {\n}");
589   verifyFormat("if consteval {\n} else {\n}");
590   verifyFormat("if !consteval {\n} else {\n}");
591   verifyFormat("if consteval {\n"
592                "  f();\n"
593                "}");
594   verifyFormat("if !consteval {\n"
595                "  f();\n"
596                "}");
597   verifyFormat("if consteval {\n"
598                "  f();\n"
599                "} else {\n"
600                "  g();\n"
601                "}");
602   verifyFormat("if CONSTEVAL {\n"
603                "  f();\n"
604                "}");
605   verifyFormat("if !CONSTEVAL {\n"
606                "  f();\n"
607                "}");
608 
609   verifyFormat("if (a)\n"
610                "  g();");
611   verifyFormat("if (a) {\n"
612                "  g()\n"
613                "};");
614   verifyFormat("if (a)\n"
615                "  g();\n"
616                "else\n"
617                "  g();");
618   verifyFormat("if (a) {\n"
619                "  g();\n"
620                "} else\n"
621                "  g();");
622   verifyFormat("if (a)\n"
623                "  g();\n"
624                "else {\n"
625                "  g();\n"
626                "}");
627   verifyFormat("if (a) {\n"
628                "  g();\n"
629                "} else {\n"
630                "  g();\n"
631                "}");
632   verifyFormat("if (a)\n"
633                "  g();\n"
634                "else if (b)\n"
635                "  g();\n"
636                "else\n"
637                "  g();");
638   verifyFormat("if (a) {\n"
639                "  g();\n"
640                "} else if (b)\n"
641                "  g();\n"
642                "else\n"
643                "  g();");
644   verifyFormat("if (a)\n"
645                "  g();\n"
646                "else if (b) {\n"
647                "  g();\n"
648                "} else\n"
649                "  g();");
650   verifyFormat("if (a)\n"
651                "  g();\n"
652                "else if (b)\n"
653                "  g();\n"
654                "else {\n"
655                "  g();\n"
656                "}");
657   verifyFormat("if (a)\n"
658                "  g();\n"
659                "else if (b) {\n"
660                "  g();\n"
661                "} else {\n"
662                "  g();\n"
663                "}");
664   verifyFormat("if (a) {\n"
665                "  g();\n"
666                "} else if (b) {\n"
667                "  g();\n"
668                "} else {\n"
669                "  g();\n"
670                "}");
671 
672   FormatStyle AllowsMergedIf = getLLVMStyle();
673   AllowsMergedIf.IfMacros.push_back("MYIF");
674   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
675   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
676       FormatStyle::SIS_WithoutElse;
677   verifyFormat("if (a)\n"
678                "  // comment\n"
679                "  f();",
680                AllowsMergedIf);
681   verifyFormat("{\n"
682                "  if (a)\n"
683                "  label:\n"
684                "    f();\n"
685                "}",
686                AllowsMergedIf);
687   verifyFormat("#define A \\\n"
688                "  if (a)  \\\n"
689                "  label:  \\\n"
690                "    f()",
691                AllowsMergedIf);
692   verifyFormat("if (a)\n"
693                "  ;",
694                AllowsMergedIf);
695   verifyFormat("if (a)\n"
696                "  if (b) return;",
697                AllowsMergedIf);
698 
699   verifyFormat("if (a) // Can't merge this\n"
700                "  f();\n",
701                AllowsMergedIf);
702   verifyFormat("if (a) /* still don't merge */\n"
703                "  f();",
704                AllowsMergedIf);
705   verifyFormat("if (a) { // Never merge this\n"
706                "  f();\n"
707                "}",
708                AllowsMergedIf);
709   verifyFormat("if (a) { /* Never merge this */\n"
710                "  f();\n"
711                "}",
712                AllowsMergedIf);
713   verifyFormat("MYIF (a)\n"
714                "  // comment\n"
715                "  f();",
716                AllowsMergedIf);
717   verifyFormat("{\n"
718                "  MYIF (a)\n"
719                "  label:\n"
720                "    f();\n"
721                "}",
722                AllowsMergedIf);
723   verifyFormat("#define A  \\\n"
724                "  MYIF (a) \\\n"
725                "  label:   \\\n"
726                "    f()",
727                AllowsMergedIf);
728   verifyFormat("MYIF (a)\n"
729                "  ;",
730                AllowsMergedIf);
731   verifyFormat("MYIF (a)\n"
732                "  MYIF (b) return;",
733                AllowsMergedIf);
734 
735   verifyFormat("MYIF (a) // Can't merge this\n"
736                "  f();\n",
737                AllowsMergedIf);
738   verifyFormat("MYIF (a) /* still don't merge */\n"
739                "  f();",
740                AllowsMergedIf);
741   verifyFormat("MYIF (a) { // Never merge this\n"
742                "  f();\n"
743                "}",
744                AllowsMergedIf);
745   verifyFormat("MYIF (a) { /* Never merge this */\n"
746                "  f();\n"
747                "}",
748                AllowsMergedIf);
749 
750   AllowsMergedIf.ColumnLimit = 14;
751   // Where line-lengths matter, a 2-letter synonym that maintains line length.
752   // Not IF to avoid any confusion that IF is somehow special.
753   AllowsMergedIf.IfMacros.push_back("FI");
754   verifyFormat("if (a) return;", AllowsMergedIf);
755   verifyFormat("if (aaaaaaaaa)\n"
756                "  return;",
757                AllowsMergedIf);
758   verifyFormat("FI (a) return;", AllowsMergedIf);
759   verifyFormat("FI (aaaaaaaaa)\n"
760                "  return;",
761                AllowsMergedIf);
762 
763   AllowsMergedIf.ColumnLimit = 13;
764   verifyFormat("if (a)\n  return;", AllowsMergedIf);
765   verifyFormat("FI (a)\n  return;", AllowsMergedIf);
766 
767   FormatStyle AllowsMergedIfElse = getLLVMStyle();
768   AllowsMergedIfElse.IfMacros.push_back("MYIF");
769   AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
770       FormatStyle::SIS_AllIfsAndElse;
771   verifyFormat("if (a)\n"
772                "  // comment\n"
773                "  f();\n"
774                "else\n"
775                "  // comment\n"
776                "  f();",
777                AllowsMergedIfElse);
778   verifyFormat("{\n"
779                "  if (a)\n"
780                "  label:\n"
781                "    f();\n"
782                "  else\n"
783                "  label:\n"
784                "    f();\n"
785                "}",
786                AllowsMergedIfElse);
787   verifyFormat("if (a)\n"
788                "  ;\n"
789                "else\n"
790                "  ;",
791                AllowsMergedIfElse);
792   verifyFormat("if (a) {\n"
793                "} else {\n"
794                "}",
795                AllowsMergedIfElse);
796   verifyFormat("if (a) return;\n"
797                "else if (b) return;\n"
798                "else return;",
799                AllowsMergedIfElse);
800   verifyFormat("if (a) {\n"
801                "} else return;",
802                AllowsMergedIfElse);
803   verifyFormat("if (a) {\n"
804                "} else if (b) return;\n"
805                "else return;",
806                AllowsMergedIfElse);
807   verifyFormat("if (a) return;\n"
808                "else if (b) {\n"
809                "} else return;",
810                AllowsMergedIfElse);
811   verifyFormat("if (a)\n"
812                "  if (b) return;\n"
813                "  else return;",
814                AllowsMergedIfElse);
815   verifyFormat("if constexpr (a)\n"
816                "  if constexpr (b) return;\n"
817                "  else if constexpr (c) return;\n"
818                "  else return;",
819                AllowsMergedIfElse);
820   verifyFormat("MYIF (a)\n"
821                "  // comment\n"
822                "  f();\n"
823                "else\n"
824                "  // comment\n"
825                "  f();",
826                AllowsMergedIfElse);
827   verifyFormat("{\n"
828                "  MYIF (a)\n"
829                "  label:\n"
830                "    f();\n"
831                "  else\n"
832                "  label:\n"
833                "    f();\n"
834                "}",
835                AllowsMergedIfElse);
836   verifyFormat("MYIF (a)\n"
837                "  ;\n"
838                "else\n"
839                "  ;",
840                AllowsMergedIfElse);
841   verifyFormat("MYIF (a) {\n"
842                "} else {\n"
843                "}",
844                AllowsMergedIfElse);
845   verifyFormat("MYIF (a) return;\n"
846                "else MYIF (b) return;\n"
847                "else return;",
848                AllowsMergedIfElse);
849   verifyFormat("MYIF (a) {\n"
850                "} else return;",
851                AllowsMergedIfElse);
852   verifyFormat("MYIF (a) {\n"
853                "} else MYIF (b) return;\n"
854                "else return;",
855                AllowsMergedIfElse);
856   verifyFormat("MYIF (a) return;\n"
857                "else MYIF (b) {\n"
858                "} else return;",
859                AllowsMergedIfElse);
860   verifyFormat("MYIF (a)\n"
861                "  MYIF (b) return;\n"
862                "  else return;",
863                AllowsMergedIfElse);
864   verifyFormat("MYIF constexpr (a)\n"
865                "  MYIF constexpr (b) return;\n"
866                "  else MYIF constexpr (c) return;\n"
867                "  else return;",
868                AllowsMergedIfElse);
869 }
870 
871 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
872   FormatStyle AllowsMergedIf = getLLVMStyle();
873   AllowsMergedIf.IfMacros.push_back("MYIF");
874   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
875   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
876       FormatStyle::SIS_WithoutElse;
877   verifyFormat("if (a)\n"
878                "  f();\n"
879                "else {\n"
880                "  g();\n"
881                "}",
882                AllowsMergedIf);
883   verifyFormat("if (a)\n"
884                "  f();\n"
885                "else\n"
886                "  g();\n",
887                AllowsMergedIf);
888 
889   verifyFormat("if (a) g();", AllowsMergedIf);
890   verifyFormat("if (a) {\n"
891                "  g()\n"
892                "};",
893                AllowsMergedIf);
894   verifyFormat("if (a)\n"
895                "  g();\n"
896                "else\n"
897                "  g();",
898                AllowsMergedIf);
899   verifyFormat("if (a) {\n"
900                "  g();\n"
901                "} else\n"
902                "  g();",
903                AllowsMergedIf);
904   verifyFormat("if (a)\n"
905                "  g();\n"
906                "else {\n"
907                "  g();\n"
908                "}",
909                AllowsMergedIf);
910   verifyFormat("if (a) {\n"
911                "  g();\n"
912                "} else {\n"
913                "  g();\n"
914                "}",
915                AllowsMergedIf);
916   verifyFormat("if (a)\n"
917                "  g();\n"
918                "else if (b)\n"
919                "  g();\n"
920                "else\n"
921                "  g();",
922                AllowsMergedIf);
923   verifyFormat("if (a) {\n"
924                "  g();\n"
925                "} else if (b)\n"
926                "  g();\n"
927                "else\n"
928                "  g();",
929                AllowsMergedIf);
930   verifyFormat("if (a)\n"
931                "  g();\n"
932                "else if (b) {\n"
933                "  g();\n"
934                "} else\n"
935                "  g();",
936                AllowsMergedIf);
937   verifyFormat("if (a)\n"
938                "  g();\n"
939                "else if (b)\n"
940                "  g();\n"
941                "else {\n"
942                "  g();\n"
943                "}",
944                AllowsMergedIf);
945   verifyFormat("if (a)\n"
946                "  g();\n"
947                "else if (b) {\n"
948                "  g();\n"
949                "} else {\n"
950                "  g();\n"
951                "}",
952                AllowsMergedIf);
953   verifyFormat("if (a) {\n"
954                "  g();\n"
955                "} else if (b) {\n"
956                "  g();\n"
957                "} else {\n"
958                "  g();\n"
959                "}",
960                AllowsMergedIf);
961   verifyFormat("MYIF (a)\n"
962                "  f();\n"
963                "else {\n"
964                "  g();\n"
965                "}",
966                AllowsMergedIf);
967   verifyFormat("MYIF (a)\n"
968                "  f();\n"
969                "else\n"
970                "  g();\n",
971                AllowsMergedIf);
972 
973   verifyFormat("MYIF (a) g();", AllowsMergedIf);
974   verifyFormat("MYIF (a) {\n"
975                "  g()\n"
976                "};",
977                AllowsMergedIf);
978   verifyFormat("MYIF (a)\n"
979                "  g();\n"
980                "else\n"
981                "  g();",
982                AllowsMergedIf);
983   verifyFormat("MYIF (a) {\n"
984                "  g();\n"
985                "} else\n"
986                "  g();",
987                AllowsMergedIf);
988   verifyFormat("MYIF (a)\n"
989                "  g();\n"
990                "else {\n"
991                "  g();\n"
992                "}",
993                AllowsMergedIf);
994   verifyFormat("MYIF (a) {\n"
995                "  g();\n"
996                "} else {\n"
997                "  g();\n"
998                "}",
999                AllowsMergedIf);
1000   verifyFormat("MYIF (a)\n"
1001                "  g();\n"
1002                "else MYIF (b)\n"
1003                "  g();\n"
1004                "else\n"
1005                "  g();",
1006                AllowsMergedIf);
1007   verifyFormat("MYIF (a)\n"
1008                "  g();\n"
1009                "else if (b)\n"
1010                "  g();\n"
1011                "else\n"
1012                "  g();",
1013                AllowsMergedIf);
1014   verifyFormat("MYIF (a) {\n"
1015                "  g();\n"
1016                "} else MYIF (b)\n"
1017                "  g();\n"
1018                "else\n"
1019                "  g();",
1020                AllowsMergedIf);
1021   verifyFormat("MYIF (a) {\n"
1022                "  g();\n"
1023                "} else if (b)\n"
1024                "  g();\n"
1025                "else\n"
1026                "  g();",
1027                AllowsMergedIf);
1028   verifyFormat("MYIF (a)\n"
1029                "  g();\n"
1030                "else MYIF (b) {\n"
1031                "  g();\n"
1032                "} else\n"
1033                "  g();",
1034                AllowsMergedIf);
1035   verifyFormat("MYIF (a)\n"
1036                "  g();\n"
1037                "else if (b) {\n"
1038                "  g();\n"
1039                "} else\n"
1040                "  g();",
1041                AllowsMergedIf);
1042   verifyFormat("MYIF (a)\n"
1043                "  g();\n"
1044                "else MYIF (b)\n"
1045                "  g();\n"
1046                "else {\n"
1047                "  g();\n"
1048                "}",
1049                AllowsMergedIf);
1050   verifyFormat("MYIF (a)\n"
1051                "  g();\n"
1052                "else if (b)\n"
1053                "  g();\n"
1054                "else {\n"
1055                "  g();\n"
1056                "}",
1057                AllowsMergedIf);
1058   verifyFormat("MYIF (a)\n"
1059                "  g();\n"
1060                "else MYIF (b) {\n"
1061                "  g();\n"
1062                "} else {\n"
1063                "  g();\n"
1064                "}",
1065                AllowsMergedIf);
1066   verifyFormat("MYIF (a)\n"
1067                "  g();\n"
1068                "else if (b) {\n"
1069                "  g();\n"
1070                "} else {\n"
1071                "  g();\n"
1072                "}",
1073                AllowsMergedIf);
1074   verifyFormat("MYIF (a) {\n"
1075                "  g();\n"
1076                "} else MYIF (b) {\n"
1077                "  g();\n"
1078                "} else {\n"
1079                "  g();\n"
1080                "}",
1081                AllowsMergedIf);
1082   verifyFormat("MYIF (a) {\n"
1083                "  g();\n"
1084                "} else if (b) {\n"
1085                "  g();\n"
1086                "} else {\n"
1087                "  g();\n"
1088                "}",
1089                AllowsMergedIf);
1090 
1091   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1092       FormatStyle::SIS_OnlyFirstIf;
1093 
1094   verifyFormat("if (a) f();\n"
1095                "else {\n"
1096                "  g();\n"
1097                "}",
1098                AllowsMergedIf);
1099   verifyFormat("if (a) f();\n"
1100                "else {\n"
1101                "  if (a) f();\n"
1102                "  else {\n"
1103                "    g();\n"
1104                "  }\n"
1105                "  g();\n"
1106                "}",
1107                AllowsMergedIf);
1108 
1109   verifyFormat("if (a) g();", AllowsMergedIf);
1110   verifyFormat("if (a) {\n"
1111                "  g()\n"
1112                "};",
1113                AllowsMergedIf);
1114   verifyFormat("if (a) g();\n"
1115                "else\n"
1116                "  g();",
1117                AllowsMergedIf);
1118   verifyFormat("if (a) {\n"
1119                "  g();\n"
1120                "} else\n"
1121                "  g();",
1122                AllowsMergedIf);
1123   verifyFormat("if (a) g();\n"
1124                "else {\n"
1125                "  g();\n"
1126                "}",
1127                AllowsMergedIf);
1128   verifyFormat("if (a) {\n"
1129                "  g();\n"
1130                "} else {\n"
1131                "  g();\n"
1132                "}",
1133                AllowsMergedIf);
1134   verifyFormat("if (a) g();\n"
1135                "else if (b)\n"
1136                "  g();\n"
1137                "else\n"
1138                "  g();",
1139                AllowsMergedIf);
1140   verifyFormat("if (a) {\n"
1141                "  g();\n"
1142                "} else if (b)\n"
1143                "  g();\n"
1144                "else\n"
1145                "  g();",
1146                AllowsMergedIf);
1147   verifyFormat("if (a) g();\n"
1148                "else if (b) {\n"
1149                "  g();\n"
1150                "} else\n"
1151                "  g();",
1152                AllowsMergedIf);
1153   verifyFormat("if (a) g();\n"
1154                "else if (b)\n"
1155                "  g();\n"
1156                "else {\n"
1157                "  g();\n"
1158                "}",
1159                AllowsMergedIf);
1160   verifyFormat("if (a) g();\n"
1161                "else if (b) {\n"
1162                "  g();\n"
1163                "} else {\n"
1164                "  g();\n"
1165                "}",
1166                AllowsMergedIf);
1167   verifyFormat("if (a) {\n"
1168                "  g();\n"
1169                "} else if (b) {\n"
1170                "  g();\n"
1171                "} else {\n"
1172                "  g();\n"
1173                "}",
1174                AllowsMergedIf);
1175   verifyFormat("MYIF (a) f();\n"
1176                "else {\n"
1177                "  g();\n"
1178                "}",
1179                AllowsMergedIf);
1180   verifyFormat("MYIF (a) f();\n"
1181                "else {\n"
1182                "  if (a) f();\n"
1183                "  else {\n"
1184                "    g();\n"
1185                "  }\n"
1186                "  g();\n"
1187                "}",
1188                AllowsMergedIf);
1189 
1190   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1191   verifyFormat("MYIF (a) {\n"
1192                "  g()\n"
1193                "};",
1194                AllowsMergedIf);
1195   verifyFormat("MYIF (a) g();\n"
1196                "else\n"
1197                "  g();",
1198                AllowsMergedIf);
1199   verifyFormat("MYIF (a) {\n"
1200                "  g();\n"
1201                "} else\n"
1202                "  g();",
1203                AllowsMergedIf);
1204   verifyFormat("MYIF (a) g();\n"
1205                "else {\n"
1206                "  g();\n"
1207                "}",
1208                AllowsMergedIf);
1209   verifyFormat("MYIF (a) {\n"
1210                "  g();\n"
1211                "} else {\n"
1212                "  g();\n"
1213                "}",
1214                AllowsMergedIf);
1215   verifyFormat("MYIF (a) g();\n"
1216                "else MYIF (b)\n"
1217                "  g();\n"
1218                "else\n"
1219                "  g();",
1220                AllowsMergedIf);
1221   verifyFormat("MYIF (a) g();\n"
1222                "else if (b)\n"
1223                "  g();\n"
1224                "else\n"
1225                "  g();",
1226                AllowsMergedIf);
1227   verifyFormat("MYIF (a) {\n"
1228                "  g();\n"
1229                "} else MYIF (b)\n"
1230                "  g();\n"
1231                "else\n"
1232                "  g();",
1233                AllowsMergedIf);
1234   verifyFormat("MYIF (a) {\n"
1235                "  g();\n"
1236                "} else if (b)\n"
1237                "  g();\n"
1238                "else\n"
1239                "  g();",
1240                AllowsMergedIf);
1241   verifyFormat("MYIF (a) g();\n"
1242                "else MYIF (b) {\n"
1243                "  g();\n"
1244                "} else\n"
1245                "  g();",
1246                AllowsMergedIf);
1247   verifyFormat("MYIF (a) g();\n"
1248                "else if (b) {\n"
1249                "  g();\n"
1250                "} else\n"
1251                "  g();",
1252                AllowsMergedIf);
1253   verifyFormat("MYIF (a) g();\n"
1254                "else MYIF (b)\n"
1255                "  g();\n"
1256                "else {\n"
1257                "  g();\n"
1258                "}",
1259                AllowsMergedIf);
1260   verifyFormat("MYIF (a) g();\n"
1261                "else if (b)\n"
1262                "  g();\n"
1263                "else {\n"
1264                "  g();\n"
1265                "}",
1266                AllowsMergedIf);
1267   verifyFormat("MYIF (a) g();\n"
1268                "else MYIF (b) {\n"
1269                "  g();\n"
1270                "} else {\n"
1271                "  g();\n"
1272                "}",
1273                AllowsMergedIf);
1274   verifyFormat("MYIF (a) g();\n"
1275                "else if (b) {\n"
1276                "  g();\n"
1277                "} else {\n"
1278                "  g();\n"
1279                "}",
1280                AllowsMergedIf);
1281   verifyFormat("MYIF (a) {\n"
1282                "  g();\n"
1283                "} else MYIF (b) {\n"
1284                "  g();\n"
1285                "} else {\n"
1286                "  g();\n"
1287                "}",
1288                AllowsMergedIf);
1289   verifyFormat("MYIF (a) {\n"
1290                "  g();\n"
1291                "} else if (b) {\n"
1292                "  g();\n"
1293                "} else {\n"
1294                "  g();\n"
1295                "}",
1296                AllowsMergedIf);
1297 
1298   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1299       FormatStyle::SIS_AllIfsAndElse;
1300 
1301   verifyFormat("if (a) f();\n"
1302                "else {\n"
1303                "  g();\n"
1304                "}",
1305                AllowsMergedIf);
1306   verifyFormat("if (a) f();\n"
1307                "else {\n"
1308                "  if (a) f();\n"
1309                "  else {\n"
1310                "    g();\n"
1311                "  }\n"
1312                "  g();\n"
1313                "}",
1314                AllowsMergedIf);
1315 
1316   verifyFormat("if (a) g();", AllowsMergedIf);
1317   verifyFormat("if (a) {\n"
1318                "  g()\n"
1319                "};",
1320                AllowsMergedIf);
1321   verifyFormat("if (a) g();\n"
1322                "else g();",
1323                AllowsMergedIf);
1324   verifyFormat("if (a) {\n"
1325                "  g();\n"
1326                "} else g();",
1327                AllowsMergedIf);
1328   verifyFormat("if (a) g();\n"
1329                "else {\n"
1330                "  g();\n"
1331                "}",
1332                AllowsMergedIf);
1333   verifyFormat("if (a) {\n"
1334                "  g();\n"
1335                "} else {\n"
1336                "  g();\n"
1337                "}",
1338                AllowsMergedIf);
1339   verifyFormat("if (a) g();\n"
1340                "else if (b) g();\n"
1341                "else g();",
1342                AllowsMergedIf);
1343   verifyFormat("if (a) {\n"
1344                "  g();\n"
1345                "} else if (b) g();\n"
1346                "else g();",
1347                AllowsMergedIf);
1348   verifyFormat("if (a) g();\n"
1349                "else if (b) {\n"
1350                "  g();\n"
1351                "} else g();",
1352                AllowsMergedIf);
1353   verifyFormat("if (a) g();\n"
1354                "else if (b) g();\n"
1355                "else {\n"
1356                "  g();\n"
1357                "}",
1358                AllowsMergedIf);
1359   verifyFormat("if (a) g();\n"
1360                "else if (b) {\n"
1361                "  g();\n"
1362                "} else {\n"
1363                "  g();\n"
1364                "}",
1365                AllowsMergedIf);
1366   verifyFormat("if (a) {\n"
1367                "  g();\n"
1368                "} else if (b) {\n"
1369                "  g();\n"
1370                "} else {\n"
1371                "  g();\n"
1372                "}",
1373                AllowsMergedIf);
1374   verifyFormat("MYIF (a) f();\n"
1375                "else {\n"
1376                "  g();\n"
1377                "}",
1378                AllowsMergedIf);
1379   verifyFormat("MYIF (a) f();\n"
1380                "else {\n"
1381                "  if (a) f();\n"
1382                "  else {\n"
1383                "    g();\n"
1384                "  }\n"
1385                "  g();\n"
1386                "}",
1387                AllowsMergedIf);
1388 
1389   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1390   verifyFormat("MYIF (a) {\n"
1391                "  g()\n"
1392                "};",
1393                AllowsMergedIf);
1394   verifyFormat("MYIF (a) g();\n"
1395                "else g();",
1396                AllowsMergedIf);
1397   verifyFormat("MYIF (a) {\n"
1398                "  g();\n"
1399                "} else g();",
1400                AllowsMergedIf);
1401   verifyFormat("MYIF (a) g();\n"
1402                "else {\n"
1403                "  g();\n"
1404                "}",
1405                AllowsMergedIf);
1406   verifyFormat("MYIF (a) {\n"
1407                "  g();\n"
1408                "} else {\n"
1409                "  g();\n"
1410                "}",
1411                AllowsMergedIf);
1412   verifyFormat("MYIF (a) g();\n"
1413                "else MYIF (b) g();\n"
1414                "else g();",
1415                AllowsMergedIf);
1416   verifyFormat("MYIF (a) g();\n"
1417                "else if (b) g();\n"
1418                "else g();",
1419                AllowsMergedIf);
1420   verifyFormat("MYIF (a) {\n"
1421                "  g();\n"
1422                "} else MYIF (b) g();\n"
1423                "else g();",
1424                AllowsMergedIf);
1425   verifyFormat("MYIF (a) {\n"
1426                "  g();\n"
1427                "} else if (b) g();\n"
1428                "else g();",
1429                AllowsMergedIf);
1430   verifyFormat("MYIF (a) g();\n"
1431                "else MYIF (b) {\n"
1432                "  g();\n"
1433                "} else g();",
1434                AllowsMergedIf);
1435   verifyFormat("MYIF (a) g();\n"
1436                "else if (b) {\n"
1437                "  g();\n"
1438                "} else g();",
1439                AllowsMergedIf);
1440   verifyFormat("MYIF (a) g();\n"
1441                "else MYIF (b) g();\n"
1442                "else {\n"
1443                "  g();\n"
1444                "}",
1445                AllowsMergedIf);
1446   verifyFormat("MYIF (a) g();\n"
1447                "else if (b) g();\n"
1448                "else {\n"
1449                "  g();\n"
1450                "}",
1451                AllowsMergedIf);
1452   verifyFormat("MYIF (a) g();\n"
1453                "else MYIF (b) {\n"
1454                "  g();\n"
1455                "} else {\n"
1456                "  g();\n"
1457                "}",
1458                AllowsMergedIf);
1459   verifyFormat("MYIF (a) g();\n"
1460                "else if (b) {\n"
1461                "  g();\n"
1462                "} else {\n"
1463                "  g();\n"
1464                "}",
1465                AllowsMergedIf);
1466   verifyFormat("MYIF (a) {\n"
1467                "  g();\n"
1468                "} else MYIF (b) {\n"
1469                "  g();\n"
1470                "} else {\n"
1471                "  g();\n"
1472                "}",
1473                AllowsMergedIf);
1474   verifyFormat("MYIF (a) {\n"
1475                "  g();\n"
1476                "} else if (b) {\n"
1477                "  g();\n"
1478                "} else {\n"
1479                "  g();\n"
1480                "}",
1481                AllowsMergedIf);
1482 }
1483 
1484 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
1485   FormatStyle AllowsMergedLoops = getLLVMStyle();
1486   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
1487   verifyFormat("while (true) continue;", AllowsMergedLoops);
1488   verifyFormat("for (;;) continue;", AllowsMergedLoops);
1489   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
1490   verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
1491   verifyFormat("while (true)\n"
1492                "  ;",
1493                AllowsMergedLoops);
1494   verifyFormat("for (;;)\n"
1495                "  ;",
1496                AllowsMergedLoops);
1497   verifyFormat("for (;;)\n"
1498                "  for (;;) continue;",
1499                AllowsMergedLoops);
1500   verifyFormat("for (;;)\n"
1501                "  while (true) continue;",
1502                AllowsMergedLoops);
1503   verifyFormat("while (true)\n"
1504                "  for (;;) continue;",
1505                AllowsMergedLoops);
1506   verifyFormat("BOOST_FOREACH (int &v, vec)\n"
1507                "  for (;;) continue;",
1508                AllowsMergedLoops);
1509   verifyFormat("for (;;)\n"
1510                "  BOOST_FOREACH (int &v, vec) continue;",
1511                AllowsMergedLoops);
1512   verifyFormat("for (;;) // Can't merge this\n"
1513                "  continue;",
1514                AllowsMergedLoops);
1515   verifyFormat("for (;;) /* still don't merge */\n"
1516                "  continue;",
1517                AllowsMergedLoops);
1518   verifyFormat("do a++;\n"
1519                "while (true);",
1520                AllowsMergedLoops);
1521   verifyFormat("do /* Don't merge */\n"
1522                "  a++;\n"
1523                "while (true);",
1524                AllowsMergedLoops);
1525   verifyFormat("do // Don't merge\n"
1526                "  a++;\n"
1527                "while (true);",
1528                AllowsMergedLoops);
1529   verifyFormat("do\n"
1530                "  // Don't merge\n"
1531                "  a++;\n"
1532                "while (true);",
1533                AllowsMergedLoops);
1534   // Without braces labels are interpreted differently.
1535   verifyFormat("{\n"
1536                "  do\n"
1537                "  label:\n"
1538                "    a++;\n"
1539                "  while (true);\n"
1540                "}",
1541                AllowsMergedLoops);
1542 }
1543 
1544 TEST_F(FormatTest, FormatShortBracedStatements) {
1545   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
1546   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false);
1547   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine,
1548             FormatStyle::SIS_Never);
1549   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false);
1550   EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false);
1551   verifyFormat("for (;;) {\n"
1552                "  f();\n"
1553                "}");
1554   verifyFormat("/*comment*/ for (;;) {\n"
1555                "  f();\n"
1556                "}");
1557   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1558                "  f();\n"
1559                "}");
1560   verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n"
1561                "  f();\n"
1562                "}");
1563   verifyFormat("while (true) {\n"
1564                "  f();\n"
1565                "}");
1566   verifyFormat("/*comment*/ while (true) {\n"
1567                "  f();\n"
1568                "}");
1569   verifyFormat("if (true) {\n"
1570                "  f();\n"
1571                "}");
1572   verifyFormat("/*comment*/ if (true) {\n"
1573                "  f();\n"
1574                "}");
1575 
1576   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1577   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1578   // Not IF to avoid any confusion that IF is somehow special.
1579   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1580   AllowSimpleBracedStatements.ColumnLimit = 40;
1581   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1582       FormatStyle::SBS_Always;
1583 
1584   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1585       FormatStyle::SIS_WithoutElse;
1586   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1587 
1588   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1589   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1590   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1591 
1592   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1593   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1594   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1595   verifyFormat("if consteval {}", AllowSimpleBracedStatements);
1596   verifyFormat("if !consteval {}", AllowSimpleBracedStatements);
1597   verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements);
1598   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1599   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1600   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1601   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1602   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1603   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1604   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1605   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1606   verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements);
1607   verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements);
1608   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1609   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1610   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1611   verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements);
1612   verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements);
1613   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1614   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1615   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1616                AllowSimpleBracedStatements);
1617   verifyFormat("if (true) {\n"
1618                "  ffffffffffffffffffffffff();\n"
1619                "}",
1620                AllowSimpleBracedStatements);
1621   verifyFormat("if (true) {\n"
1622                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1623                "}",
1624                AllowSimpleBracedStatements);
1625   verifyFormat("if (true) { //\n"
1626                "  f();\n"
1627                "}",
1628                AllowSimpleBracedStatements);
1629   verifyFormat("if (true) {\n"
1630                "  f();\n"
1631                "  f();\n"
1632                "}",
1633                AllowSimpleBracedStatements);
1634   verifyFormat("if (true) {\n"
1635                "  f();\n"
1636                "} else {\n"
1637                "  f();\n"
1638                "}",
1639                AllowSimpleBracedStatements);
1640   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1641                AllowSimpleBracedStatements);
1642   verifyFormat("MYIF (true) {\n"
1643                "  ffffffffffffffffffffffff();\n"
1644                "}",
1645                AllowSimpleBracedStatements);
1646   verifyFormat("MYIF (true) {\n"
1647                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1648                "}",
1649                AllowSimpleBracedStatements);
1650   verifyFormat("MYIF (true) { //\n"
1651                "  f();\n"
1652                "}",
1653                AllowSimpleBracedStatements);
1654   verifyFormat("MYIF (true) {\n"
1655                "  f();\n"
1656                "  f();\n"
1657                "}",
1658                AllowSimpleBracedStatements);
1659   verifyFormat("MYIF (true) {\n"
1660                "  f();\n"
1661                "} else {\n"
1662                "  f();\n"
1663                "}",
1664                AllowSimpleBracedStatements);
1665 
1666   verifyFormat("struct A2 {\n"
1667                "  int X;\n"
1668                "};",
1669                AllowSimpleBracedStatements);
1670   verifyFormat("typedef struct A2 {\n"
1671                "  int X;\n"
1672                "} A2_t;",
1673                AllowSimpleBracedStatements);
1674   verifyFormat("template <int> struct A2 {\n"
1675                "  struct B {};\n"
1676                "};",
1677                AllowSimpleBracedStatements);
1678 
1679   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1680       FormatStyle::SIS_Never;
1681   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1682   verifyFormat("if (true) {\n"
1683                "  f();\n"
1684                "}",
1685                AllowSimpleBracedStatements);
1686   verifyFormat("if (true) {\n"
1687                "  f();\n"
1688                "} else {\n"
1689                "  f();\n"
1690                "}",
1691                AllowSimpleBracedStatements);
1692   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1693   verifyFormat("MYIF (true) {\n"
1694                "  f();\n"
1695                "}",
1696                AllowSimpleBracedStatements);
1697   verifyFormat("MYIF (true) {\n"
1698                "  f();\n"
1699                "} else {\n"
1700                "  f();\n"
1701                "}",
1702                AllowSimpleBracedStatements);
1703 
1704   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1705   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1706   verifyFormat("while (true) {\n"
1707                "  f();\n"
1708                "}",
1709                AllowSimpleBracedStatements);
1710   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1711   verifyFormat("for (;;) {\n"
1712                "  f();\n"
1713                "}",
1714                AllowSimpleBracedStatements);
1715   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1716   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1717                "  f();\n"
1718                "}",
1719                AllowSimpleBracedStatements);
1720 
1721   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1722       FormatStyle::SIS_WithoutElse;
1723   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1724   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1725       FormatStyle::BWACS_Always;
1726 
1727   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1728   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1729   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1730   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1731   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1732   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1733   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1734   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1735   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1736   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1737   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1738   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1739   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1740   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1741   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1742   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1743   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1744                AllowSimpleBracedStatements);
1745   verifyFormat("if (true)\n"
1746                "{\n"
1747                "  ffffffffffffffffffffffff();\n"
1748                "}",
1749                AllowSimpleBracedStatements);
1750   verifyFormat("if (true)\n"
1751                "{\n"
1752                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1753                "}",
1754                AllowSimpleBracedStatements);
1755   verifyFormat("if (true)\n"
1756                "{ //\n"
1757                "  f();\n"
1758                "}",
1759                AllowSimpleBracedStatements);
1760   verifyFormat("if (true)\n"
1761                "{\n"
1762                "  f();\n"
1763                "  f();\n"
1764                "}",
1765                AllowSimpleBracedStatements);
1766   verifyFormat("if (true)\n"
1767                "{\n"
1768                "  f();\n"
1769                "} else\n"
1770                "{\n"
1771                "  f();\n"
1772                "}",
1773                AllowSimpleBracedStatements);
1774   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1775                AllowSimpleBracedStatements);
1776   verifyFormat("MYIF (true)\n"
1777                "{\n"
1778                "  ffffffffffffffffffffffff();\n"
1779                "}",
1780                AllowSimpleBracedStatements);
1781   verifyFormat("MYIF (true)\n"
1782                "{\n"
1783                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1784                "}",
1785                AllowSimpleBracedStatements);
1786   verifyFormat("MYIF (true)\n"
1787                "{ //\n"
1788                "  f();\n"
1789                "}",
1790                AllowSimpleBracedStatements);
1791   verifyFormat("MYIF (true)\n"
1792                "{\n"
1793                "  f();\n"
1794                "  f();\n"
1795                "}",
1796                AllowSimpleBracedStatements);
1797   verifyFormat("MYIF (true)\n"
1798                "{\n"
1799                "  f();\n"
1800                "} else\n"
1801                "{\n"
1802                "  f();\n"
1803                "}",
1804                AllowSimpleBracedStatements);
1805 
1806   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1807       FormatStyle::SIS_Never;
1808   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1809   verifyFormat("if (true)\n"
1810                "{\n"
1811                "  f();\n"
1812                "}",
1813                AllowSimpleBracedStatements);
1814   verifyFormat("if (true)\n"
1815                "{\n"
1816                "  f();\n"
1817                "} else\n"
1818                "{\n"
1819                "  f();\n"
1820                "}",
1821                AllowSimpleBracedStatements);
1822   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1823   verifyFormat("MYIF (true)\n"
1824                "{\n"
1825                "  f();\n"
1826                "}",
1827                AllowSimpleBracedStatements);
1828   verifyFormat("MYIF (true)\n"
1829                "{\n"
1830                "  f();\n"
1831                "} else\n"
1832                "{\n"
1833                "  f();\n"
1834                "}",
1835                AllowSimpleBracedStatements);
1836 
1837   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1838   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1839   verifyFormat("while (true)\n"
1840                "{\n"
1841                "  f();\n"
1842                "}",
1843                AllowSimpleBracedStatements);
1844   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1845   verifyFormat("for (;;)\n"
1846                "{\n"
1847                "  f();\n"
1848                "}",
1849                AllowSimpleBracedStatements);
1850   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1851   verifyFormat("BOOST_FOREACH (int v, vec)\n"
1852                "{\n"
1853                "  f();\n"
1854                "}",
1855                AllowSimpleBracedStatements);
1856 }
1857 
1858 TEST_F(FormatTest, UnderstandsMacros) {
1859   verifyFormat("#define A (parentheses)");
1860   verifyFormat("/* comment */ #define A (parentheses)");
1861   verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
1862   // Even the partial code should never be merged.
1863   EXPECT_EQ("/* comment */ #define A (parentheses)\n"
1864             "#",
1865             format("/* comment */ #define A (parentheses)\n"
1866                    "#"));
1867   verifyFormat("/* comment */ #define A (parentheses)\n"
1868                "#\n");
1869   verifyFormat("/* comment */ #define A (parentheses)\n"
1870                "#define B (parentheses)");
1871   verifyFormat("#define true ((int)1)");
1872   verifyFormat("#define and(x)");
1873   verifyFormat("#define if(x) x");
1874   verifyFormat("#define return(x) (x)");
1875   verifyFormat("#define while(x) for (; x;)");
1876   verifyFormat("#define xor(x) (^(x))");
1877   verifyFormat("#define __except(x)");
1878   verifyFormat("#define __try(x)");
1879 
1880   // https://llvm.org/PR54348.
1881   verifyFormat(
1882       "#define A"
1883       "                                                                      "
1884       "\\\n"
1885       "  class & {}");
1886 
1887   FormatStyle Style = getLLVMStyle();
1888   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1889   Style.BraceWrapping.AfterFunction = true;
1890   // Test that a macro definition never gets merged with the following
1891   // definition.
1892   // FIXME: The AAA macro definition probably should not be split into 3 lines.
1893   verifyFormat("#define AAA                                                    "
1894                "                \\\n"
1895                "  N                                                            "
1896                "                \\\n"
1897                "  {\n"
1898                "#define BBB }\n",
1899                Style);
1900   // verifyFormat("#define AAA N { //\n", Style);
1901 
1902   verifyFormat("MACRO(return)");
1903   verifyFormat("MACRO(co_await)");
1904   verifyFormat("MACRO(co_return)");
1905   verifyFormat("MACRO(co_yield)");
1906   verifyFormat("MACRO(return, something)");
1907   verifyFormat("MACRO(co_return, something)");
1908   verifyFormat("MACRO(something##something)");
1909   verifyFormat("MACRO(return##something)");
1910   verifyFormat("MACRO(co_return##something)");
1911 }
1912 
1913 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1914   FormatStyle Style = getLLVMStyleWithColumns(60);
1915   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1916   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1917   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1918   EXPECT_EQ("#define A                                                  \\\n"
1919             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1920             "  {                                                        \\\n"
1921             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1922             "  }\n"
1923             "X;",
1924             format("#define A \\\n"
1925                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1926                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1927                    "   }\n"
1928                    "X;",
1929                    Style));
1930 }
1931 
1932 TEST_F(FormatTest, ParseIfElse) {
1933   verifyFormat("if (true)\n"
1934                "  if (true)\n"
1935                "    if (true)\n"
1936                "      f();\n"
1937                "    else\n"
1938                "      g();\n"
1939                "  else\n"
1940                "    h();\n"
1941                "else\n"
1942                "  i();");
1943   verifyFormat("if (true)\n"
1944                "  if (true)\n"
1945                "    if (true) {\n"
1946                "      if (true)\n"
1947                "        f();\n"
1948                "    } else {\n"
1949                "      g();\n"
1950                "    }\n"
1951                "  else\n"
1952                "    h();\n"
1953                "else {\n"
1954                "  i();\n"
1955                "}");
1956   verifyFormat("if (true)\n"
1957                "  if constexpr (true)\n"
1958                "    if (true) {\n"
1959                "      if constexpr (true)\n"
1960                "        f();\n"
1961                "    } else {\n"
1962                "      g();\n"
1963                "    }\n"
1964                "  else\n"
1965                "    h();\n"
1966                "else {\n"
1967                "  i();\n"
1968                "}");
1969   verifyFormat("if (true)\n"
1970                "  if CONSTEXPR (true)\n"
1971                "    if (true) {\n"
1972                "      if CONSTEXPR (true)\n"
1973                "        f();\n"
1974                "    } else {\n"
1975                "      g();\n"
1976                "    }\n"
1977                "  else\n"
1978                "    h();\n"
1979                "else {\n"
1980                "  i();\n"
1981                "}");
1982   verifyFormat("void f() {\n"
1983                "  if (a) {\n"
1984                "  } else {\n"
1985                "  }\n"
1986                "}");
1987 }
1988 
1989 TEST_F(FormatTest, ElseIf) {
1990   verifyFormat("if (a) {\n} else if (b) {\n}");
1991   verifyFormat("if (a)\n"
1992                "  f();\n"
1993                "else if (b)\n"
1994                "  g();\n"
1995                "else\n"
1996                "  h();");
1997   verifyFormat("if (a)\n"
1998                "  f();\n"
1999                "else // comment\n"
2000                "  if (b) {\n"
2001                "    g();\n"
2002                "    h();\n"
2003                "  }");
2004   verifyFormat("if constexpr (a)\n"
2005                "  f();\n"
2006                "else if constexpr (b)\n"
2007                "  g();\n"
2008                "else\n"
2009                "  h();");
2010   verifyFormat("if CONSTEXPR (a)\n"
2011                "  f();\n"
2012                "else if CONSTEXPR (b)\n"
2013                "  g();\n"
2014                "else\n"
2015                "  h();");
2016   verifyFormat("if (a) {\n"
2017                "  f();\n"
2018                "}\n"
2019                "// or else ..\n"
2020                "else {\n"
2021                "  g()\n"
2022                "}");
2023 
2024   verifyFormat("if (a) {\n"
2025                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2026                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2027                "}");
2028   verifyFormat("if (a) {\n"
2029                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2030                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2031                "}");
2032   verifyFormat("if (a) {\n"
2033                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2034                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2035                "}");
2036   verifyFormat("if (a) {\n"
2037                "} else if (\n"
2038                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2039                "}",
2040                getLLVMStyleWithColumns(62));
2041   verifyFormat("if (a) {\n"
2042                "} else if constexpr (\n"
2043                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2044                "}",
2045                getLLVMStyleWithColumns(62));
2046   verifyFormat("if (a) {\n"
2047                "} else if CONSTEXPR (\n"
2048                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2049                "}",
2050                getLLVMStyleWithColumns(62));
2051 }
2052 
2053 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
2054   FormatStyle Style = getLLVMStyle();
2055   EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
2056   EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer);
2057   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
2058   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
2059   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
2060   verifyFormat("int *f1(int &a) const &;", Style);
2061   verifyFormat("int *f1(int &a) const & = 0;", Style);
2062   verifyFormat("int *a = f1();", Style);
2063   verifyFormat("int &b = f2();", Style);
2064   verifyFormat("int &&c = f3();", Style);
2065   verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2066   verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2067   verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2068   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2069   verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2070   verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2071   verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2072   verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
2073   verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
2074   verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
2075   verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
2076   verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
2077   verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
2078   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
2079   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
2080   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
2081   verifyFormat(
2082       "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n"
2083       "                     res2 = [](int &a) { return 0000000000000; };",
2084       Style);
2085 
2086   Style.AlignConsecutiveDeclarations.Enabled = true;
2087   verifyFormat("Const unsigned int *c;\n"
2088                "const unsigned int *d;\n"
2089                "Const unsigned int &e;\n"
2090                "const unsigned int &f;\n"
2091                "const unsigned    &&g;\n"
2092                "Const unsigned      h;",
2093                Style);
2094 
2095   Style.PointerAlignment = FormatStyle::PAS_Left;
2096   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2097   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
2098   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
2099   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
2100   verifyFormat("int* f1(int& a) const& = 0;", Style);
2101   verifyFormat("int* a = f1();", Style);
2102   verifyFormat("int& b = f2();", Style);
2103   verifyFormat("int&& c = f3();", Style);
2104   verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2105   verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2106   verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2107   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2108   verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2109   verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2110   verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2111   verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2112   verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
2113   verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
2114   verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
2115   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2116   verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
2117   verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
2118   verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
2119   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
2120   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
2121   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
2122   verifyFormat(
2123       "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n"
2124       "                    res2 = [](int& a) { return 0000000000000; };",
2125       Style);
2126 
2127   Style.AlignConsecutiveDeclarations.Enabled = true;
2128   verifyFormat("Const unsigned int* c;\n"
2129                "const unsigned int* d;\n"
2130                "Const unsigned int& e;\n"
2131                "const unsigned int& f;\n"
2132                "const unsigned&&    g;\n"
2133                "Const unsigned      h;",
2134                Style);
2135 
2136   Style.PointerAlignment = FormatStyle::PAS_Right;
2137   Style.ReferenceAlignment = FormatStyle::RAS_Left;
2138   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
2139   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
2140   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
2141   verifyFormat("int *a = f1();", Style);
2142   verifyFormat("int& b = f2();", Style);
2143   verifyFormat("int&& c = f3();", Style);
2144   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2145   verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2146   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
2147 
2148   Style.AlignConsecutiveDeclarations.Enabled = true;
2149   verifyFormat("Const unsigned int *c;\n"
2150                "const unsigned int *d;\n"
2151                "Const unsigned int& e;\n"
2152                "const unsigned int& f;\n"
2153                "const unsigned      g;\n"
2154                "Const unsigned      h;",
2155                Style);
2156 
2157   Style.PointerAlignment = FormatStyle::PAS_Left;
2158   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
2159   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
2160   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
2161   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
2162   verifyFormat("int* a = f1();", Style);
2163   verifyFormat("int & b = f2();", Style);
2164   verifyFormat("int && c = f3();", Style);
2165   verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
2166   verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
2167   verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
2168   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2169   verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
2170   verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
2171   verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
2172   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2173   verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
2174   verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
2175   verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
2176   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
2177   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
2178   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
2179   verifyFormat(
2180       "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n"
2181       "                     res2 = [](int & a) { return 0000000000000; };",
2182       Style);
2183 
2184   Style.AlignConsecutiveDeclarations.Enabled = true;
2185   verifyFormat("Const unsigned int*  c;\n"
2186                "const unsigned int*  d;\n"
2187                "Const unsigned int & e;\n"
2188                "const unsigned int & f;\n"
2189                "const unsigned &&    g;\n"
2190                "Const unsigned       h;",
2191                Style);
2192 
2193   Style.PointerAlignment = FormatStyle::PAS_Middle;
2194   Style.ReferenceAlignment = FormatStyle::RAS_Right;
2195   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
2196   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
2197   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
2198   verifyFormat("int * a = f1();", Style);
2199   verifyFormat("int &b = f2();", Style);
2200   verifyFormat("int &&c = f3();", Style);
2201   verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2202   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2203   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
2204 
2205   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2206   // specifically handled
2207   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2208 }
2209 
2210 TEST_F(FormatTest, FormatsForLoop) {
2211   verifyFormat(
2212       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2213       "     ++VeryVeryLongLoopVariable)\n"
2214       "  ;");
2215   verifyFormat("for (;;)\n"
2216                "  f();");
2217   verifyFormat("for (;;) {\n}");
2218   verifyFormat("for (;;) {\n"
2219                "  f();\n"
2220                "}");
2221   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2222 
2223   verifyFormat(
2224       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2225       "                                          E = UnwrappedLines.end();\n"
2226       "     I != E; ++I) {\n}");
2227 
2228   verifyFormat(
2229       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2230       "     ++IIIII) {\n}");
2231   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2232                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2233                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2234   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2235                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2236                "         E = FD->getDeclsInPrototypeScope().end();\n"
2237                "     I != E; ++I) {\n}");
2238   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2239                "         I = Container.begin(),\n"
2240                "         E = Container.end();\n"
2241                "     I != E; ++I) {\n}",
2242                getLLVMStyleWithColumns(76));
2243 
2244   verifyFormat(
2245       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2246       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2247       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2248       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2249       "     ++aaaaaaaaaaa) {\n}");
2250   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2251                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2252                "     ++i) {\n}");
2253   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2254                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2255                "}");
2256   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2257                "         aaaaaaaaaa);\n"
2258                "     iter; ++iter) {\n"
2259                "}");
2260   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2261                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2262                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2263                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2264 
2265   // These should not be formatted as Objective-C for-in loops.
2266   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2267   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2268   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2269   verifyFormat(
2270       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2271 
2272   FormatStyle NoBinPacking = getLLVMStyle();
2273   NoBinPacking.BinPackParameters = false;
2274   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2275                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2276                "                                           aaaaaaaaaaaaaaaa,\n"
2277                "                                           aaaaaaaaaaaaaaaa,\n"
2278                "                                           aaaaaaaaaaaaaaaa);\n"
2279                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2280                "}",
2281                NoBinPacking);
2282   verifyFormat(
2283       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2284       "                                          E = UnwrappedLines.end();\n"
2285       "     I != E;\n"
2286       "     ++I) {\n}",
2287       NoBinPacking);
2288 
2289   FormatStyle AlignLeft = getLLVMStyle();
2290   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2291   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2292 }
2293 
2294 TEST_F(FormatTest, RangeBasedForLoops) {
2295   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2296                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2297   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2298                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2299   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2300                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2301   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2302                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2303 }
2304 
2305 TEST_F(FormatTest, ForEachLoops) {
2306   FormatStyle Style = getLLVMStyle();
2307   EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2308   EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
2309   verifyFormat("void f() {\n"
2310                "  for (;;) {\n"
2311                "  }\n"
2312                "  foreach (Item *item, itemlist) {\n"
2313                "  }\n"
2314                "  Q_FOREACH (Item *item, itemlist) {\n"
2315                "  }\n"
2316                "  BOOST_FOREACH (Item *item, itemlist) {\n"
2317                "  }\n"
2318                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2319                "}",
2320                Style);
2321   verifyFormat("void f() {\n"
2322                "  for (;;)\n"
2323                "    int j = 1;\n"
2324                "  Q_FOREACH (int v, vec)\n"
2325                "    v *= 2;\n"
2326                "  for (;;) {\n"
2327                "    int j = 1;\n"
2328                "  }\n"
2329                "  Q_FOREACH (int v, vec) {\n"
2330                "    v *= 2;\n"
2331                "  }\n"
2332                "}",
2333                Style);
2334 
2335   FormatStyle ShortBlocks = getLLVMStyle();
2336   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2337   EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
2338   verifyFormat("void f() {\n"
2339                "  for (;;)\n"
2340                "    int j = 1;\n"
2341                "  Q_FOREACH (int &v, vec)\n"
2342                "    v *= 2;\n"
2343                "  for (;;) {\n"
2344                "    int j = 1;\n"
2345                "  }\n"
2346                "  Q_FOREACH (int &v, vec) {\n"
2347                "    int j = 1;\n"
2348                "  }\n"
2349                "}",
2350                ShortBlocks);
2351 
2352   FormatStyle ShortLoops = getLLVMStyle();
2353   ShortLoops.AllowShortLoopsOnASingleLine = true;
2354   EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2355   verifyFormat("void f() {\n"
2356                "  for (;;) int j = 1;\n"
2357                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2358                "  for (;;) {\n"
2359                "    int j = 1;\n"
2360                "  }\n"
2361                "  Q_FOREACH (int &v, vec) {\n"
2362                "    int j = 1;\n"
2363                "  }\n"
2364                "}",
2365                ShortLoops);
2366 
2367   FormatStyle ShortBlocksAndLoops = getLLVMStyle();
2368   ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2369   ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true;
2370   verifyFormat("void f() {\n"
2371                "  for (;;) int j = 1;\n"
2372                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2373                "  for (;;) { int j = 1; }\n"
2374                "  Q_FOREACH (int &v, vec) { int j = 1; }\n"
2375                "}",
2376                ShortBlocksAndLoops);
2377 
2378   Style.SpaceBeforeParens =
2379       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2380   verifyFormat("void f() {\n"
2381                "  for (;;) {\n"
2382                "  }\n"
2383                "  foreach(Item *item, itemlist) {\n"
2384                "  }\n"
2385                "  Q_FOREACH(Item *item, itemlist) {\n"
2386                "  }\n"
2387                "  BOOST_FOREACH(Item *item, itemlist) {\n"
2388                "  }\n"
2389                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2390                "}",
2391                Style);
2392 
2393   // As function-like macros.
2394   verifyFormat("#define foreach(x, y)\n"
2395                "#define Q_FOREACH(x, y)\n"
2396                "#define BOOST_FOREACH(x, y)\n"
2397                "#define UNKNOWN_FOREACH(x, y)\n");
2398 
2399   // Not as function-like macros.
2400   verifyFormat("#define foreach (x, y)\n"
2401                "#define Q_FOREACH (x, y)\n"
2402                "#define BOOST_FOREACH (x, y)\n"
2403                "#define UNKNOWN_FOREACH (x, y)\n");
2404 
2405   // handle microsoft non standard extension
2406   verifyFormat("for each (char c in x->MyStringProperty)");
2407 }
2408 
2409 TEST_F(FormatTest, FormatsWhileLoop) {
2410   verifyFormat("while (true) {\n}");
2411   verifyFormat("while (true)\n"
2412                "  f();");
2413   verifyFormat("while () {\n}");
2414   verifyFormat("while () {\n"
2415                "  f();\n"
2416                "}");
2417 }
2418 
2419 TEST_F(FormatTest, FormatsDoWhile) {
2420   verifyFormat("do {\n"
2421                "  do_something();\n"
2422                "} while (something());");
2423   verifyFormat("do\n"
2424                "  do_something();\n"
2425                "while (something());");
2426 }
2427 
2428 TEST_F(FormatTest, FormatsSwitchStatement) {
2429   verifyFormat("switch (x) {\n"
2430                "case 1:\n"
2431                "  f();\n"
2432                "  break;\n"
2433                "case kFoo:\n"
2434                "case ns::kBar:\n"
2435                "case kBaz:\n"
2436                "  break;\n"
2437                "default:\n"
2438                "  g();\n"
2439                "  break;\n"
2440                "}");
2441   verifyFormat("switch (x) {\n"
2442                "case 1: {\n"
2443                "  f();\n"
2444                "  break;\n"
2445                "}\n"
2446                "case 2: {\n"
2447                "  break;\n"
2448                "}\n"
2449                "}");
2450   verifyFormat("switch (x) {\n"
2451                "case 1: {\n"
2452                "  f();\n"
2453                "  {\n"
2454                "    g();\n"
2455                "    h();\n"
2456                "  }\n"
2457                "  break;\n"
2458                "}\n"
2459                "}");
2460   verifyFormat("switch (x) {\n"
2461                "case 1: {\n"
2462                "  f();\n"
2463                "  if (foo) {\n"
2464                "    g();\n"
2465                "    h();\n"
2466                "  }\n"
2467                "  break;\n"
2468                "}\n"
2469                "}");
2470   verifyFormat("switch (x) {\n"
2471                "case 1: {\n"
2472                "  f();\n"
2473                "  g();\n"
2474                "} break;\n"
2475                "}");
2476   verifyFormat("switch (test)\n"
2477                "  ;");
2478   verifyFormat("switch (x) {\n"
2479                "default: {\n"
2480                "  // Do nothing.\n"
2481                "}\n"
2482                "}");
2483   verifyFormat("switch (x) {\n"
2484                "// comment\n"
2485                "// if 1, do f()\n"
2486                "case 1:\n"
2487                "  f();\n"
2488                "}");
2489   verifyFormat("switch (x) {\n"
2490                "case 1:\n"
2491                "  // Do amazing stuff\n"
2492                "  {\n"
2493                "    f();\n"
2494                "    g();\n"
2495                "  }\n"
2496                "  break;\n"
2497                "}");
2498   verifyFormat("#define A          \\\n"
2499                "  switch (x) {     \\\n"
2500                "  case a:          \\\n"
2501                "    foo = b;       \\\n"
2502                "  }",
2503                getLLVMStyleWithColumns(20));
2504   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2505                "  case OP_name:                        \\\n"
2506                "    return operations::Operation##name\n",
2507                getLLVMStyleWithColumns(40));
2508   verifyFormat("switch (x) {\n"
2509                "case 1:;\n"
2510                "default:;\n"
2511                "  int i;\n"
2512                "}");
2513 
2514   verifyGoogleFormat("switch (x) {\n"
2515                      "  case 1:\n"
2516                      "    f();\n"
2517                      "    break;\n"
2518                      "  case kFoo:\n"
2519                      "  case ns::kBar:\n"
2520                      "  case kBaz:\n"
2521                      "    break;\n"
2522                      "  default:\n"
2523                      "    g();\n"
2524                      "    break;\n"
2525                      "}");
2526   verifyGoogleFormat("switch (x) {\n"
2527                      "  case 1: {\n"
2528                      "    f();\n"
2529                      "    break;\n"
2530                      "  }\n"
2531                      "}");
2532   verifyGoogleFormat("switch (test)\n"
2533                      "  ;");
2534 
2535   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2536                      "  case OP_name:              \\\n"
2537                      "    return operations::Operation##name\n");
2538   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2539                      "  // Get the correction operation class.\n"
2540                      "  switch (OpCode) {\n"
2541                      "    CASE(Add);\n"
2542                      "    CASE(Subtract);\n"
2543                      "    default:\n"
2544                      "      return operations::Unknown;\n"
2545                      "  }\n"
2546                      "#undef OPERATION_CASE\n"
2547                      "}");
2548   verifyFormat("DEBUG({\n"
2549                "  switch (x) {\n"
2550                "  case A:\n"
2551                "    f();\n"
2552                "    break;\n"
2553                "    // fallthrough\n"
2554                "  case B:\n"
2555                "    g();\n"
2556                "    break;\n"
2557                "  }\n"
2558                "});");
2559   EXPECT_EQ("DEBUG({\n"
2560             "  switch (x) {\n"
2561             "  case A:\n"
2562             "    f();\n"
2563             "    break;\n"
2564             "  // On B:\n"
2565             "  case B:\n"
2566             "    g();\n"
2567             "    break;\n"
2568             "  }\n"
2569             "});",
2570             format("DEBUG({\n"
2571                    "  switch (x) {\n"
2572                    "  case A:\n"
2573                    "    f();\n"
2574                    "    break;\n"
2575                    "  // On B:\n"
2576                    "  case B:\n"
2577                    "    g();\n"
2578                    "    break;\n"
2579                    "  }\n"
2580                    "});",
2581                    getLLVMStyle()));
2582   EXPECT_EQ("switch (n) {\n"
2583             "case 0: {\n"
2584             "  return false;\n"
2585             "}\n"
2586             "default: {\n"
2587             "  return true;\n"
2588             "}\n"
2589             "}",
2590             format("switch (n)\n"
2591                    "{\n"
2592                    "case 0: {\n"
2593                    "  return false;\n"
2594                    "}\n"
2595                    "default: {\n"
2596                    "  return true;\n"
2597                    "}\n"
2598                    "}",
2599                    getLLVMStyle()));
2600   verifyFormat("switch (a) {\n"
2601                "case (b):\n"
2602                "  return;\n"
2603                "}");
2604 
2605   verifyFormat("switch (a) {\n"
2606                "case some_namespace::\n"
2607                "    some_constant:\n"
2608                "  return;\n"
2609                "}",
2610                getLLVMStyleWithColumns(34));
2611 
2612   verifyFormat("switch (a) {\n"
2613                "[[likely]] case 1:\n"
2614                "  return;\n"
2615                "}");
2616   verifyFormat("switch (a) {\n"
2617                "[[likely]] [[other::likely]] case 1:\n"
2618                "  return;\n"
2619                "}");
2620   verifyFormat("switch (x) {\n"
2621                "case 1:\n"
2622                "  return;\n"
2623                "[[likely]] case 2:\n"
2624                "  return;\n"
2625                "}");
2626   verifyFormat("switch (a) {\n"
2627                "case 1:\n"
2628                "[[likely]] case 2:\n"
2629                "  return;\n"
2630                "}");
2631   FormatStyle Attributes = getLLVMStyle();
2632   Attributes.AttributeMacros.push_back("LIKELY");
2633   Attributes.AttributeMacros.push_back("OTHER_LIKELY");
2634   verifyFormat("switch (a) {\n"
2635                "LIKELY case b:\n"
2636                "  return;\n"
2637                "}",
2638                Attributes);
2639   verifyFormat("switch (a) {\n"
2640                "LIKELY OTHER_LIKELY() case b:\n"
2641                "  return;\n"
2642                "}",
2643                Attributes);
2644   verifyFormat("switch (a) {\n"
2645                "case 1:\n"
2646                "  return;\n"
2647                "LIKELY case 2:\n"
2648                "  return;\n"
2649                "}",
2650                Attributes);
2651   verifyFormat("switch (a) {\n"
2652                "case 1:\n"
2653                "LIKELY case 2:\n"
2654                "  return;\n"
2655                "}",
2656                Attributes);
2657 
2658   FormatStyle Style = getLLVMStyle();
2659   Style.IndentCaseLabels = true;
2660   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2661   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2662   Style.BraceWrapping.AfterCaseLabel = true;
2663   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2664   EXPECT_EQ("switch (n)\n"
2665             "{\n"
2666             "  case 0:\n"
2667             "  {\n"
2668             "    return false;\n"
2669             "  }\n"
2670             "  default:\n"
2671             "  {\n"
2672             "    return true;\n"
2673             "  }\n"
2674             "}",
2675             format("switch (n) {\n"
2676                    "  case 0: {\n"
2677                    "    return false;\n"
2678                    "  }\n"
2679                    "  default: {\n"
2680                    "    return true;\n"
2681                    "  }\n"
2682                    "}",
2683                    Style));
2684   Style.BraceWrapping.AfterCaseLabel = false;
2685   EXPECT_EQ("switch (n)\n"
2686             "{\n"
2687             "  case 0: {\n"
2688             "    return false;\n"
2689             "  }\n"
2690             "  default: {\n"
2691             "    return true;\n"
2692             "  }\n"
2693             "}",
2694             format("switch (n) {\n"
2695                    "  case 0:\n"
2696                    "  {\n"
2697                    "    return false;\n"
2698                    "  }\n"
2699                    "  default:\n"
2700                    "  {\n"
2701                    "    return true;\n"
2702                    "  }\n"
2703                    "}",
2704                    Style));
2705   Style.IndentCaseLabels = false;
2706   Style.IndentCaseBlocks = true;
2707   EXPECT_EQ("switch (n)\n"
2708             "{\n"
2709             "case 0:\n"
2710             "  {\n"
2711             "    return false;\n"
2712             "  }\n"
2713             "case 1:\n"
2714             "  break;\n"
2715             "default:\n"
2716             "  {\n"
2717             "    return true;\n"
2718             "  }\n"
2719             "}",
2720             format("switch (n) {\n"
2721                    "case 0: {\n"
2722                    "  return false;\n"
2723                    "}\n"
2724                    "case 1:\n"
2725                    "  break;\n"
2726                    "default: {\n"
2727                    "  return true;\n"
2728                    "}\n"
2729                    "}",
2730                    Style));
2731   Style.IndentCaseLabels = true;
2732   Style.IndentCaseBlocks = true;
2733   EXPECT_EQ("switch (n)\n"
2734             "{\n"
2735             "  case 0:\n"
2736             "    {\n"
2737             "      return false;\n"
2738             "    }\n"
2739             "  case 1:\n"
2740             "    break;\n"
2741             "  default:\n"
2742             "    {\n"
2743             "      return true;\n"
2744             "    }\n"
2745             "}",
2746             format("switch (n) {\n"
2747                    "case 0: {\n"
2748                    "  return false;\n"
2749                    "}\n"
2750                    "case 1:\n"
2751                    "  break;\n"
2752                    "default: {\n"
2753                    "  return true;\n"
2754                    "}\n"
2755                    "}",
2756                    Style));
2757 }
2758 
2759 TEST_F(FormatTest, CaseRanges) {
2760   verifyFormat("switch (x) {\n"
2761                "case 'A' ... 'Z':\n"
2762                "case 1 ... 5:\n"
2763                "case a ... b:\n"
2764                "  break;\n"
2765                "}");
2766 }
2767 
2768 TEST_F(FormatTest, ShortEnums) {
2769   FormatStyle Style = getLLVMStyle();
2770   Style.AllowShortEnumsOnASingleLine = true;
2771   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2772   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2773   Style.AllowShortEnumsOnASingleLine = false;
2774   verifyFormat("enum {\n"
2775                "  A,\n"
2776                "  B,\n"
2777                "  C\n"
2778                "} ShortEnum1, ShortEnum2;",
2779                Style);
2780   verifyFormat("typedef enum {\n"
2781                "  A,\n"
2782                "  B,\n"
2783                "  C\n"
2784                "} ShortEnum1, ShortEnum2;",
2785                Style);
2786   verifyFormat("enum {\n"
2787                "  A,\n"
2788                "} ShortEnum1, ShortEnum2;",
2789                Style);
2790   verifyFormat("typedef enum {\n"
2791                "  A,\n"
2792                "} ShortEnum1, ShortEnum2;",
2793                Style);
2794   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2795   Style.BraceWrapping.AfterEnum = true;
2796   verifyFormat("enum\n"
2797                "{\n"
2798                "  A,\n"
2799                "  B,\n"
2800                "  C\n"
2801                "} ShortEnum1, ShortEnum2;",
2802                Style);
2803   verifyFormat("typedef enum\n"
2804                "{\n"
2805                "  A,\n"
2806                "  B,\n"
2807                "  C\n"
2808                "} ShortEnum1, ShortEnum2;",
2809                Style);
2810 }
2811 
2812 TEST_F(FormatTest, ShortCaseLabels) {
2813   FormatStyle Style = getLLVMStyle();
2814   Style.AllowShortCaseLabelsOnASingleLine = true;
2815   verifyFormat("switch (a) {\n"
2816                "case 1: x = 1; break;\n"
2817                "case 2: return;\n"
2818                "case 3:\n"
2819                "case 4:\n"
2820                "case 5: return;\n"
2821                "case 6: // comment\n"
2822                "  return;\n"
2823                "case 7:\n"
2824                "  // comment\n"
2825                "  return;\n"
2826                "case 8:\n"
2827                "  x = 8; // comment\n"
2828                "  break;\n"
2829                "default: y = 1; break;\n"
2830                "}",
2831                Style);
2832   verifyFormat("switch (a) {\n"
2833                "case 0: return; // comment\n"
2834                "case 1: break;  // comment\n"
2835                "case 2: return;\n"
2836                "// comment\n"
2837                "case 3: return;\n"
2838                "// comment 1\n"
2839                "// comment 2\n"
2840                "// comment 3\n"
2841                "case 4: break; /* comment */\n"
2842                "case 5:\n"
2843                "  // comment\n"
2844                "  break;\n"
2845                "case 6: /* comment */ x = 1; break;\n"
2846                "case 7: x = /* comment */ 1; break;\n"
2847                "case 8:\n"
2848                "  x = 1; /* comment */\n"
2849                "  break;\n"
2850                "case 9:\n"
2851                "  break; // comment line 1\n"
2852                "         // comment line 2\n"
2853                "}",
2854                Style);
2855   EXPECT_EQ("switch (a) {\n"
2856             "case 1:\n"
2857             "  x = 8;\n"
2858             "  // fall through\n"
2859             "case 2: x = 8;\n"
2860             "// comment\n"
2861             "case 3:\n"
2862             "  return; /* comment line 1\n"
2863             "           * comment line 2 */\n"
2864             "case 4: i = 8;\n"
2865             "// something else\n"
2866             "#if FOO\n"
2867             "case 5: break;\n"
2868             "#endif\n"
2869             "}",
2870             format("switch (a) {\n"
2871                    "case 1: x = 8;\n"
2872                    "  // fall through\n"
2873                    "case 2:\n"
2874                    "  x = 8;\n"
2875                    "// comment\n"
2876                    "case 3:\n"
2877                    "  return; /* comment line 1\n"
2878                    "           * comment line 2 */\n"
2879                    "case 4:\n"
2880                    "  i = 8;\n"
2881                    "// something else\n"
2882                    "#if FOO\n"
2883                    "case 5: break;\n"
2884                    "#endif\n"
2885                    "}",
2886                    Style));
2887   EXPECT_EQ("switch (a) {\n"
2888             "case 0:\n"
2889             "  return; // long long long long long long long long long long "
2890             "long long comment\n"
2891             "          // line\n"
2892             "}",
2893             format("switch (a) {\n"
2894                    "case 0: return; // long long long long long long long long "
2895                    "long long long long comment line\n"
2896                    "}",
2897                    Style));
2898   EXPECT_EQ("switch (a) {\n"
2899             "case 0:\n"
2900             "  return; /* long long long long long long long long long long "
2901             "long long comment\n"
2902             "             line */\n"
2903             "}",
2904             format("switch (a) {\n"
2905                    "case 0: return; /* long long long long long long long long "
2906                    "long long long long comment line */\n"
2907                    "}",
2908                    Style));
2909   verifyFormat("switch (a) {\n"
2910                "#if FOO\n"
2911                "case 0: return 0;\n"
2912                "#endif\n"
2913                "}",
2914                Style);
2915   verifyFormat("switch (a) {\n"
2916                "case 1: {\n"
2917                "}\n"
2918                "case 2: {\n"
2919                "  return;\n"
2920                "}\n"
2921                "case 3: {\n"
2922                "  x = 1;\n"
2923                "  return;\n"
2924                "}\n"
2925                "case 4:\n"
2926                "  if (x)\n"
2927                "    return;\n"
2928                "}",
2929                Style);
2930   Style.ColumnLimit = 21;
2931   verifyFormat("switch (a) {\n"
2932                "case 1: x = 1; break;\n"
2933                "case 2: return;\n"
2934                "case 3:\n"
2935                "case 4:\n"
2936                "case 5: return;\n"
2937                "default:\n"
2938                "  y = 1;\n"
2939                "  break;\n"
2940                "}",
2941                Style);
2942   Style.ColumnLimit = 80;
2943   Style.AllowShortCaseLabelsOnASingleLine = false;
2944   Style.IndentCaseLabels = true;
2945   EXPECT_EQ("switch (n) {\n"
2946             "  default /*comments*/:\n"
2947             "    return true;\n"
2948             "  case 0:\n"
2949             "    return false;\n"
2950             "}",
2951             format("switch (n) {\n"
2952                    "default/*comments*/:\n"
2953                    "  return true;\n"
2954                    "case 0:\n"
2955                    "  return false;\n"
2956                    "}",
2957                    Style));
2958   Style.AllowShortCaseLabelsOnASingleLine = true;
2959   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2960   Style.BraceWrapping.AfterCaseLabel = true;
2961   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2962   EXPECT_EQ("switch (n)\n"
2963             "{\n"
2964             "  case 0:\n"
2965             "  {\n"
2966             "    return false;\n"
2967             "  }\n"
2968             "  default:\n"
2969             "  {\n"
2970             "    return true;\n"
2971             "  }\n"
2972             "}",
2973             format("switch (n) {\n"
2974                    "  case 0: {\n"
2975                    "    return false;\n"
2976                    "  }\n"
2977                    "  default:\n"
2978                    "  {\n"
2979                    "    return true;\n"
2980                    "  }\n"
2981                    "}",
2982                    Style));
2983 }
2984 
2985 TEST_F(FormatTest, FormatsLabels) {
2986   verifyFormat("void f() {\n"
2987                "  some_code();\n"
2988                "test_label:\n"
2989                "  some_other_code();\n"
2990                "  {\n"
2991                "    some_more_code();\n"
2992                "  another_label:\n"
2993                "    some_more_code();\n"
2994                "  }\n"
2995                "}");
2996   verifyFormat("{\n"
2997                "  some_code();\n"
2998                "test_label:\n"
2999                "  some_other_code();\n"
3000                "}");
3001   verifyFormat("{\n"
3002                "  some_code();\n"
3003                "test_label:;\n"
3004                "  int i = 0;\n"
3005                "}");
3006   FormatStyle Style = getLLVMStyle();
3007   Style.IndentGotoLabels = false;
3008   verifyFormat("void f() {\n"
3009                "  some_code();\n"
3010                "test_label:\n"
3011                "  some_other_code();\n"
3012                "  {\n"
3013                "    some_more_code();\n"
3014                "another_label:\n"
3015                "    some_more_code();\n"
3016                "  }\n"
3017                "}",
3018                Style);
3019   verifyFormat("{\n"
3020                "  some_code();\n"
3021                "test_label:\n"
3022                "  some_other_code();\n"
3023                "}",
3024                Style);
3025   verifyFormat("{\n"
3026                "  some_code();\n"
3027                "test_label:;\n"
3028                "  int i = 0;\n"
3029                "}");
3030 }
3031 
3032 TEST_F(FormatTest, MultiLineControlStatements) {
3033   FormatStyle Style = getLLVMStyleWithColumns(20);
3034   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3035   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3036   // Short lines should keep opening brace on same line.
3037   EXPECT_EQ("if (foo) {\n"
3038             "  bar();\n"
3039             "}",
3040             format("if(foo){bar();}", Style));
3041   EXPECT_EQ("if (foo) {\n"
3042             "  bar();\n"
3043             "} else {\n"
3044             "  baz();\n"
3045             "}",
3046             format("if(foo){bar();}else{baz();}", Style));
3047   EXPECT_EQ("if (foo && bar) {\n"
3048             "  baz();\n"
3049             "}",
3050             format("if(foo&&bar){baz();}", Style));
3051   EXPECT_EQ("if (foo) {\n"
3052             "  bar();\n"
3053             "} else if (baz) {\n"
3054             "  quux();\n"
3055             "}",
3056             format("if(foo){bar();}else if(baz){quux();}", Style));
3057   EXPECT_EQ(
3058       "if (foo) {\n"
3059       "  bar();\n"
3060       "} else if (baz) {\n"
3061       "  quux();\n"
3062       "} else {\n"
3063       "  foobar();\n"
3064       "}",
3065       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
3066   EXPECT_EQ("for (;;) {\n"
3067             "  foo();\n"
3068             "}",
3069             format("for(;;){foo();}"));
3070   EXPECT_EQ("while (1) {\n"
3071             "  foo();\n"
3072             "}",
3073             format("while(1){foo();}", Style));
3074   EXPECT_EQ("switch (foo) {\n"
3075             "case bar:\n"
3076             "  return;\n"
3077             "}",
3078             format("switch(foo){case bar:return;}", Style));
3079   EXPECT_EQ("try {\n"
3080             "  foo();\n"
3081             "} catch (...) {\n"
3082             "  bar();\n"
3083             "}",
3084             format("try{foo();}catch(...){bar();}", Style));
3085   EXPECT_EQ("do {\n"
3086             "  foo();\n"
3087             "} while (bar &&\n"
3088             "         baz);",
3089             format("do{foo();}while(bar&&baz);", Style));
3090   // Long lines should put opening brace on new line.
3091   EXPECT_EQ("if (foo && bar &&\n"
3092             "    baz)\n"
3093             "{\n"
3094             "  quux();\n"
3095             "}",
3096             format("if(foo&&bar&&baz){quux();}", Style));
3097   EXPECT_EQ("if (foo && bar &&\n"
3098             "    baz)\n"
3099             "{\n"
3100             "  quux();\n"
3101             "}",
3102             format("if (foo && bar &&\n"
3103                    "    baz) {\n"
3104                    "  quux();\n"
3105                    "}",
3106                    Style));
3107   EXPECT_EQ("if (foo) {\n"
3108             "  bar();\n"
3109             "} else if (baz ||\n"
3110             "           quux)\n"
3111             "{\n"
3112             "  foobar();\n"
3113             "}",
3114             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
3115   EXPECT_EQ(
3116       "if (foo) {\n"
3117       "  bar();\n"
3118       "} else if (baz ||\n"
3119       "           quux)\n"
3120       "{\n"
3121       "  foobar();\n"
3122       "} else {\n"
3123       "  barbaz();\n"
3124       "}",
3125       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3126              Style));
3127   EXPECT_EQ("for (int i = 0;\n"
3128             "     i < 10; ++i)\n"
3129             "{\n"
3130             "  foo();\n"
3131             "}",
3132             format("for(int i=0;i<10;++i){foo();}", Style));
3133   EXPECT_EQ("foreach (int i,\n"
3134             "         list)\n"
3135             "{\n"
3136             "  foo();\n"
3137             "}",
3138             format("foreach(int i, list){foo();}", Style));
3139   Style.ColumnLimit =
3140       40; // to concentrate at brace wrapping, not line wrap due to column limit
3141   EXPECT_EQ("foreach (int i, list) {\n"
3142             "  foo();\n"
3143             "}",
3144             format("foreach(int i, list){foo();}", Style));
3145   Style.ColumnLimit =
3146       20; // to concentrate at brace wrapping, not line wrap due to column limit
3147   EXPECT_EQ("while (foo || bar ||\n"
3148             "       baz)\n"
3149             "{\n"
3150             "  quux();\n"
3151             "}",
3152             format("while(foo||bar||baz){quux();}", Style));
3153   EXPECT_EQ("switch (\n"
3154             "    foo = barbaz)\n"
3155             "{\n"
3156             "case quux:\n"
3157             "  return;\n"
3158             "}",
3159             format("switch(foo=barbaz){case quux:return;}", Style));
3160   EXPECT_EQ("try {\n"
3161             "  foo();\n"
3162             "} catch (\n"
3163             "    Exception &bar)\n"
3164             "{\n"
3165             "  baz();\n"
3166             "}",
3167             format("try{foo();}catch(Exception&bar){baz();}", Style));
3168   Style.ColumnLimit =
3169       40; // to concentrate at brace wrapping, not line wrap due to column limit
3170   EXPECT_EQ("try {\n"
3171             "  foo();\n"
3172             "} catch (Exception &bar) {\n"
3173             "  baz();\n"
3174             "}",
3175             format("try{foo();}catch(Exception&bar){baz();}", Style));
3176   Style.ColumnLimit =
3177       20; // to concentrate at brace wrapping, not line wrap due to column limit
3178 
3179   Style.BraceWrapping.BeforeElse = true;
3180   EXPECT_EQ(
3181       "if (foo) {\n"
3182       "  bar();\n"
3183       "}\n"
3184       "else if (baz ||\n"
3185       "         quux)\n"
3186       "{\n"
3187       "  foobar();\n"
3188       "}\n"
3189       "else {\n"
3190       "  barbaz();\n"
3191       "}",
3192       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3193              Style));
3194 
3195   Style.BraceWrapping.BeforeCatch = true;
3196   EXPECT_EQ("try {\n"
3197             "  foo();\n"
3198             "}\n"
3199             "catch (...) {\n"
3200             "  baz();\n"
3201             "}",
3202             format("try{foo();}catch(...){baz();}", Style));
3203 
3204   Style.BraceWrapping.AfterFunction = true;
3205   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3206   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
3207   Style.ColumnLimit = 80;
3208   verifyFormat("void shortfunction() { bar(); }", Style);
3209 
3210   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
3211   verifyFormat("void shortfunction()\n"
3212                "{\n"
3213                "  bar();\n"
3214                "}",
3215                Style);
3216 }
3217 
3218 TEST_F(FormatTest, BeforeWhile) {
3219   FormatStyle Style = getLLVMStyle();
3220   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3221 
3222   verifyFormat("do {\n"
3223                "  foo();\n"
3224                "} while (1);",
3225                Style);
3226   Style.BraceWrapping.BeforeWhile = true;
3227   verifyFormat("do {\n"
3228                "  foo();\n"
3229                "}\n"
3230                "while (1);",
3231                Style);
3232 }
3233 
3234 //===----------------------------------------------------------------------===//
3235 // Tests for classes, namespaces, etc.
3236 //===----------------------------------------------------------------------===//
3237 
3238 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3239   verifyFormat("class A {};");
3240 }
3241 
3242 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
3243   verifyFormat("class A {\n"
3244                "public:\n"
3245                "public: // comment\n"
3246                "protected:\n"
3247                "private:\n"
3248                "  void f() {}\n"
3249                "};");
3250   verifyFormat("export class A {\n"
3251                "public:\n"
3252                "public: // comment\n"
3253                "protected:\n"
3254                "private:\n"
3255                "  void f() {}\n"
3256                "};");
3257   verifyGoogleFormat("class A {\n"
3258                      " public:\n"
3259                      " protected:\n"
3260                      " private:\n"
3261                      "  void f() {}\n"
3262                      "};");
3263   verifyGoogleFormat("export class A {\n"
3264                      " public:\n"
3265                      " protected:\n"
3266                      " private:\n"
3267                      "  void f() {}\n"
3268                      "};");
3269   verifyFormat("class A {\n"
3270                "public slots:\n"
3271                "  void f1() {}\n"
3272                "public Q_SLOTS:\n"
3273                "  void f2() {}\n"
3274                "protected slots:\n"
3275                "  void f3() {}\n"
3276                "protected Q_SLOTS:\n"
3277                "  void f4() {}\n"
3278                "private slots:\n"
3279                "  void f5() {}\n"
3280                "private Q_SLOTS:\n"
3281                "  void f6() {}\n"
3282                "signals:\n"
3283                "  void g1();\n"
3284                "Q_SIGNALS:\n"
3285                "  void g2();\n"
3286                "};");
3287 
3288   // Don't interpret 'signals' the wrong way.
3289   verifyFormat("signals.set();");
3290   verifyFormat("for (Signals signals : f()) {\n}");
3291   verifyFormat("{\n"
3292                "  signals.set(); // This needs indentation.\n"
3293                "}");
3294   verifyFormat("void f() {\n"
3295                "label:\n"
3296                "  signals.baz();\n"
3297                "}");
3298   verifyFormat("private[1];");
3299   verifyFormat("testArray[public] = 1;");
3300   verifyFormat("public();");
3301   verifyFormat("myFunc(public);");
3302   verifyFormat("std::vector<int> testVec = {private};");
3303   verifyFormat("private.p = 1;");
3304   verifyFormat("void function(private...){};");
3305   verifyFormat("if (private && public)\n");
3306   verifyFormat("private &= true;");
3307   verifyFormat("int x = private * public;");
3308   verifyFormat("public *= private;");
3309   verifyFormat("int x = public + private;");
3310   verifyFormat("private++;");
3311   verifyFormat("++private;");
3312   verifyFormat("public += private;");
3313   verifyFormat("public = public - private;");
3314   verifyFormat("public->foo();");
3315   verifyFormat("private--;");
3316   verifyFormat("--private;");
3317   verifyFormat("public -= 1;");
3318   verifyFormat("if (!private && !public)\n");
3319   verifyFormat("public != private;");
3320   verifyFormat("int x = public / private;");
3321   verifyFormat("public /= 2;");
3322   verifyFormat("public = public % 2;");
3323   verifyFormat("public %= 2;");
3324   verifyFormat("if (public < private)\n");
3325   verifyFormat("public << private;");
3326   verifyFormat("public <<= private;");
3327   verifyFormat("if (public > private)\n");
3328   verifyFormat("public >> private;");
3329   verifyFormat("public >>= private;");
3330   verifyFormat("public ^ private;");
3331   verifyFormat("public ^= private;");
3332   verifyFormat("public | private;");
3333   verifyFormat("public |= private;");
3334   verifyFormat("auto x = private ? 1 : 2;");
3335   verifyFormat("if (public == private)\n");
3336   verifyFormat("void foo(public, private)");
3337   verifyFormat("public::foo();");
3338 }
3339 
3340 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3341   EXPECT_EQ("class A {\n"
3342             "public:\n"
3343             "  void f();\n"
3344             "\n"
3345             "private:\n"
3346             "  void g() {}\n"
3347             "  // test\n"
3348             "protected:\n"
3349             "  int h;\n"
3350             "};",
3351             format("class A {\n"
3352                    "public:\n"
3353                    "void f();\n"
3354                    "private:\n"
3355                    "void g() {}\n"
3356                    "// test\n"
3357                    "protected:\n"
3358                    "int h;\n"
3359                    "};"));
3360   EXPECT_EQ("class A {\n"
3361             "protected:\n"
3362             "public:\n"
3363             "  void f();\n"
3364             "};",
3365             format("class A {\n"
3366                    "protected:\n"
3367                    "\n"
3368                    "public:\n"
3369                    "\n"
3370                    "  void f();\n"
3371                    "};"));
3372 
3373   // Even ensure proper spacing inside macros.
3374   EXPECT_EQ("#define B     \\\n"
3375             "  class A {   \\\n"
3376             "   protected: \\\n"
3377             "   public:    \\\n"
3378             "    void f(); \\\n"
3379             "  };",
3380             format("#define B     \\\n"
3381                    "  class A {   \\\n"
3382                    "   protected: \\\n"
3383                    "              \\\n"
3384                    "   public:    \\\n"
3385                    "              \\\n"
3386                    "    void f(); \\\n"
3387                    "  };",
3388                    getGoogleStyle()));
3389   // But don't remove empty lines after macros ending in access specifiers.
3390   EXPECT_EQ("#define A private:\n"
3391             "\n"
3392             "int i;",
3393             format("#define A         private:\n"
3394                    "\n"
3395                    "int              i;"));
3396 }
3397 
3398 TEST_F(FormatTest, FormatsClasses) {
3399   verifyFormat("class A : public B {};");
3400   verifyFormat("class A : public ::B {};");
3401 
3402   verifyFormat(
3403       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3404       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3405   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3406                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3407                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3408   verifyFormat(
3409       "class A : public B, public C, public D, public E, public F {};");
3410   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3411                "                     public C,\n"
3412                "                     public D,\n"
3413                "                     public E,\n"
3414                "                     public F,\n"
3415                "                     public G {};");
3416 
3417   verifyFormat("class\n"
3418                "    ReallyReallyLongClassName {\n"
3419                "  int i;\n"
3420                "};",
3421                getLLVMStyleWithColumns(32));
3422   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3423                "                           aaaaaaaaaaaaaaaa> {};");
3424   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3425                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3426                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3427   verifyFormat("template <class R, class C>\n"
3428                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3429                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3430   verifyFormat("class ::A::B {};");
3431 }
3432 
3433 TEST_F(FormatTest, BreakInheritanceStyle) {
3434   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3435   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3436       FormatStyle::BILS_BeforeComma;
3437   verifyFormat("class MyClass : public X {};",
3438                StyleWithInheritanceBreakBeforeComma);
3439   verifyFormat("class MyClass\n"
3440                "    : public X\n"
3441                "    , public Y {};",
3442                StyleWithInheritanceBreakBeforeComma);
3443   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3444                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3445                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3446                StyleWithInheritanceBreakBeforeComma);
3447   verifyFormat("struct aaaaaaaaaaaaa\n"
3448                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3449                "          aaaaaaaaaaaaaaaa> {};",
3450                StyleWithInheritanceBreakBeforeComma);
3451 
3452   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3453   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3454       FormatStyle::BILS_AfterColon;
3455   verifyFormat("class MyClass : public X {};",
3456                StyleWithInheritanceBreakAfterColon);
3457   verifyFormat("class MyClass : public X, public Y {};",
3458                StyleWithInheritanceBreakAfterColon);
3459   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3460                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3461                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3462                StyleWithInheritanceBreakAfterColon);
3463   verifyFormat("struct aaaaaaaaaaaaa :\n"
3464                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3465                "        aaaaaaaaaaaaaaaa> {};",
3466                StyleWithInheritanceBreakAfterColon);
3467 
3468   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3469   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3470       FormatStyle::BILS_AfterComma;
3471   verifyFormat("class MyClass : public X {};",
3472                StyleWithInheritanceBreakAfterComma);
3473   verifyFormat("class MyClass : public X,\n"
3474                "                public Y {};",
3475                StyleWithInheritanceBreakAfterComma);
3476   verifyFormat(
3477       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3478       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3479       "{};",
3480       StyleWithInheritanceBreakAfterComma);
3481   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3482                "                           aaaaaaaaaaaaaaaa> {};",
3483                StyleWithInheritanceBreakAfterComma);
3484   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3485                "    : public OnceBreak,\n"
3486                "      public AlwaysBreak,\n"
3487                "      EvenBasesFitInOneLine {};",
3488                StyleWithInheritanceBreakAfterComma);
3489 }
3490 
3491 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
3492   verifyFormat("class A {\n} a, b;");
3493   verifyFormat("struct A {\n} a, b;");
3494   verifyFormat("union A {\n} a, b;");
3495 
3496   verifyFormat("constexpr class A {\n} a, b;");
3497   verifyFormat("constexpr struct A {\n} a, b;");
3498   verifyFormat("constexpr union A {\n} a, b;");
3499 
3500   verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
3501   verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
3502   verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
3503 
3504   verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
3505   verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
3506   verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
3507 
3508   verifyFormat("namespace ns {\n"
3509                "class {\n"
3510                "} a, b;\n"
3511                "} // namespace ns");
3512   verifyFormat("namespace ns {\n"
3513                "const class {\n"
3514                "} a, b;\n"
3515                "} // namespace ns");
3516   verifyFormat("namespace ns {\n"
3517                "constexpr class C {\n"
3518                "} a, b;\n"
3519                "} // namespace ns");
3520   verifyFormat("namespace ns {\n"
3521                "class { /* comment */\n"
3522                "} a, b;\n"
3523                "} // namespace ns");
3524   verifyFormat("namespace ns {\n"
3525                "const class { /* comment */\n"
3526                "} a, b;\n"
3527                "} // namespace ns");
3528 }
3529 
3530 TEST_F(FormatTest, FormatsEnum) {
3531   verifyFormat("enum {\n"
3532                "  Zero,\n"
3533                "  One = 1,\n"
3534                "  Two = One + 1,\n"
3535                "  Three = (One + Two),\n"
3536                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3537                "  Five = (One, Two, Three, Four, 5)\n"
3538                "};");
3539   verifyGoogleFormat("enum {\n"
3540                      "  Zero,\n"
3541                      "  One = 1,\n"
3542                      "  Two = One + 1,\n"
3543                      "  Three = (One + Two),\n"
3544                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3545                      "  Five = (One, Two, Three, Four, 5)\n"
3546                      "};");
3547   verifyFormat("enum Enum {};");
3548   verifyFormat("enum {};");
3549   verifyFormat("enum X E {} d;");
3550   verifyFormat("enum __attribute__((...)) E {} d;");
3551   verifyFormat("enum __declspec__((...)) E {} d;");
3552   verifyFormat("enum {\n"
3553                "  Bar = Foo<int, int>::value\n"
3554                "};",
3555                getLLVMStyleWithColumns(30));
3556 
3557   verifyFormat("enum ShortEnum { A, B, C };");
3558   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3559 
3560   EXPECT_EQ("enum KeepEmptyLines {\n"
3561             "  ONE,\n"
3562             "\n"
3563             "  TWO,\n"
3564             "\n"
3565             "  THREE\n"
3566             "}",
3567             format("enum KeepEmptyLines {\n"
3568                    "  ONE,\n"
3569                    "\n"
3570                    "  TWO,\n"
3571                    "\n"
3572                    "\n"
3573                    "  THREE\n"
3574                    "}"));
3575   verifyFormat("enum E { // comment\n"
3576                "  ONE,\n"
3577                "  TWO\n"
3578                "};\n"
3579                "int i;");
3580 
3581   FormatStyle EightIndent = getLLVMStyle();
3582   EightIndent.IndentWidth = 8;
3583   verifyFormat("enum {\n"
3584                "        VOID,\n"
3585                "        CHAR,\n"
3586                "        SHORT,\n"
3587                "        INT,\n"
3588                "        LONG,\n"
3589                "        SIGNED,\n"
3590                "        UNSIGNED,\n"
3591                "        BOOL,\n"
3592                "        FLOAT,\n"
3593                "        DOUBLE,\n"
3594                "        COMPLEX\n"
3595                "};",
3596                EightIndent);
3597 
3598   // Not enums.
3599   verifyFormat("enum X f() {\n"
3600                "  a();\n"
3601                "  return 42;\n"
3602                "}");
3603   verifyFormat("enum X Type::f() {\n"
3604                "  a();\n"
3605                "  return 42;\n"
3606                "}");
3607   verifyFormat("enum ::X f() {\n"
3608                "  a();\n"
3609                "  return 42;\n"
3610                "}");
3611   verifyFormat("enum ns::X f() {\n"
3612                "  a();\n"
3613                "  return 42;\n"
3614                "}");
3615 }
3616 
3617 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3618   verifyFormat("enum Type {\n"
3619                "  One = 0; // These semicolons should be commas.\n"
3620                "  Two = 1;\n"
3621                "};");
3622   verifyFormat("namespace n {\n"
3623                "enum Type {\n"
3624                "  One,\n"
3625                "  Two, // missing };\n"
3626                "  int i;\n"
3627                "}\n"
3628                "void g() {}");
3629 }
3630 
3631 TEST_F(FormatTest, FormatsEnumStruct) {
3632   verifyFormat("enum struct {\n"
3633                "  Zero,\n"
3634                "  One = 1,\n"
3635                "  Two = One + 1,\n"
3636                "  Three = (One + Two),\n"
3637                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3638                "  Five = (One, Two, Three, Four, 5)\n"
3639                "};");
3640   verifyFormat("enum struct Enum {};");
3641   verifyFormat("enum struct {};");
3642   verifyFormat("enum struct X E {} d;");
3643   verifyFormat("enum struct __attribute__((...)) E {} d;");
3644   verifyFormat("enum struct __declspec__((...)) E {} d;");
3645   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3646 }
3647 
3648 TEST_F(FormatTest, FormatsEnumClass) {
3649   verifyFormat("enum class {\n"
3650                "  Zero,\n"
3651                "  One = 1,\n"
3652                "  Two = One + 1,\n"
3653                "  Three = (One + Two),\n"
3654                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3655                "  Five = (One, Two, Three, Four, 5)\n"
3656                "};");
3657   verifyFormat("enum class Enum {};");
3658   verifyFormat("enum class {};");
3659   verifyFormat("enum class X E {} d;");
3660   verifyFormat("enum class __attribute__((...)) E {} d;");
3661   verifyFormat("enum class __declspec__((...)) E {} d;");
3662   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3663 }
3664 
3665 TEST_F(FormatTest, FormatsEnumTypes) {
3666   verifyFormat("enum X : int {\n"
3667                "  A, // Force multiple lines.\n"
3668                "  B\n"
3669                "};");
3670   verifyFormat("enum X : int { A, B };");
3671   verifyFormat("enum X : std::uint32_t { A, B };");
3672 }
3673 
3674 TEST_F(FormatTest, FormatsTypedefEnum) {
3675   FormatStyle Style = getLLVMStyleWithColumns(40);
3676   verifyFormat("typedef enum {} EmptyEnum;");
3677   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3678   verifyFormat("typedef enum {\n"
3679                "  ZERO = 0,\n"
3680                "  ONE = 1,\n"
3681                "  TWO = 2,\n"
3682                "  THREE = 3\n"
3683                "} LongEnum;",
3684                Style);
3685   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3686   Style.BraceWrapping.AfterEnum = true;
3687   verifyFormat("typedef enum {} EmptyEnum;");
3688   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3689   verifyFormat("typedef enum\n"
3690                "{\n"
3691                "  ZERO = 0,\n"
3692                "  ONE = 1,\n"
3693                "  TWO = 2,\n"
3694                "  THREE = 3\n"
3695                "} LongEnum;",
3696                Style);
3697 }
3698 
3699 TEST_F(FormatTest, FormatsNSEnums) {
3700   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3701   verifyGoogleFormat(
3702       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3703   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3704                      "  // Information about someDecentlyLongValue.\n"
3705                      "  someDecentlyLongValue,\n"
3706                      "  // Information about anotherDecentlyLongValue.\n"
3707                      "  anotherDecentlyLongValue,\n"
3708                      "  // Information about aThirdDecentlyLongValue.\n"
3709                      "  aThirdDecentlyLongValue\n"
3710                      "};");
3711   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3712                      "  // Information about someDecentlyLongValue.\n"
3713                      "  someDecentlyLongValue,\n"
3714                      "  // Information about anotherDecentlyLongValue.\n"
3715                      "  anotherDecentlyLongValue,\n"
3716                      "  // Information about aThirdDecentlyLongValue.\n"
3717                      "  aThirdDecentlyLongValue\n"
3718                      "};");
3719   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3720                      "  a = 1,\n"
3721                      "  b = 2,\n"
3722                      "  c = 3,\n"
3723                      "};");
3724   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3725                      "  a = 1,\n"
3726                      "  b = 2,\n"
3727                      "  c = 3,\n"
3728                      "};");
3729   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3730                      "  a = 1,\n"
3731                      "  b = 2,\n"
3732                      "  c = 3,\n"
3733                      "};");
3734   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3735                      "  a = 1,\n"
3736                      "  b = 2,\n"
3737                      "  c = 3,\n"
3738                      "};");
3739 }
3740 
3741 TEST_F(FormatTest, FormatsBitfields) {
3742   verifyFormat("struct Bitfields {\n"
3743                "  unsigned sClass : 8;\n"
3744                "  unsigned ValueKind : 2;\n"
3745                "};");
3746   verifyFormat("struct A {\n"
3747                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3748                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3749                "};");
3750   verifyFormat("struct MyStruct {\n"
3751                "  uchar data;\n"
3752                "  uchar : 8;\n"
3753                "  uchar : 8;\n"
3754                "  uchar other;\n"
3755                "};");
3756   FormatStyle Style = getLLVMStyle();
3757   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3758   verifyFormat("struct Bitfields {\n"
3759                "  unsigned sClass:8;\n"
3760                "  unsigned ValueKind:2;\n"
3761                "  uchar other;\n"
3762                "};",
3763                Style);
3764   verifyFormat("struct A {\n"
3765                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3766                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3767                "};",
3768                Style);
3769   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3770   verifyFormat("struct Bitfields {\n"
3771                "  unsigned sClass :8;\n"
3772                "  unsigned ValueKind :2;\n"
3773                "  uchar other;\n"
3774                "};",
3775                Style);
3776   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3777   verifyFormat("struct Bitfields {\n"
3778                "  unsigned sClass: 8;\n"
3779                "  unsigned ValueKind: 2;\n"
3780                "  uchar other;\n"
3781                "};",
3782                Style);
3783 }
3784 
3785 TEST_F(FormatTest, FormatsNamespaces) {
3786   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3787   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3788 
3789   verifyFormat("namespace some_namespace {\n"
3790                "class A {};\n"
3791                "void f() { f(); }\n"
3792                "}",
3793                LLVMWithNoNamespaceFix);
3794   verifyFormat("#define M(x) x##x\n"
3795                "namespace M(x) {\n"
3796                "class A {};\n"
3797                "void f() { f(); }\n"
3798                "}",
3799                LLVMWithNoNamespaceFix);
3800   verifyFormat("#define M(x) x##x\n"
3801                "namespace N::inline M(x) {\n"
3802                "class A {};\n"
3803                "void f() { f(); }\n"
3804                "}",
3805                LLVMWithNoNamespaceFix);
3806   verifyFormat("#define M(x) x##x\n"
3807                "namespace M(x)::inline N {\n"
3808                "class A {};\n"
3809                "void f() { f(); }\n"
3810                "}",
3811                LLVMWithNoNamespaceFix);
3812   verifyFormat("#define M(x) x##x\n"
3813                "namespace N::M(x) {\n"
3814                "class A {};\n"
3815                "void f() { f(); }\n"
3816                "}",
3817                LLVMWithNoNamespaceFix);
3818   verifyFormat("#define M(x) x##x\n"
3819                "namespace M::N(x) {\n"
3820                "class A {};\n"
3821                "void f() { f(); }\n"
3822                "}",
3823                LLVMWithNoNamespaceFix);
3824   verifyFormat("namespace N::inline D {\n"
3825                "class A {};\n"
3826                "void f() { f(); }\n"
3827                "}",
3828                LLVMWithNoNamespaceFix);
3829   verifyFormat("namespace N::inline D::E {\n"
3830                "class A {};\n"
3831                "void f() { f(); }\n"
3832                "}",
3833                LLVMWithNoNamespaceFix);
3834   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3835                "class A {};\n"
3836                "void f() { f(); }\n"
3837                "}",
3838                LLVMWithNoNamespaceFix);
3839   verifyFormat("/* something */ namespace some_namespace {\n"
3840                "class A {};\n"
3841                "void f() { f(); }\n"
3842                "}",
3843                LLVMWithNoNamespaceFix);
3844   verifyFormat("namespace {\n"
3845                "class A {};\n"
3846                "void f() { f(); }\n"
3847                "}",
3848                LLVMWithNoNamespaceFix);
3849   verifyFormat("/* something */ namespace {\n"
3850                "class A {};\n"
3851                "void f() { f(); }\n"
3852                "}",
3853                LLVMWithNoNamespaceFix);
3854   verifyFormat("inline namespace X {\n"
3855                "class A {};\n"
3856                "void f() { f(); }\n"
3857                "}",
3858                LLVMWithNoNamespaceFix);
3859   verifyFormat("/* something */ inline namespace X {\n"
3860                "class A {};\n"
3861                "void f() { f(); }\n"
3862                "}",
3863                LLVMWithNoNamespaceFix);
3864   verifyFormat("export namespace X {\n"
3865                "class A {};\n"
3866                "void f() { f(); }\n"
3867                "}",
3868                LLVMWithNoNamespaceFix);
3869   verifyFormat("using namespace some_namespace;\n"
3870                "class A {};\n"
3871                "void f() { f(); }",
3872                LLVMWithNoNamespaceFix);
3873 
3874   // This code is more common than we thought; if we
3875   // layout this correctly the semicolon will go into
3876   // its own line, which is undesirable.
3877   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3878   verifyFormat("namespace {\n"
3879                "class A {};\n"
3880                "};",
3881                LLVMWithNoNamespaceFix);
3882 
3883   verifyFormat("namespace {\n"
3884                "int SomeVariable = 0; // comment\n"
3885                "} // namespace",
3886                LLVMWithNoNamespaceFix);
3887   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3888             "#define HEADER_GUARD\n"
3889             "namespace my_namespace {\n"
3890             "int i;\n"
3891             "} // my_namespace\n"
3892             "#endif // HEADER_GUARD",
3893             format("#ifndef HEADER_GUARD\n"
3894                    " #define HEADER_GUARD\n"
3895                    "   namespace my_namespace {\n"
3896                    "int i;\n"
3897                    "}    // my_namespace\n"
3898                    "#endif    // HEADER_GUARD",
3899                    LLVMWithNoNamespaceFix));
3900 
3901   EXPECT_EQ("namespace A::B {\n"
3902             "class C {};\n"
3903             "}",
3904             format("namespace A::B {\n"
3905                    "class C {};\n"
3906                    "}",
3907                    LLVMWithNoNamespaceFix));
3908 
3909   FormatStyle Style = getLLVMStyle();
3910   Style.NamespaceIndentation = FormatStyle::NI_All;
3911   EXPECT_EQ("namespace out {\n"
3912             "  int i;\n"
3913             "  namespace in {\n"
3914             "    int i;\n"
3915             "  } // namespace in\n"
3916             "} // namespace out",
3917             format("namespace out {\n"
3918                    "int i;\n"
3919                    "namespace in {\n"
3920                    "int i;\n"
3921                    "} // namespace in\n"
3922                    "} // namespace out",
3923                    Style));
3924 
3925   FormatStyle ShortInlineFunctions = getLLVMStyle();
3926   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3927   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3928       FormatStyle::SFS_Inline;
3929   verifyFormat("namespace {\n"
3930                "  void f() {\n"
3931                "    return;\n"
3932                "  }\n"
3933                "} // namespace\n",
3934                ShortInlineFunctions);
3935   verifyFormat("namespace { /* comment */\n"
3936                "  void f() {\n"
3937                "    return;\n"
3938                "  }\n"
3939                "} // namespace\n",
3940                ShortInlineFunctions);
3941   verifyFormat("namespace { // comment\n"
3942                "  void f() {\n"
3943                "    return;\n"
3944                "  }\n"
3945                "} // namespace\n",
3946                ShortInlineFunctions);
3947   verifyFormat("namespace {\n"
3948                "  int some_int;\n"
3949                "  void f() {\n"
3950                "    return;\n"
3951                "  }\n"
3952                "} // namespace\n",
3953                ShortInlineFunctions);
3954   verifyFormat("namespace interface {\n"
3955                "  void f() {\n"
3956                "    return;\n"
3957                "  }\n"
3958                "} // namespace interface\n",
3959                ShortInlineFunctions);
3960   verifyFormat("namespace {\n"
3961                "  class X {\n"
3962                "    void f() { return; }\n"
3963                "  };\n"
3964                "} // namespace\n",
3965                ShortInlineFunctions);
3966   verifyFormat("namespace {\n"
3967                "  class X { /* comment */\n"
3968                "    void f() { return; }\n"
3969                "  };\n"
3970                "} // namespace\n",
3971                ShortInlineFunctions);
3972   verifyFormat("namespace {\n"
3973                "  class X { // comment\n"
3974                "    void f() { return; }\n"
3975                "  };\n"
3976                "} // namespace\n",
3977                ShortInlineFunctions);
3978   verifyFormat("namespace {\n"
3979                "  struct X {\n"
3980                "    void f() { return; }\n"
3981                "  };\n"
3982                "} // namespace\n",
3983                ShortInlineFunctions);
3984   verifyFormat("namespace {\n"
3985                "  union X {\n"
3986                "    void f() { return; }\n"
3987                "  };\n"
3988                "} // namespace\n",
3989                ShortInlineFunctions);
3990   verifyFormat("extern \"C\" {\n"
3991                "void f() {\n"
3992                "  return;\n"
3993                "}\n"
3994                "} // namespace\n",
3995                ShortInlineFunctions);
3996   verifyFormat("namespace {\n"
3997                "  class X {\n"
3998                "    void f() { return; }\n"
3999                "  } x;\n"
4000                "} // namespace\n",
4001                ShortInlineFunctions);
4002   verifyFormat("namespace {\n"
4003                "  [[nodiscard]] class X {\n"
4004                "    void f() { return; }\n"
4005                "  };\n"
4006                "} // namespace\n",
4007                ShortInlineFunctions);
4008   verifyFormat("namespace {\n"
4009                "  static class X {\n"
4010                "    void f() { return; }\n"
4011                "  } x;\n"
4012                "} // namespace\n",
4013                ShortInlineFunctions);
4014   verifyFormat("namespace {\n"
4015                "  constexpr class X {\n"
4016                "    void f() { return; }\n"
4017                "  } x;\n"
4018                "} // namespace\n",
4019                ShortInlineFunctions);
4020 
4021   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
4022   verifyFormat("extern \"C\" {\n"
4023                "  void f() {\n"
4024                "    return;\n"
4025                "  }\n"
4026                "} // namespace\n",
4027                ShortInlineFunctions);
4028 
4029   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4030   EXPECT_EQ("namespace out {\n"
4031             "int i;\n"
4032             "namespace in {\n"
4033             "  int i;\n"
4034             "} // namespace in\n"
4035             "} // namespace out",
4036             format("namespace out {\n"
4037                    "int i;\n"
4038                    "namespace in {\n"
4039                    "int i;\n"
4040                    "} // namespace in\n"
4041                    "} // namespace out",
4042                    Style));
4043 
4044   Style.NamespaceIndentation = FormatStyle::NI_None;
4045   verifyFormat("template <class T>\n"
4046                "concept a_concept = X<>;\n"
4047                "namespace B {\n"
4048                "struct b_struct {};\n"
4049                "} // namespace B\n",
4050                Style);
4051   verifyFormat("template <int I>\n"
4052                "constexpr void foo()\n"
4053                "  requires(I == 42)\n"
4054                "{}\n"
4055                "namespace ns {\n"
4056                "void foo() {}\n"
4057                "} // namespace ns\n",
4058                Style);
4059 }
4060 
4061 TEST_F(FormatTest, NamespaceMacros) {
4062   FormatStyle Style = getLLVMStyle();
4063   Style.NamespaceMacros.push_back("TESTSUITE");
4064 
4065   verifyFormat("TESTSUITE(A) {\n"
4066                "int foo();\n"
4067                "} // TESTSUITE(A)",
4068                Style);
4069 
4070   verifyFormat("TESTSUITE(A, B) {\n"
4071                "int foo();\n"
4072                "} // TESTSUITE(A)",
4073                Style);
4074 
4075   // Properly indent according to NamespaceIndentation style
4076   Style.NamespaceIndentation = FormatStyle::NI_All;
4077   verifyFormat("TESTSUITE(A) {\n"
4078                "  int foo();\n"
4079                "} // TESTSUITE(A)",
4080                Style);
4081   verifyFormat("TESTSUITE(A) {\n"
4082                "  namespace B {\n"
4083                "    int foo();\n"
4084                "  } // namespace B\n"
4085                "} // TESTSUITE(A)",
4086                Style);
4087   verifyFormat("namespace A {\n"
4088                "  TESTSUITE(B) {\n"
4089                "    int foo();\n"
4090                "  } // TESTSUITE(B)\n"
4091                "} // namespace A",
4092                Style);
4093 
4094   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4095   verifyFormat("TESTSUITE(A) {\n"
4096                "TESTSUITE(B) {\n"
4097                "  int foo();\n"
4098                "} // TESTSUITE(B)\n"
4099                "} // TESTSUITE(A)",
4100                Style);
4101   verifyFormat("TESTSUITE(A) {\n"
4102                "namespace B {\n"
4103                "  int foo();\n"
4104                "} // namespace B\n"
4105                "} // TESTSUITE(A)",
4106                Style);
4107   verifyFormat("namespace A {\n"
4108                "TESTSUITE(B) {\n"
4109                "  int foo();\n"
4110                "} // TESTSUITE(B)\n"
4111                "} // namespace A",
4112                Style);
4113 
4114   // Properly merge namespace-macros blocks in CompactNamespaces mode
4115   Style.NamespaceIndentation = FormatStyle::NI_None;
4116   Style.CompactNamespaces = true;
4117   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
4118                "}} // TESTSUITE(A::B)",
4119                Style);
4120 
4121   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4122             "}} // TESTSUITE(out::in)",
4123             format("TESTSUITE(out) {\n"
4124                    "TESTSUITE(in) {\n"
4125                    "} // TESTSUITE(in)\n"
4126                    "} // TESTSUITE(out)",
4127                    Style));
4128 
4129   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4130             "}} // TESTSUITE(out::in)",
4131             format("TESTSUITE(out) {\n"
4132                    "TESTSUITE(in) {\n"
4133                    "} // TESTSUITE(in)\n"
4134                    "} // TESTSUITE(out)",
4135                    Style));
4136 
4137   // Do not merge different namespaces/macros
4138   EXPECT_EQ("namespace out {\n"
4139             "TESTSUITE(in) {\n"
4140             "} // TESTSUITE(in)\n"
4141             "} // namespace out",
4142             format("namespace out {\n"
4143                    "TESTSUITE(in) {\n"
4144                    "} // TESTSUITE(in)\n"
4145                    "} // namespace out",
4146                    Style));
4147   EXPECT_EQ("TESTSUITE(out) {\n"
4148             "namespace in {\n"
4149             "} // namespace in\n"
4150             "} // TESTSUITE(out)",
4151             format("TESTSUITE(out) {\n"
4152                    "namespace in {\n"
4153                    "} // namespace in\n"
4154                    "} // TESTSUITE(out)",
4155                    Style));
4156   Style.NamespaceMacros.push_back("FOOBAR");
4157   EXPECT_EQ("TESTSUITE(out) {\n"
4158             "FOOBAR(in) {\n"
4159             "} // FOOBAR(in)\n"
4160             "} // TESTSUITE(out)",
4161             format("TESTSUITE(out) {\n"
4162                    "FOOBAR(in) {\n"
4163                    "} // FOOBAR(in)\n"
4164                    "} // TESTSUITE(out)",
4165                    Style));
4166 }
4167 
4168 TEST_F(FormatTest, FormatsCompactNamespaces) {
4169   FormatStyle Style = getLLVMStyle();
4170   Style.CompactNamespaces = true;
4171   Style.NamespaceMacros.push_back("TESTSUITE");
4172 
4173   verifyFormat("namespace A { namespace B {\n"
4174                "}} // namespace A::B",
4175                Style);
4176 
4177   EXPECT_EQ("namespace out { namespace in {\n"
4178             "}} // namespace out::in",
4179             format("namespace out {\n"
4180                    "namespace in {\n"
4181                    "} // namespace in\n"
4182                    "} // namespace out",
4183                    Style));
4184 
4185   // Only namespaces which have both consecutive opening and end get compacted
4186   EXPECT_EQ("namespace out {\n"
4187             "namespace in1 {\n"
4188             "} // namespace in1\n"
4189             "namespace in2 {\n"
4190             "} // namespace in2\n"
4191             "} // namespace out",
4192             format("namespace out {\n"
4193                    "namespace in1 {\n"
4194                    "} // namespace in1\n"
4195                    "namespace in2 {\n"
4196                    "} // namespace in2\n"
4197                    "} // namespace out",
4198                    Style));
4199 
4200   EXPECT_EQ("namespace out {\n"
4201             "int i;\n"
4202             "namespace in {\n"
4203             "int j;\n"
4204             "} // namespace in\n"
4205             "int k;\n"
4206             "} // namespace out",
4207             format("namespace out { int i;\n"
4208                    "namespace in { int j; } // namespace in\n"
4209                    "int k; } // namespace out",
4210                    Style));
4211 
4212   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
4213             "}}} // namespace A::B::C\n",
4214             format("namespace A { namespace B {\n"
4215                    "namespace C {\n"
4216                    "}} // namespace B::C\n"
4217                    "} // namespace A\n",
4218                    Style));
4219 
4220   Style.ColumnLimit = 40;
4221   EXPECT_EQ("namespace aaaaaaaaaa {\n"
4222             "namespace bbbbbbbbbb {\n"
4223             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
4224             format("namespace aaaaaaaaaa {\n"
4225                    "namespace bbbbbbbbbb {\n"
4226                    "} // namespace bbbbbbbbbb\n"
4227                    "} // namespace aaaaaaaaaa",
4228                    Style));
4229 
4230   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
4231             "namespace cccccc {\n"
4232             "}}} // namespace aaaaaa::bbbbbb::cccccc",
4233             format("namespace aaaaaa {\n"
4234                    "namespace bbbbbb {\n"
4235                    "namespace cccccc {\n"
4236                    "} // namespace cccccc\n"
4237                    "} // namespace bbbbbb\n"
4238                    "} // namespace aaaaaa",
4239                    Style));
4240   Style.ColumnLimit = 80;
4241 
4242   // Extra semicolon after 'inner' closing brace prevents merging
4243   EXPECT_EQ("namespace out { namespace in {\n"
4244             "}; } // namespace out::in",
4245             format("namespace out {\n"
4246                    "namespace in {\n"
4247                    "}; // namespace in\n"
4248                    "} // namespace out",
4249                    Style));
4250 
4251   // Extra semicolon after 'outer' closing brace is conserved
4252   EXPECT_EQ("namespace out { namespace in {\n"
4253             "}}; // namespace out::in",
4254             format("namespace out {\n"
4255                    "namespace in {\n"
4256                    "} // namespace in\n"
4257                    "}; // namespace out",
4258                    Style));
4259 
4260   Style.NamespaceIndentation = FormatStyle::NI_All;
4261   EXPECT_EQ("namespace out { namespace in {\n"
4262             "  int i;\n"
4263             "}} // namespace out::in",
4264             format("namespace out {\n"
4265                    "namespace in {\n"
4266                    "int i;\n"
4267                    "} // namespace in\n"
4268                    "} // namespace out",
4269                    Style));
4270   EXPECT_EQ("namespace out { namespace mid {\n"
4271             "  namespace in {\n"
4272             "    int j;\n"
4273             "  } // namespace in\n"
4274             "  int k;\n"
4275             "}} // namespace out::mid",
4276             format("namespace out { namespace mid {\n"
4277                    "namespace in { int j; } // namespace in\n"
4278                    "int k; }} // namespace out::mid",
4279                    Style));
4280 
4281   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4282   EXPECT_EQ("namespace out { namespace in {\n"
4283             "  int i;\n"
4284             "}} // namespace out::in",
4285             format("namespace out {\n"
4286                    "namespace in {\n"
4287                    "int i;\n"
4288                    "} // namespace in\n"
4289                    "} // namespace out",
4290                    Style));
4291   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
4292             "  int i;\n"
4293             "}}} // namespace out::mid::in",
4294             format("namespace out {\n"
4295                    "namespace mid {\n"
4296                    "namespace in {\n"
4297                    "int i;\n"
4298                    "} // namespace in\n"
4299                    "} // namespace mid\n"
4300                    "} // namespace out",
4301                    Style));
4302 
4303   Style.CompactNamespaces = true;
4304   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4305   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4306   Style.BraceWrapping.BeforeLambdaBody = true;
4307   verifyFormat("namespace out { namespace in {\n"
4308                "}} // namespace out::in",
4309                Style);
4310   EXPECT_EQ("namespace out { namespace in {\n"
4311             "}} // namespace out::in",
4312             format("namespace out {\n"
4313                    "namespace in {\n"
4314                    "} // namespace in\n"
4315                    "} // namespace out",
4316                    Style));
4317 }
4318 
4319 TEST_F(FormatTest, FormatsExternC) {
4320   verifyFormat("extern \"C\" {\nint a;");
4321   verifyFormat("extern \"C\" {}");
4322   verifyFormat("extern \"C\" {\n"
4323                "int foo();\n"
4324                "}");
4325   verifyFormat("extern \"C\" int foo() {}");
4326   verifyFormat("extern \"C\" int foo();");
4327   verifyFormat("extern \"C\" int foo() {\n"
4328                "  int i = 42;\n"
4329                "  return i;\n"
4330                "}");
4331 
4332   FormatStyle Style = getLLVMStyle();
4333   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4334   Style.BraceWrapping.AfterFunction = true;
4335   verifyFormat("extern \"C\" int foo() {}", Style);
4336   verifyFormat("extern \"C\" int foo();", Style);
4337   verifyFormat("extern \"C\" int foo()\n"
4338                "{\n"
4339                "  int i = 42;\n"
4340                "  return i;\n"
4341                "}",
4342                Style);
4343 
4344   Style.BraceWrapping.AfterExternBlock = true;
4345   Style.BraceWrapping.SplitEmptyRecord = false;
4346   verifyFormat("extern \"C\"\n"
4347                "{}",
4348                Style);
4349   verifyFormat("extern \"C\"\n"
4350                "{\n"
4351                "  int foo();\n"
4352                "}",
4353                Style);
4354 }
4355 
4356 TEST_F(FormatTest, IndentExternBlockStyle) {
4357   FormatStyle Style = getLLVMStyle();
4358   Style.IndentWidth = 2;
4359 
4360   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4361   verifyFormat("extern \"C\" { /*9*/\n"
4362                "}",
4363                Style);
4364   verifyFormat("extern \"C\" {\n"
4365                "  int foo10();\n"
4366                "}",
4367                Style);
4368 
4369   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4370   verifyFormat("extern \"C\" { /*11*/\n"
4371                "}",
4372                Style);
4373   verifyFormat("extern \"C\" {\n"
4374                "int foo12();\n"
4375                "}",
4376                Style);
4377 
4378   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4379   Style.BraceWrapping.AfterExternBlock = true;
4380   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4381   verifyFormat("extern \"C\"\n"
4382                "{ /*13*/\n"
4383                "}",
4384                Style);
4385   verifyFormat("extern \"C\"\n{\n"
4386                "  int foo14();\n"
4387                "}",
4388                Style);
4389 
4390   Style.BraceWrapping.AfterExternBlock = false;
4391   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4392   verifyFormat("extern \"C\" { /*15*/\n"
4393                "}",
4394                Style);
4395   verifyFormat("extern \"C\" {\n"
4396                "int foo16();\n"
4397                "}",
4398                Style);
4399 
4400   Style.BraceWrapping.AfterExternBlock = true;
4401   verifyFormat("extern \"C\"\n"
4402                "{ /*13*/\n"
4403                "}",
4404                Style);
4405   verifyFormat("extern \"C\"\n"
4406                "{\n"
4407                "int foo14();\n"
4408                "}",
4409                Style);
4410 
4411   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4412   verifyFormat("extern \"C\"\n"
4413                "{ /*13*/\n"
4414                "}",
4415                Style);
4416   verifyFormat("extern \"C\"\n"
4417                "{\n"
4418                "  int foo14();\n"
4419                "}",
4420                Style);
4421 }
4422 
4423 TEST_F(FormatTest, FormatsInlineASM) {
4424   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4425   verifyFormat("asm(\"nop\" ::: \"memory\");");
4426   verifyFormat(
4427       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4428       "    \"cpuid\\n\\t\"\n"
4429       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4430       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4431       "    : \"a\"(value));");
4432   EXPECT_EQ(
4433       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4434       "  __asm {\n"
4435       "        mov     edx,[that] // vtable in edx\n"
4436       "        mov     eax,methodIndex\n"
4437       "        call    [edx][eax*4] // stdcall\n"
4438       "  }\n"
4439       "}",
4440       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4441              "    __asm {\n"
4442              "        mov     edx,[that] // vtable in edx\n"
4443              "        mov     eax,methodIndex\n"
4444              "        call    [edx][eax*4] // stdcall\n"
4445              "    }\n"
4446              "}"));
4447   EXPECT_EQ("_asm {\n"
4448             "  xor eax, eax;\n"
4449             "  cpuid;\n"
4450             "}",
4451             format("_asm {\n"
4452                    "  xor eax, eax;\n"
4453                    "  cpuid;\n"
4454                    "}"));
4455   verifyFormat("void function() {\n"
4456                "  // comment\n"
4457                "  asm(\"\");\n"
4458                "}");
4459   EXPECT_EQ("__asm {\n"
4460             "}\n"
4461             "int i;",
4462             format("__asm   {\n"
4463                    "}\n"
4464                    "int   i;"));
4465 }
4466 
4467 TEST_F(FormatTest, FormatTryCatch) {
4468   verifyFormat("try {\n"
4469                "  throw a * b;\n"
4470                "} catch (int a) {\n"
4471                "  // Do nothing.\n"
4472                "} catch (...) {\n"
4473                "  exit(42);\n"
4474                "}");
4475 
4476   // Function-level try statements.
4477   verifyFormat("int f() try { return 4; } catch (...) {\n"
4478                "  return 5;\n"
4479                "}");
4480   verifyFormat("class A {\n"
4481                "  int a;\n"
4482                "  A() try : a(0) {\n"
4483                "  } catch (...) {\n"
4484                "    throw;\n"
4485                "  }\n"
4486                "};\n");
4487   verifyFormat("class A {\n"
4488                "  int a;\n"
4489                "  A() try : a(0), b{1} {\n"
4490                "  } catch (...) {\n"
4491                "    throw;\n"
4492                "  }\n"
4493                "};\n");
4494   verifyFormat("class A {\n"
4495                "  int a;\n"
4496                "  A() try : a(0), b{1}, c{2} {\n"
4497                "  } catch (...) {\n"
4498                "    throw;\n"
4499                "  }\n"
4500                "};\n");
4501   verifyFormat("class A {\n"
4502                "  int a;\n"
4503                "  A() try : a(0), b{1}, c{2} {\n"
4504                "    { // New scope.\n"
4505                "    }\n"
4506                "  } catch (...) {\n"
4507                "    throw;\n"
4508                "  }\n"
4509                "};\n");
4510 
4511   // Incomplete try-catch blocks.
4512   verifyIncompleteFormat("try {} catch (");
4513 }
4514 
4515 TEST_F(FormatTest, FormatTryAsAVariable) {
4516   verifyFormat("int try;");
4517   verifyFormat("int try, size;");
4518   verifyFormat("try = foo();");
4519   verifyFormat("if (try < size) {\n  return true;\n}");
4520 
4521   verifyFormat("int catch;");
4522   verifyFormat("int catch, size;");
4523   verifyFormat("catch = foo();");
4524   verifyFormat("if (catch < size) {\n  return true;\n}");
4525 
4526   FormatStyle Style = getLLVMStyle();
4527   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4528   Style.BraceWrapping.AfterFunction = true;
4529   Style.BraceWrapping.BeforeCatch = true;
4530   verifyFormat("try {\n"
4531                "  int bar = 1;\n"
4532                "}\n"
4533                "catch (...) {\n"
4534                "  int bar = 1;\n"
4535                "}",
4536                Style);
4537   verifyFormat("#if NO_EX\n"
4538                "try\n"
4539                "#endif\n"
4540                "{\n"
4541                "}\n"
4542                "#if NO_EX\n"
4543                "catch (...) {\n"
4544                "}",
4545                Style);
4546   verifyFormat("try /* abc */ {\n"
4547                "  int bar = 1;\n"
4548                "}\n"
4549                "catch (...) {\n"
4550                "  int bar = 1;\n"
4551                "}",
4552                Style);
4553   verifyFormat("try\n"
4554                "// abc\n"
4555                "{\n"
4556                "  int bar = 1;\n"
4557                "}\n"
4558                "catch (...) {\n"
4559                "  int bar = 1;\n"
4560                "}",
4561                Style);
4562 }
4563 
4564 TEST_F(FormatTest, FormatSEHTryCatch) {
4565   verifyFormat("__try {\n"
4566                "  int a = b * c;\n"
4567                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4568                "  // Do nothing.\n"
4569                "}");
4570 
4571   verifyFormat("__try {\n"
4572                "  int a = b * c;\n"
4573                "} __finally {\n"
4574                "  // Do nothing.\n"
4575                "}");
4576 
4577   verifyFormat("DEBUG({\n"
4578                "  __try {\n"
4579                "  } __finally {\n"
4580                "  }\n"
4581                "});\n");
4582 }
4583 
4584 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4585   verifyFormat("try {\n"
4586                "  f();\n"
4587                "} catch {\n"
4588                "  g();\n"
4589                "}");
4590   verifyFormat("try {\n"
4591                "  f();\n"
4592                "} catch (A a) MACRO(x) {\n"
4593                "  g();\n"
4594                "} catch (B b) MACRO(x) {\n"
4595                "  g();\n"
4596                "}");
4597 }
4598 
4599 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4600   FormatStyle Style = getLLVMStyle();
4601   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4602                           FormatStyle::BS_WebKit}) {
4603     Style.BreakBeforeBraces = BraceStyle;
4604     verifyFormat("try {\n"
4605                  "  // something\n"
4606                  "} catch (...) {\n"
4607                  "  // something\n"
4608                  "}",
4609                  Style);
4610   }
4611   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4612   verifyFormat("try {\n"
4613                "  // something\n"
4614                "}\n"
4615                "catch (...) {\n"
4616                "  // something\n"
4617                "}",
4618                Style);
4619   verifyFormat("__try {\n"
4620                "  // something\n"
4621                "}\n"
4622                "__finally {\n"
4623                "  // something\n"
4624                "}",
4625                Style);
4626   verifyFormat("@try {\n"
4627                "  // something\n"
4628                "}\n"
4629                "@finally {\n"
4630                "  // something\n"
4631                "}",
4632                Style);
4633   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4634   verifyFormat("try\n"
4635                "{\n"
4636                "  // something\n"
4637                "}\n"
4638                "catch (...)\n"
4639                "{\n"
4640                "  // something\n"
4641                "}",
4642                Style);
4643   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4644   verifyFormat("try\n"
4645                "  {\n"
4646                "  // something white\n"
4647                "  }\n"
4648                "catch (...)\n"
4649                "  {\n"
4650                "  // something white\n"
4651                "  }",
4652                Style);
4653   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4654   verifyFormat("try\n"
4655                "  {\n"
4656                "    // something\n"
4657                "  }\n"
4658                "catch (...)\n"
4659                "  {\n"
4660                "    // something\n"
4661                "  }",
4662                Style);
4663   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4664   Style.BraceWrapping.BeforeCatch = true;
4665   verifyFormat("try {\n"
4666                "  // something\n"
4667                "}\n"
4668                "catch (...) {\n"
4669                "  // something\n"
4670                "}",
4671                Style);
4672 }
4673 
4674 TEST_F(FormatTest, StaticInitializers) {
4675   verifyFormat("static SomeClass SC = {1, 'a'};");
4676 
4677   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4678                "    100000000, "
4679                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4680 
4681   // Here, everything other than the "}" would fit on a line.
4682   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4683                "    10000000000000000000000000};");
4684   EXPECT_EQ("S s = {a,\n"
4685             "\n"
4686             "       b};",
4687             format("S s = {\n"
4688                    "  a,\n"
4689                    "\n"
4690                    "  b\n"
4691                    "};"));
4692 
4693   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4694   // line. However, the formatting looks a bit off and this probably doesn't
4695   // happen often in practice.
4696   verifyFormat("static int Variable[1] = {\n"
4697                "    {1000000000000000000000000000000000000}};",
4698                getLLVMStyleWithColumns(40));
4699 }
4700 
4701 TEST_F(FormatTest, DesignatedInitializers) {
4702   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4703   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4704                "                    .bbbbbbbbbb = 2,\n"
4705                "                    .cccccccccc = 3,\n"
4706                "                    .dddddddddd = 4,\n"
4707                "                    .eeeeeeeeee = 5};");
4708   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4709                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4710                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4711                "    .ccccccccccccccccccccccccccc = 3,\n"
4712                "    .ddddddddddddddddddddddddddd = 4,\n"
4713                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4714 
4715   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4716 
4717   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4718   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4719                "                    [2] = bbbbbbbbbb,\n"
4720                "                    [3] = cccccccccc,\n"
4721                "                    [4] = dddddddddd,\n"
4722                "                    [5] = eeeeeeeeee};");
4723   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4724                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4725                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4726                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4727                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4728                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4729 }
4730 
4731 TEST_F(FormatTest, NestedStaticInitializers) {
4732   verifyFormat("static A x = {{{}}};\n");
4733   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4734                "               {init1, init2, init3, init4}}};",
4735                getLLVMStyleWithColumns(50));
4736 
4737   verifyFormat("somes Status::global_reps[3] = {\n"
4738                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4739                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4740                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4741                getLLVMStyleWithColumns(60));
4742   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4743                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4744                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4745                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4746   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4747                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4748                "rect.fTop}};");
4749 
4750   verifyFormat(
4751       "SomeArrayOfSomeType a = {\n"
4752       "    {{1, 2, 3},\n"
4753       "     {1, 2, 3},\n"
4754       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4755       "      333333333333333333333333333333},\n"
4756       "     {1, 2, 3},\n"
4757       "     {1, 2, 3}}};");
4758   verifyFormat(
4759       "SomeArrayOfSomeType a = {\n"
4760       "    {{1, 2, 3}},\n"
4761       "    {{1, 2, 3}},\n"
4762       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4763       "      333333333333333333333333333333}},\n"
4764       "    {{1, 2, 3}},\n"
4765       "    {{1, 2, 3}}};");
4766 
4767   verifyFormat("struct {\n"
4768                "  unsigned bit;\n"
4769                "  const char *const name;\n"
4770                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4771                "                 {kOsWin, \"Windows\"},\n"
4772                "                 {kOsLinux, \"Linux\"},\n"
4773                "                 {kOsCrOS, \"Chrome OS\"}};");
4774   verifyFormat("struct {\n"
4775                "  unsigned bit;\n"
4776                "  const char *const name;\n"
4777                "} kBitsToOs[] = {\n"
4778                "    {kOsMac, \"Mac\"},\n"
4779                "    {kOsWin, \"Windows\"},\n"
4780                "    {kOsLinux, \"Linux\"},\n"
4781                "    {kOsCrOS, \"Chrome OS\"},\n"
4782                "};");
4783 }
4784 
4785 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4786   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4787                "                      \\\n"
4788                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4789 }
4790 
4791 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4792   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4793                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4794 
4795   // Do break defaulted and deleted functions.
4796   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4797                "    default;",
4798                getLLVMStyleWithColumns(40));
4799   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4800                "    delete;",
4801                getLLVMStyleWithColumns(40));
4802 }
4803 
4804 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4805   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4806                getLLVMStyleWithColumns(40));
4807   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4808                getLLVMStyleWithColumns(40));
4809   EXPECT_EQ("#define Q                              \\\n"
4810             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4811             "  \"aaaaaaaa.cpp\"",
4812             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4813                    getLLVMStyleWithColumns(40)));
4814 }
4815 
4816 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4817   EXPECT_EQ("# 123 \"A string literal\"",
4818             format("   #     123    \"A string literal\""));
4819 }
4820 
4821 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4822   EXPECT_EQ("#;", format("#;"));
4823   verifyFormat("#\n;\n;\n;");
4824 }
4825 
4826 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4827   EXPECT_EQ("#line 42 \"test\"\n",
4828             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4829   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4830                                     getLLVMStyleWithColumns(12)));
4831 }
4832 
4833 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4834   EXPECT_EQ("#line 42 \"test\"",
4835             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4836   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4837 }
4838 
4839 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4840   verifyFormat("#define A \\x20");
4841   verifyFormat("#define A \\ x20");
4842   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4843   verifyFormat("#define A ''");
4844   verifyFormat("#define A ''qqq");
4845   verifyFormat("#define A `qqq");
4846   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4847   EXPECT_EQ("const char *c = STRINGIFY(\n"
4848             "\\na : b);",
4849             format("const char * c = STRINGIFY(\n"
4850                    "\\na : b);"));
4851 
4852   verifyFormat("a\r\\");
4853   verifyFormat("a\v\\");
4854   verifyFormat("a\f\\");
4855 }
4856 
4857 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4858   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4859   style.IndentWidth = 4;
4860   style.PPIndentWidth = 1;
4861 
4862   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4863   verifyFormat("#ifdef __linux__\n"
4864                "void foo() {\n"
4865                "    int x = 0;\n"
4866                "}\n"
4867                "#define FOO\n"
4868                "#endif\n"
4869                "void bar() {\n"
4870                "    int y = 0;\n"
4871                "}\n",
4872                style);
4873 
4874   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4875   verifyFormat("#ifdef __linux__\n"
4876                "void foo() {\n"
4877                "    int x = 0;\n"
4878                "}\n"
4879                "# define FOO foo\n"
4880                "#endif\n"
4881                "void bar() {\n"
4882                "    int y = 0;\n"
4883                "}\n",
4884                style);
4885 
4886   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4887   verifyFormat("#ifdef __linux__\n"
4888                "void foo() {\n"
4889                "    int x = 0;\n"
4890                "}\n"
4891                " #define FOO foo\n"
4892                "#endif\n"
4893                "void bar() {\n"
4894                "    int y = 0;\n"
4895                "}\n",
4896                style);
4897 }
4898 
4899 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4900   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4901   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4902   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4903   // FIXME: We never break before the macro name.
4904   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4905 
4906   verifyFormat("#define A A\n#define A A");
4907   verifyFormat("#define A(X) A\n#define A A");
4908 
4909   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4910   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4911 }
4912 
4913 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4914   EXPECT_EQ("// somecomment\n"
4915             "#include \"a.h\"\n"
4916             "#define A(  \\\n"
4917             "    A, B)\n"
4918             "#include \"b.h\"\n"
4919             "// somecomment\n",
4920             format("  // somecomment\n"
4921                    "  #include \"a.h\"\n"
4922                    "#define A(A,\\\n"
4923                    "    B)\n"
4924                    "    #include \"b.h\"\n"
4925                    " // somecomment\n",
4926                    getLLVMStyleWithColumns(13)));
4927 }
4928 
4929 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4930 
4931 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4932   EXPECT_EQ("#define A    \\\n"
4933             "  c;         \\\n"
4934             "  e;\n"
4935             "f;",
4936             format("#define A c; e;\n"
4937                    "f;",
4938                    getLLVMStyleWithColumns(14)));
4939 }
4940 
4941 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4942 
4943 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4944   EXPECT_EQ("int x,\n"
4945             "#define A\n"
4946             "    y;",
4947             format("int x,\n#define A\ny;"));
4948 }
4949 
4950 TEST_F(FormatTest, HashInMacroDefinition) {
4951   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4952   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4953   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4954   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4955   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4956   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4957   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4958   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4959   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4960   verifyFormat("#define A  \\\n"
4961                "  {        \\\n"
4962                "    f(#c); \\\n"
4963                "  }",
4964                getLLVMStyleWithColumns(11));
4965 
4966   verifyFormat("#define A(X)         \\\n"
4967                "  void function##X()",
4968                getLLVMStyleWithColumns(22));
4969 
4970   verifyFormat("#define A(a, b, c)   \\\n"
4971                "  void a##b##c()",
4972                getLLVMStyleWithColumns(22));
4973 
4974   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4975 }
4976 
4977 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4978   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4979   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4980 
4981   FormatStyle Style = getLLVMStyle();
4982   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4983   verifyFormat("#define true ((foo)1)", Style);
4984   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4985   verifyFormat("#define false((foo)0)", Style);
4986 }
4987 
4988 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4989   EXPECT_EQ("#define A b;", format("#define A \\\n"
4990                                    "          \\\n"
4991                                    "  b;",
4992                                    getLLVMStyleWithColumns(25)));
4993   EXPECT_EQ("#define A \\\n"
4994             "          \\\n"
4995             "  a;      \\\n"
4996             "  b;",
4997             format("#define A \\\n"
4998                    "          \\\n"
4999                    "  a;      \\\n"
5000                    "  b;",
5001                    getLLVMStyleWithColumns(11)));
5002   EXPECT_EQ("#define A \\\n"
5003             "  a;      \\\n"
5004             "          \\\n"
5005             "  b;",
5006             format("#define A \\\n"
5007                    "  a;      \\\n"
5008                    "          \\\n"
5009                    "  b;",
5010                    getLLVMStyleWithColumns(11)));
5011 }
5012 
5013 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
5014   verifyIncompleteFormat("#define A :");
5015   verifyFormat("#define SOMECASES  \\\n"
5016                "  case 1:          \\\n"
5017                "  case 2\n",
5018                getLLVMStyleWithColumns(20));
5019   verifyFormat("#define MACRO(a) \\\n"
5020                "  if (a)         \\\n"
5021                "    f();         \\\n"
5022                "  else           \\\n"
5023                "    g()",
5024                getLLVMStyleWithColumns(18));
5025   verifyFormat("#define A template <typename T>");
5026   verifyIncompleteFormat("#define STR(x) #x\n"
5027                          "f(STR(this_is_a_string_literal{));");
5028   verifyFormat("#pragma omp threadprivate( \\\n"
5029                "    y)), // expected-warning",
5030                getLLVMStyleWithColumns(28));
5031   verifyFormat("#d, = };");
5032   verifyFormat("#if \"a");
5033   verifyIncompleteFormat("({\n"
5034                          "#define b     \\\n"
5035                          "  }           \\\n"
5036                          "  a\n"
5037                          "a",
5038                          getLLVMStyleWithColumns(15));
5039   verifyFormat("#define A     \\\n"
5040                "  {           \\\n"
5041                "    {\n"
5042                "#define B     \\\n"
5043                "  }           \\\n"
5044                "  }",
5045                getLLVMStyleWithColumns(15));
5046   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
5047   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
5048   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
5049   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
5050 }
5051 
5052 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
5053   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
5054   EXPECT_EQ("class A : public QObject {\n"
5055             "  Q_OBJECT\n"
5056             "\n"
5057             "  A() {}\n"
5058             "};",
5059             format("class A  :  public QObject {\n"
5060                    "     Q_OBJECT\n"
5061                    "\n"
5062                    "  A() {\n}\n"
5063                    "}  ;"));
5064   EXPECT_EQ("MACRO\n"
5065             "/*static*/ int i;",
5066             format("MACRO\n"
5067                    " /*static*/ int   i;"));
5068   EXPECT_EQ("SOME_MACRO\n"
5069             "namespace {\n"
5070             "void f();\n"
5071             "} // namespace",
5072             format("SOME_MACRO\n"
5073                    "  namespace    {\n"
5074                    "void   f(  );\n"
5075                    "} // namespace"));
5076   // Only if the identifier contains at least 5 characters.
5077   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
5078   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
5079   // Only if everything is upper case.
5080   EXPECT_EQ("class A : public QObject {\n"
5081             "  Q_Object A() {}\n"
5082             "};",
5083             format("class A  :  public QObject {\n"
5084                    "     Q_Object\n"
5085                    "  A() {\n}\n"
5086                    "}  ;"));
5087 
5088   // Only if the next line can actually start an unwrapped line.
5089   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
5090             format("SOME_WEIRD_LOG_MACRO\n"
5091                    "<< SomeThing;"));
5092 
5093   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
5094                "(n, buffers))\n",
5095                getChromiumStyle(FormatStyle::LK_Cpp));
5096 
5097   // See PR41483
5098   EXPECT_EQ("/**/ FOO(a)\n"
5099             "FOO(b)",
5100             format("/**/ FOO(a)\n"
5101                    "FOO(b)"));
5102 }
5103 
5104 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
5105   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5106             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5107             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5108             "class X {};\n"
5109             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5110             "int *createScopDetectionPass() { return 0; }",
5111             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5112                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5113                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5114                    "  class X {};\n"
5115                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5116                    "  int *createScopDetectionPass() { return 0; }"));
5117   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
5118   // braces, so that inner block is indented one level more.
5119   EXPECT_EQ("int q() {\n"
5120             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5121             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5122             "  IPC_END_MESSAGE_MAP()\n"
5123             "}",
5124             format("int q() {\n"
5125                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5126                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5127                    "  IPC_END_MESSAGE_MAP()\n"
5128                    "}"));
5129 
5130   // Same inside macros.
5131   EXPECT_EQ("#define LIST(L) \\\n"
5132             "  L(A)          \\\n"
5133             "  L(B)          \\\n"
5134             "  L(C)",
5135             format("#define LIST(L) \\\n"
5136                    "  L(A) \\\n"
5137                    "  L(B) \\\n"
5138                    "  L(C)",
5139                    getGoogleStyle()));
5140 
5141   // These must not be recognized as macros.
5142   EXPECT_EQ("int q() {\n"
5143             "  f(x);\n"
5144             "  f(x) {}\n"
5145             "  f(x)->g();\n"
5146             "  f(x)->*g();\n"
5147             "  f(x).g();\n"
5148             "  f(x) = x;\n"
5149             "  f(x) += x;\n"
5150             "  f(x) -= x;\n"
5151             "  f(x) *= x;\n"
5152             "  f(x) /= x;\n"
5153             "  f(x) %= x;\n"
5154             "  f(x) &= x;\n"
5155             "  f(x) |= x;\n"
5156             "  f(x) ^= x;\n"
5157             "  f(x) >>= x;\n"
5158             "  f(x) <<= x;\n"
5159             "  f(x)[y].z();\n"
5160             "  LOG(INFO) << x;\n"
5161             "  ifstream(x) >> x;\n"
5162             "}\n",
5163             format("int q() {\n"
5164                    "  f(x)\n;\n"
5165                    "  f(x)\n {}\n"
5166                    "  f(x)\n->g();\n"
5167                    "  f(x)\n->*g();\n"
5168                    "  f(x)\n.g();\n"
5169                    "  f(x)\n = x;\n"
5170                    "  f(x)\n += x;\n"
5171                    "  f(x)\n -= x;\n"
5172                    "  f(x)\n *= x;\n"
5173                    "  f(x)\n /= x;\n"
5174                    "  f(x)\n %= x;\n"
5175                    "  f(x)\n &= x;\n"
5176                    "  f(x)\n |= x;\n"
5177                    "  f(x)\n ^= x;\n"
5178                    "  f(x)\n >>= x;\n"
5179                    "  f(x)\n <<= x;\n"
5180                    "  f(x)\n[y].z();\n"
5181                    "  LOG(INFO)\n << x;\n"
5182                    "  ifstream(x)\n >> x;\n"
5183                    "}\n"));
5184   EXPECT_EQ("int q() {\n"
5185             "  F(x)\n"
5186             "  if (1) {\n"
5187             "  }\n"
5188             "  F(x)\n"
5189             "  while (1) {\n"
5190             "  }\n"
5191             "  F(x)\n"
5192             "  G(x);\n"
5193             "  F(x)\n"
5194             "  try {\n"
5195             "    Q();\n"
5196             "  } catch (...) {\n"
5197             "  }\n"
5198             "}\n",
5199             format("int q() {\n"
5200                    "F(x)\n"
5201                    "if (1) {}\n"
5202                    "F(x)\n"
5203                    "while (1) {}\n"
5204                    "F(x)\n"
5205                    "G(x);\n"
5206                    "F(x)\n"
5207                    "try { Q(); } catch (...) {}\n"
5208                    "}\n"));
5209   EXPECT_EQ("class A {\n"
5210             "  A() : t(0) {}\n"
5211             "  A(int i) noexcept() : {}\n"
5212             "  A(X x)\n" // FIXME: function-level try blocks are broken.
5213             "  try : t(0) {\n"
5214             "  } catch (...) {\n"
5215             "  }\n"
5216             "};",
5217             format("class A {\n"
5218                    "  A()\n : t(0) {}\n"
5219                    "  A(int i)\n noexcept() : {}\n"
5220                    "  A(X x)\n"
5221                    "  try : t(0) {} catch (...) {}\n"
5222                    "};"));
5223   FormatStyle Style = getLLVMStyle();
5224   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5225   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5226   Style.BraceWrapping.AfterFunction = true;
5227   EXPECT_EQ("void f()\n"
5228             "try\n"
5229             "{\n"
5230             "}",
5231             format("void f() try {\n"
5232                    "}",
5233                    Style));
5234   EXPECT_EQ("class SomeClass {\n"
5235             "public:\n"
5236             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5237             "};",
5238             format("class SomeClass {\n"
5239                    "public:\n"
5240                    "  SomeClass()\n"
5241                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5242                    "};"));
5243   EXPECT_EQ("class SomeClass {\n"
5244             "public:\n"
5245             "  SomeClass()\n"
5246             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5247             "};",
5248             format("class SomeClass {\n"
5249                    "public:\n"
5250                    "  SomeClass()\n"
5251                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5252                    "};",
5253                    getLLVMStyleWithColumns(40)));
5254 
5255   verifyFormat("MACRO(>)");
5256 
5257   // Some macros contain an implicit semicolon.
5258   Style = getLLVMStyle();
5259   Style.StatementMacros.push_back("FOO");
5260   verifyFormat("FOO(a) int b = 0;");
5261   verifyFormat("FOO(a)\n"
5262                "int b = 0;",
5263                Style);
5264   verifyFormat("FOO(a);\n"
5265                "int b = 0;",
5266                Style);
5267   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
5268                "int b = 0;",
5269                Style);
5270   verifyFormat("FOO()\n"
5271                "int b = 0;",
5272                Style);
5273   verifyFormat("FOO\n"
5274                "int b = 0;",
5275                Style);
5276   verifyFormat("void f() {\n"
5277                "  FOO(a)\n"
5278                "  return a;\n"
5279                "}",
5280                Style);
5281   verifyFormat("FOO(a)\n"
5282                "FOO(b)",
5283                Style);
5284   verifyFormat("int a = 0;\n"
5285                "FOO(b)\n"
5286                "int c = 0;",
5287                Style);
5288   verifyFormat("int a = 0;\n"
5289                "int x = FOO(a)\n"
5290                "int b = 0;",
5291                Style);
5292   verifyFormat("void foo(int a) { FOO(a) }\n"
5293                "uint32_t bar() {}",
5294                Style);
5295 }
5296 
5297 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
5298   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
5299 
5300   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
5301                ZeroColumn);
5302 }
5303 
5304 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5305   verifyFormat("#define A \\\n"
5306                "  f({     \\\n"
5307                "    g();  \\\n"
5308                "  });",
5309                getLLVMStyleWithColumns(11));
5310 }
5311 
5312 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5313   FormatStyle Style = getLLVMStyleWithColumns(40);
5314   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5315   verifyFormat("#ifdef _WIN32\n"
5316                "#define A 0\n"
5317                "#ifdef VAR2\n"
5318                "#define B 1\n"
5319                "#include <someheader.h>\n"
5320                "#define MACRO                          \\\n"
5321                "  some_very_long_func_aaaaaaaaaa();\n"
5322                "#endif\n"
5323                "#else\n"
5324                "#define A 1\n"
5325                "#endif",
5326                Style);
5327   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5328   verifyFormat("#ifdef _WIN32\n"
5329                "#  define A 0\n"
5330                "#  ifdef VAR2\n"
5331                "#    define B 1\n"
5332                "#    include <someheader.h>\n"
5333                "#    define MACRO                      \\\n"
5334                "      some_very_long_func_aaaaaaaaaa();\n"
5335                "#  endif\n"
5336                "#else\n"
5337                "#  define A 1\n"
5338                "#endif",
5339                Style);
5340   verifyFormat("#if A\n"
5341                "#  define MACRO                        \\\n"
5342                "    void a(int x) {                    \\\n"
5343                "      b();                             \\\n"
5344                "      c();                             \\\n"
5345                "      d();                             \\\n"
5346                "      e();                             \\\n"
5347                "      f();                             \\\n"
5348                "    }\n"
5349                "#endif",
5350                Style);
5351   // Comments before include guard.
5352   verifyFormat("// file comment\n"
5353                "// file comment\n"
5354                "#ifndef HEADER_H\n"
5355                "#define HEADER_H\n"
5356                "code();\n"
5357                "#endif",
5358                Style);
5359   // Test with include guards.
5360   verifyFormat("#ifndef HEADER_H\n"
5361                "#define HEADER_H\n"
5362                "code();\n"
5363                "#endif",
5364                Style);
5365   // Include guards must have a #define with the same variable immediately
5366   // after #ifndef.
5367   verifyFormat("#ifndef NOT_GUARD\n"
5368                "#  define FOO\n"
5369                "code();\n"
5370                "#endif",
5371                Style);
5372 
5373   // Include guards must cover the entire file.
5374   verifyFormat("code();\n"
5375                "code();\n"
5376                "#ifndef NOT_GUARD\n"
5377                "#  define NOT_GUARD\n"
5378                "code();\n"
5379                "#endif",
5380                Style);
5381   verifyFormat("#ifndef NOT_GUARD\n"
5382                "#  define NOT_GUARD\n"
5383                "code();\n"
5384                "#endif\n"
5385                "code();",
5386                Style);
5387   // Test with trailing blank lines.
5388   verifyFormat("#ifndef HEADER_H\n"
5389                "#define HEADER_H\n"
5390                "code();\n"
5391                "#endif\n",
5392                Style);
5393   // Include guards don't have #else.
5394   verifyFormat("#ifndef NOT_GUARD\n"
5395                "#  define NOT_GUARD\n"
5396                "code();\n"
5397                "#else\n"
5398                "#endif",
5399                Style);
5400   verifyFormat("#ifndef NOT_GUARD\n"
5401                "#  define NOT_GUARD\n"
5402                "code();\n"
5403                "#elif FOO\n"
5404                "#endif",
5405                Style);
5406   // Non-identifier #define after potential include guard.
5407   verifyFormat("#ifndef FOO\n"
5408                "#  define 1\n"
5409                "#endif\n",
5410                Style);
5411   // #if closes past last non-preprocessor line.
5412   verifyFormat("#ifndef FOO\n"
5413                "#define FOO\n"
5414                "#if 1\n"
5415                "int i;\n"
5416                "#  define A 0\n"
5417                "#endif\n"
5418                "#endif\n",
5419                Style);
5420   // Don't crash if there is an #elif directive without a condition.
5421   verifyFormat("#if 1\n"
5422                "int x;\n"
5423                "#elif\n"
5424                "int y;\n"
5425                "#else\n"
5426                "int z;\n"
5427                "#endif",
5428                Style);
5429   // FIXME: This doesn't handle the case where there's code between the
5430   // #ifndef and #define but all other conditions hold. This is because when
5431   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5432   // previous code line yet, so we can't detect it.
5433   EXPECT_EQ("#ifndef NOT_GUARD\n"
5434             "code();\n"
5435             "#define NOT_GUARD\n"
5436             "code();\n"
5437             "#endif",
5438             format("#ifndef NOT_GUARD\n"
5439                    "code();\n"
5440                    "#  define NOT_GUARD\n"
5441                    "code();\n"
5442                    "#endif",
5443                    Style));
5444   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5445   // be outside an include guard. Examples are #pragma once and
5446   // #pragma GCC diagnostic, or anything else that does not change the meaning
5447   // of the file if it's included multiple times.
5448   EXPECT_EQ("#ifdef WIN32\n"
5449             "#  pragma once\n"
5450             "#endif\n"
5451             "#ifndef HEADER_H\n"
5452             "#  define HEADER_H\n"
5453             "code();\n"
5454             "#endif",
5455             format("#ifdef WIN32\n"
5456                    "#  pragma once\n"
5457                    "#endif\n"
5458                    "#ifndef HEADER_H\n"
5459                    "#define HEADER_H\n"
5460                    "code();\n"
5461                    "#endif",
5462                    Style));
5463   // FIXME: This does not detect when there is a single non-preprocessor line
5464   // in front of an include-guard-like structure where other conditions hold
5465   // because ScopedLineState hides the line.
5466   EXPECT_EQ("code();\n"
5467             "#ifndef HEADER_H\n"
5468             "#define HEADER_H\n"
5469             "code();\n"
5470             "#endif",
5471             format("code();\n"
5472                    "#ifndef HEADER_H\n"
5473                    "#  define HEADER_H\n"
5474                    "code();\n"
5475                    "#endif",
5476                    Style));
5477   // Keep comments aligned with #, otherwise indent comments normally. These
5478   // tests cannot use verifyFormat because messUp manipulates leading
5479   // whitespace.
5480   {
5481     const char *Expected = ""
5482                            "void f() {\n"
5483                            "#if 1\n"
5484                            "// Preprocessor aligned.\n"
5485                            "#  define A 0\n"
5486                            "  // Code. Separated by blank line.\n"
5487                            "\n"
5488                            "#  define B 0\n"
5489                            "  // Code. Not aligned with #\n"
5490                            "#  define C 0\n"
5491                            "#endif";
5492     const char *ToFormat = ""
5493                            "void f() {\n"
5494                            "#if 1\n"
5495                            "// Preprocessor aligned.\n"
5496                            "#  define A 0\n"
5497                            "// Code. Separated by blank line.\n"
5498                            "\n"
5499                            "#  define B 0\n"
5500                            "   // Code. Not aligned with #\n"
5501                            "#  define C 0\n"
5502                            "#endif";
5503     EXPECT_EQ(Expected, format(ToFormat, Style));
5504     EXPECT_EQ(Expected, format(Expected, Style));
5505   }
5506   // Keep block quotes aligned.
5507   {
5508     const char *Expected = ""
5509                            "void f() {\n"
5510                            "#if 1\n"
5511                            "/* Preprocessor aligned. */\n"
5512                            "#  define A 0\n"
5513                            "  /* Code. Separated by blank line. */\n"
5514                            "\n"
5515                            "#  define B 0\n"
5516                            "  /* Code. Not aligned with # */\n"
5517                            "#  define C 0\n"
5518                            "#endif";
5519     const char *ToFormat = ""
5520                            "void f() {\n"
5521                            "#if 1\n"
5522                            "/* Preprocessor aligned. */\n"
5523                            "#  define A 0\n"
5524                            "/* Code. Separated by blank line. */\n"
5525                            "\n"
5526                            "#  define B 0\n"
5527                            "   /* Code. Not aligned with # */\n"
5528                            "#  define C 0\n"
5529                            "#endif";
5530     EXPECT_EQ(Expected, format(ToFormat, Style));
5531     EXPECT_EQ(Expected, format(Expected, Style));
5532   }
5533   // Keep comments aligned with un-indented directives.
5534   {
5535     const char *Expected = ""
5536                            "void f() {\n"
5537                            "// Preprocessor aligned.\n"
5538                            "#define A 0\n"
5539                            "  // Code. Separated by blank line.\n"
5540                            "\n"
5541                            "#define B 0\n"
5542                            "  // Code. Not aligned with #\n"
5543                            "#define C 0\n";
5544     const char *ToFormat = ""
5545                            "void f() {\n"
5546                            "// Preprocessor aligned.\n"
5547                            "#define A 0\n"
5548                            "// Code. Separated by blank line.\n"
5549                            "\n"
5550                            "#define B 0\n"
5551                            "   // Code. Not aligned with #\n"
5552                            "#define C 0\n";
5553     EXPECT_EQ(Expected, format(ToFormat, Style));
5554     EXPECT_EQ(Expected, format(Expected, Style));
5555   }
5556   // Test AfterHash with tabs.
5557   {
5558     FormatStyle Tabbed = Style;
5559     Tabbed.UseTab = FormatStyle::UT_Always;
5560     Tabbed.IndentWidth = 8;
5561     Tabbed.TabWidth = 8;
5562     verifyFormat("#ifdef _WIN32\n"
5563                  "#\tdefine A 0\n"
5564                  "#\tifdef VAR2\n"
5565                  "#\t\tdefine B 1\n"
5566                  "#\t\tinclude <someheader.h>\n"
5567                  "#\t\tdefine MACRO          \\\n"
5568                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5569                  "#\tendif\n"
5570                  "#else\n"
5571                  "#\tdefine A 1\n"
5572                  "#endif",
5573                  Tabbed);
5574   }
5575 
5576   // Regression test: Multiline-macro inside include guards.
5577   verifyFormat("#ifndef HEADER_H\n"
5578                "#define HEADER_H\n"
5579                "#define A()        \\\n"
5580                "  int i;           \\\n"
5581                "  int j;\n"
5582                "#endif // HEADER_H",
5583                getLLVMStyleWithColumns(20));
5584 
5585   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5586   // Basic before hash indent tests
5587   verifyFormat("#ifdef _WIN32\n"
5588                "  #define A 0\n"
5589                "  #ifdef VAR2\n"
5590                "    #define B 1\n"
5591                "    #include <someheader.h>\n"
5592                "    #define MACRO                      \\\n"
5593                "      some_very_long_func_aaaaaaaaaa();\n"
5594                "  #endif\n"
5595                "#else\n"
5596                "  #define A 1\n"
5597                "#endif",
5598                Style);
5599   verifyFormat("#if A\n"
5600                "  #define MACRO                        \\\n"
5601                "    void a(int x) {                    \\\n"
5602                "      b();                             \\\n"
5603                "      c();                             \\\n"
5604                "      d();                             \\\n"
5605                "      e();                             \\\n"
5606                "      f();                             \\\n"
5607                "    }\n"
5608                "#endif",
5609                Style);
5610   // Keep comments aligned with indented directives. These
5611   // tests cannot use verifyFormat because messUp manipulates leading
5612   // whitespace.
5613   {
5614     const char *Expected = "void f() {\n"
5615                            "// Aligned to preprocessor.\n"
5616                            "#if 1\n"
5617                            "  // Aligned to code.\n"
5618                            "  int a;\n"
5619                            "  #if 1\n"
5620                            "    // Aligned to preprocessor.\n"
5621                            "    #define A 0\n"
5622                            "  // Aligned to code.\n"
5623                            "  int b;\n"
5624                            "  #endif\n"
5625                            "#endif\n"
5626                            "}";
5627     const char *ToFormat = "void f() {\n"
5628                            "// Aligned to preprocessor.\n"
5629                            "#if 1\n"
5630                            "// Aligned to code.\n"
5631                            "int a;\n"
5632                            "#if 1\n"
5633                            "// Aligned to preprocessor.\n"
5634                            "#define A 0\n"
5635                            "// Aligned to code.\n"
5636                            "int b;\n"
5637                            "#endif\n"
5638                            "#endif\n"
5639                            "}";
5640     EXPECT_EQ(Expected, format(ToFormat, Style));
5641     EXPECT_EQ(Expected, format(Expected, Style));
5642   }
5643   {
5644     const char *Expected = "void f() {\n"
5645                            "/* Aligned to preprocessor. */\n"
5646                            "#if 1\n"
5647                            "  /* Aligned to code. */\n"
5648                            "  int a;\n"
5649                            "  #if 1\n"
5650                            "    /* Aligned to preprocessor. */\n"
5651                            "    #define A 0\n"
5652                            "  /* Aligned to code. */\n"
5653                            "  int b;\n"
5654                            "  #endif\n"
5655                            "#endif\n"
5656                            "}";
5657     const char *ToFormat = "void f() {\n"
5658                            "/* Aligned to preprocessor. */\n"
5659                            "#if 1\n"
5660                            "/* Aligned to code. */\n"
5661                            "int a;\n"
5662                            "#if 1\n"
5663                            "/* Aligned to preprocessor. */\n"
5664                            "#define A 0\n"
5665                            "/* Aligned to code. */\n"
5666                            "int b;\n"
5667                            "#endif\n"
5668                            "#endif\n"
5669                            "}";
5670     EXPECT_EQ(Expected, format(ToFormat, Style));
5671     EXPECT_EQ(Expected, format(Expected, Style));
5672   }
5673 
5674   // Test single comment before preprocessor
5675   verifyFormat("// Comment\n"
5676                "\n"
5677                "#if 1\n"
5678                "#endif",
5679                Style);
5680 }
5681 
5682 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5683   verifyFormat("{\n  { a #c; }\n}");
5684 }
5685 
5686 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5687   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5688             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5689   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5690             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5691 }
5692 
5693 TEST_F(FormatTest, EscapedNewlines) {
5694   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5695   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5696             format("#define A \\\nint i;\\\n  int j;", Narrow));
5697   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5698   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5699   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5700   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5701 
5702   FormatStyle AlignLeft = getLLVMStyle();
5703   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5704   EXPECT_EQ("#define MACRO(x) \\\n"
5705             "private:         \\\n"
5706             "  int x(int a);\n",
5707             format("#define MACRO(x) \\\n"
5708                    "private:         \\\n"
5709                    "  int x(int a);\n",
5710                    AlignLeft));
5711 
5712   // CRLF line endings
5713   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5714             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5715   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5716   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5717   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5718   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5719   EXPECT_EQ("#define MACRO(x) \\\r\n"
5720             "private:         \\\r\n"
5721             "  int x(int a);\r\n",
5722             format("#define MACRO(x) \\\r\n"
5723                    "private:         \\\r\n"
5724                    "  int x(int a);\r\n",
5725                    AlignLeft));
5726 
5727   FormatStyle DontAlign = getLLVMStyle();
5728   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5729   DontAlign.MaxEmptyLinesToKeep = 3;
5730   // FIXME: can't use verifyFormat here because the newline before
5731   // "public:" is not inserted the first time it's reformatted
5732   EXPECT_EQ("#define A \\\n"
5733             "  class Foo { \\\n"
5734             "    void bar(); \\\n"
5735             "\\\n"
5736             "\\\n"
5737             "\\\n"
5738             "  public: \\\n"
5739             "    void baz(); \\\n"
5740             "  };",
5741             format("#define A \\\n"
5742                    "  class Foo { \\\n"
5743                    "    void bar(); \\\n"
5744                    "\\\n"
5745                    "\\\n"
5746                    "\\\n"
5747                    "  public: \\\n"
5748                    "    void baz(); \\\n"
5749                    "  };",
5750                    DontAlign));
5751 }
5752 
5753 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5754   verifyFormat("#define A \\\n"
5755                "  int v(  \\\n"
5756                "      a); \\\n"
5757                "  int i;",
5758                getLLVMStyleWithColumns(11));
5759 }
5760 
5761 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5762   EXPECT_EQ(
5763       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5764       "                      \\\n"
5765       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5766       "\n"
5767       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5768       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5769       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5770              "\\\n"
5771              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5772              "  \n"
5773              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5774              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5775 }
5776 
5777 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5778   EXPECT_EQ("int\n"
5779             "#define A\n"
5780             "    a;",
5781             format("int\n#define A\na;"));
5782   verifyFormat("functionCallTo(\n"
5783                "    someOtherFunction(\n"
5784                "        withSomeParameters, whichInSequence,\n"
5785                "        areLongerThanALine(andAnotherCall,\n"
5786                "#define A B\n"
5787                "                           withMoreParamters,\n"
5788                "                           whichStronglyInfluenceTheLayout),\n"
5789                "        andMoreParameters),\n"
5790                "    trailing);",
5791                getLLVMStyleWithColumns(69));
5792   verifyFormat("Foo::Foo()\n"
5793                "#ifdef BAR\n"
5794                "    : baz(0)\n"
5795                "#endif\n"
5796                "{\n"
5797                "}");
5798   verifyFormat("void f() {\n"
5799                "  if (true)\n"
5800                "#ifdef A\n"
5801                "    f(42);\n"
5802                "  x();\n"
5803                "#else\n"
5804                "    g();\n"
5805                "  x();\n"
5806                "#endif\n"
5807                "}");
5808   verifyFormat("void f(param1, param2,\n"
5809                "       param3,\n"
5810                "#ifdef A\n"
5811                "       param4(param5,\n"
5812                "#ifdef A1\n"
5813                "              param6,\n"
5814                "#ifdef A2\n"
5815                "              param7),\n"
5816                "#else\n"
5817                "              param8),\n"
5818                "       param9,\n"
5819                "#endif\n"
5820                "       param10,\n"
5821                "#endif\n"
5822                "       param11)\n"
5823                "#else\n"
5824                "       param12)\n"
5825                "#endif\n"
5826                "{\n"
5827                "  x();\n"
5828                "}",
5829                getLLVMStyleWithColumns(28));
5830   verifyFormat("#if 1\n"
5831                "int i;");
5832   verifyFormat("#if 1\n"
5833                "#endif\n"
5834                "#if 1\n"
5835                "#else\n"
5836                "#endif\n");
5837   verifyFormat("DEBUG({\n"
5838                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5839                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5840                "});\n"
5841                "#if a\n"
5842                "#else\n"
5843                "#endif");
5844 
5845   verifyIncompleteFormat("void f(\n"
5846                          "#if A\n"
5847                          ");\n"
5848                          "#else\n"
5849                          "#endif");
5850 }
5851 
5852 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5853   verifyFormat("#endif\n"
5854                "#if B");
5855 }
5856 
5857 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5858   FormatStyle SingleLine = getLLVMStyle();
5859   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5860   verifyFormat("#if 0\n"
5861                "#elif 1\n"
5862                "#endif\n"
5863                "void foo() {\n"
5864                "  if (test) foo2();\n"
5865                "}",
5866                SingleLine);
5867 }
5868 
5869 TEST_F(FormatTest, LayoutBlockInsideParens) {
5870   verifyFormat("functionCall({ int i; });");
5871   verifyFormat("functionCall({\n"
5872                "  int i;\n"
5873                "  int j;\n"
5874                "});");
5875   verifyFormat("functionCall(\n"
5876                "    {\n"
5877                "      int i;\n"
5878                "      int j;\n"
5879                "    },\n"
5880                "    aaaa, bbbb, cccc);");
5881   verifyFormat("functionA(functionB({\n"
5882                "            int i;\n"
5883                "            int j;\n"
5884                "          }),\n"
5885                "          aaaa, bbbb, cccc);");
5886   verifyFormat("functionCall(\n"
5887                "    {\n"
5888                "      int i;\n"
5889                "      int j;\n"
5890                "    },\n"
5891                "    aaaa, bbbb, // comment\n"
5892                "    cccc);");
5893   verifyFormat("functionA(functionB({\n"
5894                "            int i;\n"
5895                "            int j;\n"
5896                "          }),\n"
5897                "          aaaa, bbbb, // comment\n"
5898                "          cccc);");
5899   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5900   verifyFormat("functionCall(aaaa, bbbb, {\n"
5901                "  int i;\n"
5902                "  int j;\n"
5903                "});");
5904   verifyFormat(
5905       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5906       "    {\n"
5907       "      int i; // break\n"
5908       "    },\n"
5909       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5910       "                                     ccccccccccccccccc));");
5911   verifyFormat("DEBUG({\n"
5912                "  if (a)\n"
5913                "    f();\n"
5914                "});");
5915 }
5916 
5917 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5918   EXPECT_EQ("SOME_MACRO { int i; }\n"
5919             "int i;",
5920             format("  SOME_MACRO  {int i;}  int i;"));
5921 }
5922 
5923 TEST_F(FormatTest, LayoutNestedBlocks) {
5924   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5925                "  struct s {\n"
5926                "    int i;\n"
5927                "  };\n"
5928                "  s kBitsToOs[] = {{10}};\n"
5929                "  for (int i = 0; i < 10; ++i)\n"
5930                "    return;\n"
5931                "}");
5932   verifyFormat("call(parameter, {\n"
5933                "  something();\n"
5934                "  // Comment using all columns.\n"
5935                "  somethingelse();\n"
5936                "});",
5937                getLLVMStyleWithColumns(40));
5938   verifyFormat("DEBUG( //\n"
5939                "    { f(); }, a);");
5940   verifyFormat("DEBUG( //\n"
5941                "    {\n"
5942                "      f(); //\n"
5943                "    },\n"
5944                "    a);");
5945 
5946   EXPECT_EQ("call(parameter, {\n"
5947             "  something();\n"
5948             "  // Comment too\n"
5949             "  // looooooooooong.\n"
5950             "  somethingElse();\n"
5951             "});",
5952             format("call(parameter, {\n"
5953                    "  something();\n"
5954                    "  // Comment too looooooooooong.\n"
5955                    "  somethingElse();\n"
5956                    "});",
5957                    getLLVMStyleWithColumns(29)));
5958   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5959   EXPECT_EQ("DEBUG({ // comment\n"
5960             "  int i;\n"
5961             "});",
5962             format("DEBUG({ // comment\n"
5963                    "int  i;\n"
5964                    "});"));
5965   EXPECT_EQ("DEBUG({\n"
5966             "  int i;\n"
5967             "\n"
5968             "  // comment\n"
5969             "  int j;\n"
5970             "});",
5971             format("DEBUG({\n"
5972                    "  int  i;\n"
5973                    "\n"
5974                    "  // comment\n"
5975                    "  int  j;\n"
5976                    "});"));
5977 
5978   verifyFormat("DEBUG({\n"
5979                "  if (a)\n"
5980                "    return;\n"
5981                "});");
5982   verifyGoogleFormat("DEBUG({\n"
5983                      "  if (a) return;\n"
5984                      "});");
5985   FormatStyle Style = getGoogleStyle();
5986   Style.ColumnLimit = 45;
5987   verifyFormat("Debug(\n"
5988                "    aaaaa,\n"
5989                "    {\n"
5990                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5991                "    },\n"
5992                "    a);",
5993                Style);
5994 
5995   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5996 
5997   verifyNoCrash("^{v^{a}}");
5998 }
5999 
6000 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
6001   EXPECT_EQ("#define MACRO()                     \\\n"
6002             "  Debug(aaa, /* force line break */ \\\n"
6003             "        {                           \\\n"
6004             "          int i;                    \\\n"
6005             "          int j;                    \\\n"
6006             "        })",
6007             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
6008                    "          {  int   i;  int  j;   })",
6009                    getGoogleStyle()));
6010 
6011   EXPECT_EQ("#define A                                       \\\n"
6012             "  [] {                                          \\\n"
6013             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
6014             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
6015             "  }",
6016             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
6017                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
6018                    getGoogleStyle()));
6019 }
6020 
6021 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
6022   EXPECT_EQ("{}", format("{}"));
6023   verifyFormat("enum E {};");
6024   verifyFormat("enum E {}");
6025   FormatStyle Style = getLLVMStyle();
6026   Style.SpaceInEmptyBlock = true;
6027   EXPECT_EQ("void f() { }", format("void f() {}", Style));
6028   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
6029   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
6030   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
6031   Style.BraceWrapping.BeforeElse = false;
6032   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
6033   verifyFormat("if (a)\n"
6034                "{\n"
6035                "} else if (b)\n"
6036                "{\n"
6037                "} else\n"
6038                "{ }",
6039                Style);
6040   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
6041   verifyFormat("if (a) {\n"
6042                "} else if (b) {\n"
6043                "} else {\n"
6044                "}",
6045                Style);
6046   Style.BraceWrapping.BeforeElse = true;
6047   verifyFormat("if (a) { }\n"
6048                "else if (b) { }\n"
6049                "else { }",
6050                Style);
6051 }
6052 
6053 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
6054   FormatStyle Style = getLLVMStyle();
6055   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
6056   Style.MacroBlockEnd = "^[A-Z_]+_END$";
6057   verifyFormat("FOO_BEGIN\n"
6058                "  FOO_ENTRY\n"
6059                "FOO_END",
6060                Style);
6061   verifyFormat("FOO_BEGIN\n"
6062                "  NESTED_FOO_BEGIN\n"
6063                "    NESTED_FOO_ENTRY\n"
6064                "  NESTED_FOO_END\n"
6065                "FOO_END",
6066                Style);
6067   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
6068                "  int x;\n"
6069                "  x = 1;\n"
6070                "FOO_END(Baz)",
6071                Style);
6072 }
6073 
6074 //===----------------------------------------------------------------------===//
6075 // Line break tests.
6076 //===----------------------------------------------------------------------===//
6077 
6078 TEST_F(FormatTest, PreventConfusingIndents) {
6079   verifyFormat(
6080       "void f() {\n"
6081       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
6082       "                         parameter, parameter, parameter)),\n"
6083       "                     SecondLongCall(parameter));\n"
6084       "}");
6085   verifyFormat(
6086       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6087       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6088       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6089       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
6090   verifyFormat(
6091       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6092       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
6093       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6094       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
6095   verifyFormat(
6096       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
6097       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
6098       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
6099       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
6100   verifyFormat("int a = bbbb && ccc &&\n"
6101                "        fffff(\n"
6102                "#define A Just forcing a new line\n"
6103                "            ddd);");
6104 }
6105 
6106 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
6107   verifyFormat(
6108       "bool aaaaaaa =\n"
6109       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
6110       "    bbbbbbbb();");
6111   verifyFormat(
6112       "bool aaaaaaa =\n"
6113       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
6114       "    bbbbbbbb();");
6115 
6116   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6117                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
6118                "    ccccccccc == ddddddddddd;");
6119   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6120                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
6121                "    ccccccccc == ddddddddddd;");
6122   verifyFormat(
6123       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6124       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
6125       "    ccccccccc == ddddddddddd;");
6126 
6127   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6128                "                 aaaaaa) &&\n"
6129                "         bbbbbb && cccccc;");
6130   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6131                "                 aaaaaa) >>\n"
6132                "         bbbbbb;");
6133   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
6134                "    SourceMgr.getSpellingColumnNumber(\n"
6135                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
6136                "    1);");
6137 
6138   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6139                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
6140                "    cccccc) {\n}");
6141   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6142                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6143                "              cccccc) {\n}");
6144   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6145                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6146                "              cccccc) {\n}");
6147   verifyFormat("b = a &&\n"
6148                "    // Comment\n"
6149                "    b.c && d;");
6150 
6151   // If the LHS of a comparison is not a binary expression itself, the
6152   // additional linebreak confuses many people.
6153   verifyFormat(
6154       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6155       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
6156       "}");
6157   verifyFormat(
6158       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6159       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6160       "}");
6161   verifyFormat(
6162       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
6163       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6164       "}");
6165   verifyFormat(
6166       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6167       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
6168       "}");
6169   // Even explicit parentheses stress the precedence enough to make the
6170   // additional break unnecessary.
6171   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6172                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6173                "}");
6174   // This cases is borderline, but with the indentation it is still readable.
6175   verifyFormat(
6176       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6177       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6178       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6179       "}",
6180       getLLVMStyleWithColumns(75));
6181 
6182   // If the LHS is a binary expression, we should still use the additional break
6183   // as otherwise the formatting hides the operator precedence.
6184   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6185                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6186                "    5) {\n"
6187                "}");
6188   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6189                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
6190                "    5) {\n"
6191                "}");
6192 
6193   FormatStyle OnePerLine = getLLVMStyle();
6194   OnePerLine.BinPackParameters = false;
6195   verifyFormat(
6196       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6197       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6198       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
6199       OnePerLine);
6200 
6201   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
6202                "                .aaa(aaaaaaaaaaaaa) *\n"
6203                "            aaaaaaa +\n"
6204                "        aaaaaaa;",
6205                getLLVMStyleWithColumns(40));
6206 }
6207 
6208 TEST_F(FormatTest, ExpressionIndentation) {
6209   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6210                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6211                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6212                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6213                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6214                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
6215                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6216                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
6217                "                 ccccccccccccccccccccccccccccccccccccccccc;");
6218   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6219                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6220                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6221                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6222   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6223                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6224                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6225                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6226   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6227                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6228                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6229                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6230   verifyFormat("if () {\n"
6231                "} else if (aaaaa && bbbbb > // break\n"
6232                "                        ccccc) {\n"
6233                "}");
6234   verifyFormat("if () {\n"
6235                "} else if constexpr (aaaaa && bbbbb > // break\n"
6236                "                                  ccccc) {\n"
6237                "}");
6238   verifyFormat("if () {\n"
6239                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
6240                "                                  ccccc) {\n"
6241                "}");
6242   verifyFormat("if () {\n"
6243                "} else if (aaaaa &&\n"
6244                "           bbbbb > // break\n"
6245                "               ccccc &&\n"
6246                "           ddddd) {\n"
6247                "}");
6248 
6249   // Presence of a trailing comment used to change indentation of b.
6250   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
6251                "       b;\n"
6252                "return aaaaaaaaaaaaaaaaaaa +\n"
6253                "       b; //",
6254                getLLVMStyleWithColumns(30));
6255 }
6256 
6257 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
6258   // Not sure what the best system is here. Like this, the LHS can be found
6259   // immediately above an operator (everything with the same or a higher
6260   // indent). The RHS is aligned right of the operator and so compasses
6261   // everything until something with the same indent as the operator is found.
6262   // FIXME: Is this a good system?
6263   FormatStyle Style = getLLVMStyle();
6264   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6265   verifyFormat(
6266       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6267       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6268       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6269       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6270       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6271       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6272       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6273       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6274       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
6275       Style);
6276   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6277                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6278                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6279                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6280                Style);
6281   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6282                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6283                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6284                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6285                Style);
6286   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6287                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6288                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6289                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6290                Style);
6291   verifyFormat("if () {\n"
6292                "} else if (aaaaa\n"
6293                "           && bbbbb // break\n"
6294                "                  > ccccc) {\n"
6295                "}",
6296                Style);
6297   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6298                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6299                Style);
6300   verifyFormat("return (a)\n"
6301                "       // comment\n"
6302                "       + b;",
6303                Style);
6304   verifyFormat(
6305       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6306       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6307       "             + cc;",
6308       Style);
6309 
6310   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6311                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6312                Style);
6313 
6314   // Forced by comments.
6315   verifyFormat(
6316       "unsigned ContentSize =\n"
6317       "    sizeof(int16_t)   // DWARF ARange version number\n"
6318       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6319       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6320       "    + sizeof(int8_t); // Segment Size (in bytes)");
6321 
6322   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6323                "       == boost::fusion::at_c<1>(iiii).second;",
6324                Style);
6325 
6326   Style.ColumnLimit = 60;
6327   verifyFormat("zzzzzzzzzz\n"
6328                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6329                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6330                Style);
6331 
6332   Style.ColumnLimit = 80;
6333   Style.IndentWidth = 4;
6334   Style.TabWidth = 4;
6335   Style.UseTab = FormatStyle::UT_Always;
6336   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6337   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6338   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6339             "\t&& (someOtherLongishConditionPart1\n"
6340             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6341             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6342                    "(someOtherLongishConditionPart1 || "
6343                    "someOtherEvenLongerNestedConditionPart2);",
6344                    Style));
6345 }
6346 
6347 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6348   FormatStyle Style = getLLVMStyle();
6349   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6350   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6351 
6352   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6353                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6354                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6355                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6356                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6357                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6358                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6359                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6360                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6361                Style);
6362   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6363                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6364                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6365                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6366                Style);
6367   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6368                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6369                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6370                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6371                Style);
6372   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6373                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6374                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6375                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6376                Style);
6377   verifyFormat("if () {\n"
6378                "} else if (aaaaa\n"
6379                "           && bbbbb // break\n"
6380                "                  > ccccc) {\n"
6381                "}",
6382                Style);
6383   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6384                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6385                Style);
6386   verifyFormat("return (a)\n"
6387                "     // comment\n"
6388                "     + b;",
6389                Style);
6390   verifyFormat(
6391       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6392       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6393       "           + cc;",
6394       Style);
6395   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6396                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6397                "                        : 3333333333333333;",
6398                Style);
6399   verifyFormat(
6400       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6401       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6402       "                                             : eeeeeeeeeeeeeeeeee)\n"
6403       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6404       "                        : 3333333333333333;",
6405       Style);
6406   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6407                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6408                Style);
6409 
6410   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6411                "    == boost::fusion::at_c<1>(iiii).second;",
6412                Style);
6413 
6414   Style.ColumnLimit = 60;
6415   verifyFormat("zzzzzzzzzzzzz\n"
6416                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6417                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6418                Style);
6419 
6420   // Forced by comments.
6421   Style.ColumnLimit = 80;
6422   verifyFormat(
6423       "unsigned ContentSize\n"
6424       "    = sizeof(int16_t) // DWARF ARange version number\n"
6425       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6426       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6427       "    + sizeof(int8_t); // Segment Size (in bytes)",
6428       Style);
6429 
6430   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6431   verifyFormat(
6432       "unsigned ContentSize =\n"
6433       "    sizeof(int16_t)   // DWARF ARange version number\n"
6434       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6435       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6436       "    + sizeof(int8_t); // Segment Size (in bytes)",
6437       Style);
6438 
6439   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6440   verifyFormat(
6441       "unsigned ContentSize =\n"
6442       "    sizeof(int16_t)   // DWARF ARange version number\n"
6443       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6444       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6445       "    + sizeof(int8_t); // Segment Size (in bytes)",
6446       Style);
6447 }
6448 
6449 TEST_F(FormatTest, EnforcedOperatorWraps) {
6450   // Here we'd like to wrap after the || operators, but a comment is forcing an
6451   // earlier wrap.
6452   verifyFormat("bool x = aaaaa //\n"
6453                "         || bbbbb\n"
6454                "         //\n"
6455                "         || cccc;");
6456 }
6457 
6458 TEST_F(FormatTest, NoOperandAlignment) {
6459   FormatStyle Style = getLLVMStyle();
6460   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6461   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6462                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6463                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6464                Style);
6465   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6466   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6467                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6468                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6469                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6470                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6471                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6472                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6473                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6474                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6475                Style);
6476 
6477   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6478                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6479                "    + cc;",
6480                Style);
6481   verifyFormat("int a = aa\n"
6482                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6483                "        * cccccccccccccccccccccccccccccccccccc;\n",
6484                Style);
6485 
6486   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6487   verifyFormat("return (a > b\n"
6488                "    // comment1\n"
6489                "    // comment2\n"
6490                "    || c);",
6491                Style);
6492 }
6493 
6494 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6495   FormatStyle Style = getLLVMStyle();
6496   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6497   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6498                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6499                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6500                Style);
6501 }
6502 
6503 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6504   FormatStyle Style = getLLVMStyleWithColumns(40);
6505   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6506   Style.BinPackArguments = false;
6507   verifyFormat("void test() {\n"
6508                "  someFunction(\n"
6509                "      this + argument + is + quite\n"
6510                "      + long + so + it + gets + wrapped\n"
6511                "      + but + remains + bin - packed);\n"
6512                "}",
6513                Style);
6514   verifyFormat("void test() {\n"
6515                "  someFunction(arg1,\n"
6516                "               this + argument + is\n"
6517                "                   + quite + long + so\n"
6518                "                   + it + gets + wrapped\n"
6519                "                   + but + remains + bin\n"
6520                "                   - packed,\n"
6521                "               arg3);\n"
6522                "}",
6523                Style);
6524   verifyFormat("void test() {\n"
6525                "  someFunction(\n"
6526                "      arg1,\n"
6527                "      this + argument + has\n"
6528                "          + anotherFunc(nested,\n"
6529                "                        calls + whose\n"
6530                "                            + arguments\n"
6531                "                            + are + also\n"
6532                "                            + wrapped,\n"
6533                "                        in + addition)\n"
6534                "          + to + being + bin - packed,\n"
6535                "      arg3);\n"
6536                "}",
6537                Style);
6538 
6539   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6540   verifyFormat("void test() {\n"
6541                "  someFunction(\n"
6542                "      arg1,\n"
6543                "      this + argument + has +\n"
6544                "          anotherFunc(nested,\n"
6545                "                      calls + whose +\n"
6546                "                          arguments +\n"
6547                "                          are + also +\n"
6548                "                          wrapped,\n"
6549                "                      in + addition) +\n"
6550                "          to + being + bin - packed,\n"
6551                "      arg3);\n"
6552                "}",
6553                Style);
6554 }
6555 
6556 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) {
6557   auto Style = getLLVMStyleWithColumns(45);
6558   EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None);
6559   verifyFormat("bool b =\n"
6560                "    is_default_constructible_v<hash<T>> and\n"
6561                "    is_copy_constructible_v<hash<T>> and\n"
6562                "    is_move_constructible_v<hash<T>> and\n"
6563                "    is_copy_assignable_v<hash<T>> and\n"
6564                "    is_move_assignable_v<hash<T>> and\n"
6565                "    is_destructible_v<hash<T>> and\n"
6566                "    is_swappable_v<hash<T>> and\n"
6567                "    is_callable_v<hash<T>(T)>;",
6568                Style);
6569 
6570   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6571   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6572                "         and is_copy_constructible_v<hash<T>>\n"
6573                "         and is_move_constructible_v<hash<T>>\n"
6574                "         and is_copy_assignable_v<hash<T>>\n"
6575                "         and is_move_assignable_v<hash<T>>\n"
6576                "         and is_destructible_v<hash<T>>\n"
6577                "         and is_swappable_v<hash<T>>\n"
6578                "         and is_callable_v<hash<T>(T)>;",
6579                Style);
6580 
6581   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6582   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6583                "         and is_copy_constructible_v<hash<T>>\n"
6584                "         and is_move_constructible_v<hash<T>>\n"
6585                "         and is_copy_assignable_v<hash<T>>\n"
6586                "         and is_move_assignable_v<hash<T>>\n"
6587                "         and is_destructible_v<hash<T>>\n"
6588                "         and is_swappable_v<hash<T>>\n"
6589                "         and is_callable_v<hash<T>(T)>;",
6590                Style);
6591 }
6592 
6593 TEST_F(FormatTest, ConstructorInitializers) {
6594   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6595   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6596                getLLVMStyleWithColumns(45));
6597   verifyFormat("Constructor()\n"
6598                "    : Inttializer(FitsOnTheLine) {}",
6599                getLLVMStyleWithColumns(44));
6600   verifyFormat("Constructor()\n"
6601                "    : Inttializer(FitsOnTheLine) {}",
6602                getLLVMStyleWithColumns(43));
6603 
6604   verifyFormat("template <typename T>\n"
6605                "Constructor() : Initializer(FitsOnTheLine) {}",
6606                getLLVMStyleWithColumns(45));
6607 
6608   verifyFormat(
6609       "SomeClass::Constructor()\n"
6610       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6611 
6612   verifyFormat(
6613       "SomeClass::Constructor()\n"
6614       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6615       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6616   verifyFormat(
6617       "SomeClass::Constructor()\n"
6618       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6619       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6620   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6621                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6622                "    : aaaaaaaaaa(aaaaaa) {}");
6623 
6624   verifyFormat("Constructor()\n"
6625                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6626                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6627                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6628                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6629 
6630   verifyFormat("Constructor()\n"
6631                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6632                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6633 
6634   verifyFormat("Constructor(int Parameter = 0)\n"
6635                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6636                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6637   verifyFormat("Constructor()\n"
6638                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6639                "}",
6640                getLLVMStyleWithColumns(60));
6641   verifyFormat("Constructor()\n"
6642                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6643                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6644 
6645   // Here a line could be saved by splitting the second initializer onto two
6646   // lines, but that is not desirable.
6647   verifyFormat("Constructor()\n"
6648                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6649                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6650                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6651 
6652   FormatStyle OnePerLine = getLLVMStyle();
6653   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6654   verifyFormat("MyClass::MyClass()\n"
6655                "    : a(a),\n"
6656                "      b(b),\n"
6657                "      c(c) {}",
6658                OnePerLine);
6659   verifyFormat("MyClass::MyClass()\n"
6660                "    : a(a), // comment\n"
6661                "      b(b),\n"
6662                "      c(c) {}",
6663                OnePerLine);
6664   verifyFormat("MyClass::MyClass(int a)\n"
6665                "    : b(a),      // comment\n"
6666                "      c(a + 1) { // lined up\n"
6667                "}",
6668                OnePerLine);
6669   verifyFormat("Constructor()\n"
6670                "    : a(b, b, b) {}",
6671                OnePerLine);
6672   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6673   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6674   verifyFormat("SomeClass::Constructor()\n"
6675                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6676                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6677                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6678                OnePerLine);
6679   verifyFormat("SomeClass::Constructor()\n"
6680                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6681                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6682                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6683                OnePerLine);
6684   verifyFormat("MyClass::MyClass(int var)\n"
6685                "    : some_var_(var),            // 4 space indent\n"
6686                "      some_other_var_(var + 1) { // lined up\n"
6687                "}",
6688                OnePerLine);
6689   verifyFormat("Constructor()\n"
6690                "    : aaaaa(aaaaaa),\n"
6691                "      aaaaa(aaaaaa),\n"
6692                "      aaaaa(aaaaaa),\n"
6693                "      aaaaa(aaaaaa),\n"
6694                "      aaaaa(aaaaaa) {}",
6695                OnePerLine);
6696   verifyFormat("Constructor()\n"
6697                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6698                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6699                OnePerLine);
6700   OnePerLine.BinPackParameters = false;
6701   verifyFormat(
6702       "Constructor()\n"
6703       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6704       "          aaaaaaaaaaa().aaa(),\n"
6705       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6706       OnePerLine);
6707   OnePerLine.ColumnLimit = 60;
6708   verifyFormat("Constructor()\n"
6709                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6710                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6711                OnePerLine);
6712 
6713   EXPECT_EQ("Constructor()\n"
6714             "    : // Comment forcing unwanted break.\n"
6715             "      aaaa(aaaa) {}",
6716             format("Constructor() :\n"
6717                    "    // Comment forcing unwanted break.\n"
6718                    "    aaaa(aaaa) {}"));
6719 }
6720 
6721 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6722   FormatStyle Style = getLLVMStyleWithColumns(60);
6723   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6724   Style.BinPackParameters = false;
6725 
6726   for (int i = 0; i < 4; ++i) {
6727     // Test all combinations of parameters that should not have an effect.
6728     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6729     Style.AllowAllArgumentsOnNextLine = i & 2;
6730 
6731     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6732     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6733     verifyFormat("Constructor()\n"
6734                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6735                  Style);
6736     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6737 
6738     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6739     verifyFormat("Constructor()\n"
6740                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6741                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6742                  Style);
6743     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6744 
6745     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6746     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6747     verifyFormat("Constructor()\n"
6748                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6749                  Style);
6750 
6751     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6752     verifyFormat("Constructor()\n"
6753                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6754                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6755                  Style);
6756 
6757     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6758     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6759     verifyFormat("Constructor() :\n"
6760                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6761                  Style);
6762 
6763     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6764     verifyFormat("Constructor() :\n"
6765                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6766                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6767                  Style);
6768   }
6769 
6770   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6771   // AllowAllConstructorInitializersOnNextLine in all
6772   // BreakConstructorInitializers modes
6773   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6774   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6775   verifyFormat("SomeClassWithALongName::Constructor(\n"
6776                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6777                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6778                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6779                Style);
6780 
6781   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6782   verifyFormat("SomeClassWithALongName::Constructor(\n"
6783                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6784                "    int bbbbbbbbbbbbb,\n"
6785                "    int cccccccccccccccc)\n"
6786                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6787                Style);
6788 
6789   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6790   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6791   verifyFormat("SomeClassWithALongName::Constructor(\n"
6792                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6793                "    int bbbbbbbbbbbbb)\n"
6794                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6795                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6796                Style);
6797 
6798   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6799 
6800   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6801   verifyFormat("SomeClassWithALongName::Constructor(\n"
6802                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6803                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6804                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6805                Style);
6806 
6807   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6808   verifyFormat("SomeClassWithALongName::Constructor(\n"
6809                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6810                "    int bbbbbbbbbbbbb,\n"
6811                "    int cccccccccccccccc)\n"
6812                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6813                Style);
6814 
6815   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6816   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6817   verifyFormat("SomeClassWithALongName::Constructor(\n"
6818                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6819                "    int bbbbbbbbbbbbb)\n"
6820                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6821                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6822                Style);
6823 
6824   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6825   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6826   verifyFormat("SomeClassWithALongName::Constructor(\n"
6827                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6828                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6829                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6830                Style);
6831 
6832   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6833   verifyFormat("SomeClassWithALongName::Constructor(\n"
6834                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6835                "    int bbbbbbbbbbbbb,\n"
6836                "    int cccccccccccccccc) :\n"
6837                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6838                Style);
6839 
6840   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6841   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6842   verifyFormat("SomeClassWithALongName::Constructor(\n"
6843                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6844                "    int bbbbbbbbbbbbb) :\n"
6845                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6846                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6847                Style);
6848 }
6849 
6850 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6851   FormatStyle Style = getLLVMStyleWithColumns(60);
6852   Style.BinPackArguments = false;
6853   for (int i = 0; i < 4; ++i) {
6854     // Test all combinations of parameters that should not have an effect.
6855     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6856     Style.PackConstructorInitializers =
6857         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6858 
6859     Style.AllowAllArgumentsOnNextLine = true;
6860     verifyFormat("void foo() {\n"
6861                  "  FunctionCallWithReallyLongName(\n"
6862                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6863                  "}",
6864                  Style);
6865     Style.AllowAllArgumentsOnNextLine = false;
6866     verifyFormat("void foo() {\n"
6867                  "  FunctionCallWithReallyLongName(\n"
6868                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6869                  "      bbbbbbbbbbbb);\n"
6870                  "}",
6871                  Style);
6872 
6873     Style.AllowAllArgumentsOnNextLine = true;
6874     verifyFormat("void foo() {\n"
6875                  "  auto VariableWithReallyLongName = {\n"
6876                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6877                  "}",
6878                  Style);
6879     Style.AllowAllArgumentsOnNextLine = false;
6880     verifyFormat("void foo() {\n"
6881                  "  auto VariableWithReallyLongName = {\n"
6882                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6883                  "      bbbbbbbbbbbb};\n"
6884                  "}",
6885                  Style);
6886   }
6887 
6888   // This parameter should not affect declarations.
6889   Style.BinPackParameters = false;
6890   Style.AllowAllArgumentsOnNextLine = false;
6891   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6892   verifyFormat("void FunctionCallWithReallyLongName(\n"
6893                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6894                Style);
6895   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6896   verifyFormat("void FunctionCallWithReallyLongName(\n"
6897                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6898                "    int bbbbbbbbbbbb);",
6899                Style);
6900 }
6901 
6902 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6903   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6904   // and BAS_Align.
6905   FormatStyle Style = getLLVMStyleWithColumns(35);
6906   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6907                     "void functionDecl(int A, int B, int C);";
6908   Style.AllowAllArgumentsOnNextLine = false;
6909   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6910   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6911                       "    paramC);\n"
6912                       "void functionDecl(int A, int B,\n"
6913                       "    int C);"),
6914             format(Input, Style));
6915   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6916   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6917                       "             paramC);\n"
6918                       "void functionDecl(int A, int B,\n"
6919                       "                  int C);"),
6920             format(Input, Style));
6921   // However, BAS_AlwaysBreak should take precedence over
6922   // AllowAllArgumentsOnNextLine.
6923   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6924   EXPECT_EQ(StringRef("functionCall(\n"
6925                       "    paramA, paramB, paramC);\n"
6926                       "void functionDecl(\n"
6927                       "    int A, int B, int C);"),
6928             format(Input, Style));
6929 
6930   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6931   // first argument.
6932   Style.AllowAllArgumentsOnNextLine = true;
6933   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6934   EXPECT_EQ(StringRef("functionCall(\n"
6935                       "    paramA, paramB, paramC);\n"
6936                       "void functionDecl(\n"
6937                       "    int A, int B, int C);"),
6938             format(Input, Style));
6939   // It wouldn't fit on one line with aligned parameters so this setting
6940   // doesn't change anything for BAS_Align.
6941   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6942   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6943                       "             paramC);\n"
6944                       "void functionDecl(int A, int B,\n"
6945                       "                  int C);"),
6946             format(Input, Style));
6947   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6948   EXPECT_EQ(StringRef("functionCall(\n"
6949                       "    paramA, paramB, paramC);\n"
6950                       "void functionDecl(\n"
6951                       "    int A, int B, int C);"),
6952             format(Input, Style));
6953 }
6954 
6955 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6956   FormatStyle Style = getLLVMStyle();
6957   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6958 
6959   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6960   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6961                getStyleWithColumns(Style, 45));
6962   verifyFormat("Constructor() :\n"
6963                "    Initializer(FitsOnTheLine) {}",
6964                getStyleWithColumns(Style, 44));
6965   verifyFormat("Constructor() :\n"
6966                "    Initializer(FitsOnTheLine) {}",
6967                getStyleWithColumns(Style, 43));
6968 
6969   verifyFormat("template <typename T>\n"
6970                "Constructor() : Initializer(FitsOnTheLine) {}",
6971                getStyleWithColumns(Style, 50));
6972   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6973   verifyFormat(
6974       "SomeClass::Constructor() :\n"
6975       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6976       Style);
6977 
6978   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6979   verifyFormat(
6980       "SomeClass::Constructor() :\n"
6981       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6982       Style);
6983 
6984   verifyFormat(
6985       "SomeClass::Constructor() :\n"
6986       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6987       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6988       Style);
6989   verifyFormat(
6990       "SomeClass::Constructor() :\n"
6991       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6992       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6993       Style);
6994   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6995                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6996                "    aaaaaaaaaa(aaaaaa) {}",
6997                Style);
6998 
6999   verifyFormat("Constructor() :\n"
7000                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7001                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7002                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7003                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
7004                Style);
7005 
7006   verifyFormat("Constructor() :\n"
7007                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7008                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7009                Style);
7010 
7011   verifyFormat("Constructor(int Parameter = 0) :\n"
7012                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
7013                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
7014                Style);
7015   verifyFormat("Constructor() :\n"
7016                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
7017                "}",
7018                getStyleWithColumns(Style, 60));
7019   verifyFormat("Constructor() :\n"
7020                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7021                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
7022                Style);
7023 
7024   // Here a line could be saved by splitting the second initializer onto two
7025   // lines, but that is not desirable.
7026   verifyFormat("Constructor() :\n"
7027                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
7028                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
7029                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7030                Style);
7031 
7032   FormatStyle OnePerLine = Style;
7033   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
7034   verifyFormat("SomeClass::Constructor() :\n"
7035                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7036                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7037                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7038                OnePerLine);
7039   verifyFormat("SomeClass::Constructor() :\n"
7040                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
7041                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7042                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7043                OnePerLine);
7044   verifyFormat("MyClass::MyClass(int var) :\n"
7045                "    some_var_(var),            // 4 space indent\n"
7046                "    some_other_var_(var + 1) { // lined up\n"
7047                "}",
7048                OnePerLine);
7049   verifyFormat("Constructor() :\n"
7050                "    aaaaa(aaaaaa),\n"
7051                "    aaaaa(aaaaaa),\n"
7052                "    aaaaa(aaaaaa),\n"
7053                "    aaaaa(aaaaaa),\n"
7054                "    aaaaa(aaaaaa) {}",
7055                OnePerLine);
7056   verifyFormat("Constructor() :\n"
7057                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
7058                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
7059                OnePerLine);
7060   OnePerLine.BinPackParameters = false;
7061   verifyFormat("Constructor() :\n"
7062                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7063                "        aaaaaaaaaaa().aaa(),\n"
7064                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7065                OnePerLine);
7066   OnePerLine.ColumnLimit = 60;
7067   verifyFormat("Constructor() :\n"
7068                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
7069                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
7070                OnePerLine);
7071 
7072   EXPECT_EQ("Constructor() :\n"
7073             "    // Comment forcing unwanted break.\n"
7074             "    aaaa(aaaa) {}",
7075             format("Constructor() :\n"
7076                    "    // Comment forcing unwanted break.\n"
7077                    "    aaaa(aaaa) {}",
7078                    Style));
7079 
7080   Style.ColumnLimit = 0;
7081   verifyFormat("SomeClass::Constructor() :\n"
7082                "    a(a) {}",
7083                Style);
7084   verifyFormat("SomeClass::Constructor() noexcept :\n"
7085                "    a(a) {}",
7086                Style);
7087   verifyFormat("SomeClass::Constructor() :\n"
7088                "    a(a), b(b), c(c) {}",
7089                Style);
7090   verifyFormat("SomeClass::Constructor() :\n"
7091                "    a(a) {\n"
7092                "  foo();\n"
7093                "  bar();\n"
7094                "}",
7095                Style);
7096 
7097   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
7098   verifyFormat("SomeClass::Constructor() :\n"
7099                "    a(a), b(b), c(c) {\n"
7100                "}",
7101                Style);
7102   verifyFormat("SomeClass::Constructor() :\n"
7103                "    a(a) {\n"
7104                "}",
7105                Style);
7106 
7107   Style.ColumnLimit = 80;
7108   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
7109   Style.ConstructorInitializerIndentWidth = 2;
7110   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
7111   verifyFormat("SomeClass::Constructor() :\n"
7112                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7113                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
7114                Style);
7115 
7116   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
7117   // well
7118   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
7119   verifyFormat(
7120       "class SomeClass\n"
7121       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7122       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7123       Style);
7124   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
7125   verifyFormat(
7126       "class SomeClass\n"
7127       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7128       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7129       Style);
7130   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
7131   verifyFormat(
7132       "class SomeClass :\n"
7133       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7134       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7135       Style);
7136   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
7137   verifyFormat(
7138       "class SomeClass\n"
7139       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7140       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7141       Style);
7142 }
7143 
7144 #ifndef EXPENSIVE_CHECKS
7145 // Expensive checks enables libstdc++ checking which includes validating the
7146 // state of ranges used in std::priority_queue - this blows out the
7147 // runtime/scalability of the function and makes this test unacceptably slow.
7148 TEST_F(FormatTest, MemoizationTests) {
7149   // This breaks if the memoization lookup does not take \c Indent and
7150   // \c LastSpace into account.
7151   verifyFormat(
7152       "extern CFRunLoopTimerRef\n"
7153       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
7154       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
7155       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
7156       "                     CFRunLoopTimerContext *context) {}");
7157 
7158   // Deep nesting somewhat works around our memoization.
7159   verifyFormat(
7160       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7161       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7162       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7163       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7164       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
7165       getLLVMStyleWithColumns(65));
7166   verifyFormat(
7167       "aaaaa(\n"
7168       "    aaaaa,\n"
7169       "    aaaaa(\n"
7170       "        aaaaa,\n"
7171       "        aaaaa(\n"
7172       "            aaaaa,\n"
7173       "            aaaaa(\n"
7174       "                aaaaa,\n"
7175       "                aaaaa(\n"
7176       "                    aaaaa,\n"
7177       "                    aaaaa(\n"
7178       "                        aaaaa,\n"
7179       "                        aaaaa(\n"
7180       "                            aaaaa,\n"
7181       "                            aaaaa(\n"
7182       "                                aaaaa,\n"
7183       "                                aaaaa(\n"
7184       "                                    aaaaa,\n"
7185       "                                    aaaaa(\n"
7186       "                                        aaaaa,\n"
7187       "                                        aaaaa(\n"
7188       "                                            aaaaa,\n"
7189       "                                            aaaaa(\n"
7190       "                                                aaaaa,\n"
7191       "                                                aaaaa))))))))))));",
7192       getLLVMStyleWithColumns(65));
7193   verifyFormat(
7194       "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
7195       "                                  a),\n"
7196       "                                a),\n"
7197       "                              a),\n"
7198       "                            a),\n"
7199       "                          a),\n"
7200       "                        a),\n"
7201       "                      a),\n"
7202       "                    a),\n"
7203       "                  a),\n"
7204       "                a),\n"
7205       "              a),\n"
7206       "            a),\n"
7207       "          a),\n"
7208       "        a),\n"
7209       "      a),\n"
7210       "    a),\n"
7211       "  a)",
7212       getLLVMStyleWithColumns(65));
7213 
7214   // This test takes VERY long when memoization is broken.
7215   FormatStyle OnePerLine = getLLVMStyle();
7216   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7217   OnePerLine.BinPackParameters = false;
7218   std::string input = "Constructor()\n"
7219                       "    : aaaa(a,\n";
7220   for (unsigned i = 0, e = 80; i != e; ++i)
7221     input += "           a,\n";
7222   input += "           a) {}";
7223   verifyFormat(input, OnePerLine);
7224 }
7225 #endif
7226 
7227 TEST_F(FormatTest, BreaksAsHighAsPossible) {
7228   verifyFormat(
7229       "void f() {\n"
7230       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
7231       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
7232       "    f();\n"
7233       "}");
7234   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
7235                "    Intervals[i - 1].getRange().getLast()) {\n}");
7236 }
7237 
7238 TEST_F(FormatTest, BreaksFunctionDeclarations) {
7239   // Principially, we break function declarations in a certain order:
7240   // 1) break amongst arguments.
7241   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
7242                "                              Cccccccccccccc cccccccccccccc);");
7243   verifyFormat("template <class TemplateIt>\n"
7244                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
7245                "                            TemplateIt *stop) {}");
7246 
7247   // 2) break after return type.
7248   verifyFormat(
7249       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7250       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
7251       getGoogleStyle());
7252 
7253   // 3) break after (.
7254   verifyFormat(
7255       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
7256       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
7257       getGoogleStyle());
7258 
7259   // 4) break before after nested name specifiers.
7260   verifyFormat(
7261       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7262       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
7263       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
7264       getGoogleStyle());
7265 
7266   // However, there are exceptions, if a sufficient amount of lines can be
7267   // saved.
7268   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
7269   // more adjusting.
7270   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7271                "                                  Cccccccccccccc cccccccccc,\n"
7272                "                                  Cccccccccccccc cccccccccc,\n"
7273                "                                  Cccccccccccccc cccccccccc,\n"
7274                "                                  Cccccccccccccc cccccccccc);");
7275   verifyFormat(
7276       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7277       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7278       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7279       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
7280       getGoogleStyle());
7281   verifyFormat(
7282       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7283       "                                          Cccccccccccccc cccccccccc,\n"
7284       "                                          Cccccccccccccc cccccccccc,\n"
7285       "                                          Cccccccccccccc cccccccccc,\n"
7286       "                                          Cccccccccccccc cccccccccc,\n"
7287       "                                          Cccccccccccccc cccccccccc,\n"
7288       "                                          Cccccccccccccc cccccccccc);");
7289   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7290                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7291                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7292                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7293                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
7294 
7295   // Break after multi-line parameters.
7296   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7297                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7298                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7299                "    bbbb bbbb);");
7300   verifyFormat("void SomeLoooooooooooongFunction(\n"
7301                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
7302                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7303                "    int bbbbbbbbbbbbb);");
7304 
7305   // Treat overloaded operators like other functions.
7306   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7307                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
7308   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7309                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
7310   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7311                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
7312   verifyGoogleFormat(
7313       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
7314       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7315   verifyGoogleFormat(
7316       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
7317       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7318   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7319                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7320   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
7321                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7322   verifyGoogleFormat(
7323       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
7324       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7325       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
7326   verifyGoogleFormat("template <typename T>\n"
7327                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7328                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
7329                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
7330 
7331   FormatStyle Style = getLLVMStyle();
7332   Style.PointerAlignment = FormatStyle::PAS_Left;
7333   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7334                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
7335                Style);
7336   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
7337                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7338                Style);
7339 }
7340 
7341 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
7342   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
7343   // Prefer keeping `::` followed by `operator` together.
7344   EXPECT_EQ("const aaaa::bbbbbbb &\n"
7345             "ccccccccc::operator++() {\n"
7346             "  stuff();\n"
7347             "}",
7348             format("const aaaa::bbbbbbb\n"
7349                    "&ccccccccc::operator++() { stuff(); }",
7350                    getLLVMStyleWithColumns(40)));
7351 }
7352 
7353 TEST_F(FormatTest, TrailingReturnType) {
7354   verifyFormat("auto foo() -> int;\n");
7355   // correct trailing return type spacing
7356   verifyFormat("auto operator->() -> int;\n");
7357   verifyFormat("auto operator++(int) -> int;\n");
7358 
7359   verifyFormat("struct S {\n"
7360                "  auto bar() const -> int;\n"
7361                "};");
7362   verifyFormat("template <size_t Order, typename T>\n"
7363                "auto load_img(const std::string &filename)\n"
7364                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
7365   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
7366                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
7367   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
7368   verifyFormat("template <typename T>\n"
7369                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
7370                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
7371 
7372   // Not trailing return types.
7373   verifyFormat("void f() { auto a = b->c(); }");
7374   verifyFormat("auto a = p->foo();");
7375   verifyFormat("int a = p->foo();");
7376   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
7377 }
7378 
7379 TEST_F(FormatTest, DeductionGuides) {
7380   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
7381   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
7382   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
7383   verifyFormat(
7384       "template <class... T>\n"
7385       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
7386   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
7387   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
7388   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
7389   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
7390   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
7391   verifyFormat("template <class T> x() -> x<1>;");
7392   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
7393 
7394   // Ensure not deduction guides.
7395   verifyFormat("c()->f<int>();");
7396   verifyFormat("x()->foo<1>;");
7397   verifyFormat("x = p->foo<3>();");
7398   verifyFormat("x()->x<1>();");
7399   verifyFormat("x()->x<1>;");
7400 }
7401 
7402 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
7403   // Avoid breaking before trailing 'const' or other trailing annotations, if
7404   // they are not function-like.
7405   FormatStyle Style = getGoogleStyleWithColumns(47);
7406   verifyFormat("void someLongFunction(\n"
7407                "    int someLoooooooooooooongParameter) const {\n}",
7408                getLLVMStyleWithColumns(47));
7409   verifyFormat("LoooooongReturnType\n"
7410                "someLoooooooongFunction() const {}",
7411                getLLVMStyleWithColumns(47));
7412   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
7413                "    const {}",
7414                Style);
7415   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7416                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
7417   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7418                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
7419   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7420                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
7421   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
7422                "                   aaaaaaaaaaa aaaaa) const override;");
7423   verifyGoogleFormat(
7424       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7425       "    const override;");
7426 
7427   // Even if the first parameter has to be wrapped.
7428   verifyFormat("void someLongFunction(\n"
7429                "    int someLongParameter) const {}",
7430                getLLVMStyleWithColumns(46));
7431   verifyFormat("void someLongFunction(\n"
7432                "    int someLongParameter) const {}",
7433                Style);
7434   verifyFormat("void someLongFunction(\n"
7435                "    int someLongParameter) override {}",
7436                Style);
7437   verifyFormat("void someLongFunction(\n"
7438                "    int someLongParameter) OVERRIDE {}",
7439                Style);
7440   verifyFormat("void someLongFunction(\n"
7441                "    int someLongParameter) final {}",
7442                Style);
7443   verifyFormat("void someLongFunction(\n"
7444                "    int someLongParameter) FINAL {}",
7445                Style);
7446   verifyFormat("void someLongFunction(\n"
7447                "    int parameter) const override {}",
7448                Style);
7449 
7450   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7451   verifyFormat("void someLongFunction(\n"
7452                "    int someLongParameter) const\n"
7453                "{\n"
7454                "}",
7455                Style);
7456 
7457   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7458   verifyFormat("void someLongFunction(\n"
7459                "    int someLongParameter) const\n"
7460                "  {\n"
7461                "  }",
7462                Style);
7463 
7464   // Unless these are unknown annotations.
7465   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7466                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7467                "    LONG_AND_UGLY_ANNOTATION;");
7468 
7469   // Breaking before function-like trailing annotations is fine to keep them
7470   // close to their arguments.
7471   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7472                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7473   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7474                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7475   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7476                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7477   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7478                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7479   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7480 
7481   verifyFormat(
7482       "void aaaaaaaaaaaaaaaaaa()\n"
7483       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7484       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7485   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7486                "    __attribute__((unused));");
7487   verifyGoogleFormat(
7488       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7489       "    GUARDED_BY(aaaaaaaaaaaa);");
7490   verifyGoogleFormat(
7491       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7492       "    GUARDED_BY(aaaaaaaaaaaa);");
7493   verifyGoogleFormat(
7494       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7495       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7496   verifyGoogleFormat(
7497       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7498       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7499 }
7500 
7501 TEST_F(FormatTest, FunctionAnnotations) {
7502   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7503                "int OldFunction(const string &parameter) {}");
7504   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7505                "string OldFunction(const string &parameter) {}");
7506   verifyFormat("template <typename T>\n"
7507                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7508                "string OldFunction(const string &parameter) {}");
7509 
7510   // Not function annotations.
7511   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7512                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7513   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7514                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7515   verifyFormat("MACRO(abc).function() // wrap\n"
7516                "    << abc;");
7517   verifyFormat("MACRO(abc)->function() // wrap\n"
7518                "    << abc;");
7519   verifyFormat("MACRO(abc)::function() // wrap\n"
7520                "    << abc;");
7521 }
7522 
7523 TEST_F(FormatTest, BreaksDesireably) {
7524   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7525                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7526                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7527   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7528                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7529                "}");
7530 
7531   verifyFormat(
7532       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7533       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7534 
7535   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7536                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7537                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7538 
7539   verifyFormat(
7540       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7541       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7542       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7543       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7544       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7545 
7546   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7547                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7548 
7549   verifyFormat(
7550       "void f() {\n"
7551       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7552       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7553       "}");
7554   verifyFormat(
7555       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7556       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7557   verifyFormat(
7558       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7559       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7560   verifyFormat(
7561       "aaaaaa(aaa,\n"
7562       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7563       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7564       "       aaaa);");
7565   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7566                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7567                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7568 
7569   // Indent consistently independent of call expression and unary operator.
7570   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7571                "    dddddddddddddddddddddddddddddd));");
7572   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7573                "    dddddddddddddddddddddddddddddd));");
7574   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7575                "    dddddddddddddddddddddddddddddd));");
7576 
7577   // This test case breaks on an incorrect memoization, i.e. an optimization not
7578   // taking into account the StopAt value.
7579   verifyFormat(
7580       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7581       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7582       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7583       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7584 
7585   verifyFormat("{\n  {\n    {\n"
7586                "      Annotation.SpaceRequiredBefore =\n"
7587                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7588                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7589                "    }\n  }\n}");
7590 
7591   // Break on an outer level if there was a break on an inner level.
7592   EXPECT_EQ("f(g(h(a, // comment\n"
7593             "      b, c),\n"
7594             "    d, e),\n"
7595             "  x, y);",
7596             format("f(g(h(a, // comment\n"
7597                    "    b, c), d, e), x, y);"));
7598 
7599   // Prefer breaking similar line breaks.
7600   verifyFormat(
7601       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7602       "                             NSTrackingMouseEnteredAndExited |\n"
7603       "                             NSTrackingActiveAlways;");
7604 }
7605 
7606 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7607   FormatStyle NoBinPacking = getGoogleStyle();
7608   NoBinPacking.BinPackParameters = false;
7609   NoBinPacking.BinPackArguments = true;
7610   verifyFormat("void f() {\n"
7611                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7612                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7613                "}",
7614                NoBinPacking);
7615   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7616                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7617                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7618                NoBinPacking);
7619 
7620   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7621   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7622                "                        vector<int> bbbbbbbbbbbbbbb);",
7623                NoBinPacking);
7624   // FIXME: This behavior difference is probably not wanted. However, currently
7625   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7626   // template arguments from BreakBeforeParameter being set because of the
7627   // one-per-line formatting.
7628   verifyFormat(
7629       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7630       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7631       NoBinPacking);
7632   verifyFormat(
7633       "void fffffffffff(\n"
7634       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7635       "        aaaaaaaaaa);");
7636 }
7637 
7638 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7639   FormatStyle NoBinPacking = getGoogleStyle();
7640   NoBinPacking.BinPackParameters = false;
7641   NoBinPacking.BinPackArguments = false;
7642   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7643                "  aaaaaaaaaaaaaaaaaaaa,\n"
7644                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7645                NoBinPacking);
7646   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7647                "        aaaaaaaaaaaaa,\n"
7648                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7649                NoBinPacking);
7650   verifyFormat(
7651       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7652       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7653       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7654       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7655       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7656       NoBinPacking);
7657   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7658                "    .aaaaaaaaaaaaaaaaaa();",
7659                NoBinPacking);
7660   verifyFormat("void f() {\n"
7661                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7662                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7663                "}",
7664                NoBinPacking);
7665 
7666   verifyFormat(
7667       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7668       "             aaaaaaaaaaaa,\n"
7669       "             aaaaaaaaaaaa);",
7670       NoBinPacking);
7671   verifyFormat(
7672       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7673       "                               ddddddddddddddddddddddddddddd),\n"
7674       "             test);",
7675       NoBinPacking);
7676 
7677   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7678                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7679                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7680                "    aaaaaaaaaaaaaaaaaa;",
7681                NoBinPacking);
7682   verifyFormat("a(\"a\"\n"
7683                "  \"a\",\n"
7684                "  a);");
7685 
7686   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7687   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7688                "                aaaaaaaaa,\n"
7689                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7690                NoBinPacking);
7691   verifyFormat(
7692       "void f() {\n"
7693       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7694       "      .aaaaaaa();\n"
7695       "}",
7696       NoBinPacking);
7697   verifyFormat(
7698       "template <class SomeType, class SomeOtherType>\n"
7699       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7700       NoBinPacking);
7701 }
7702 
7703 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7704   FormatStyle Style = getLLVMStyleWithColumns(15);
7705   Style.ExperimentalAutoDetectBinPacking = true;
7706   EXPECT_EQ("aaa(aaaa,\n"
7707             "    aaaa,\n"
7708             "    aaaa);\n"
7709             "aaa(aaaa,\n"
7710             "    aaaa,\n"
7711             "    aaaa);",
7712             format("aaa(aaaa,\n" // one-per-line
7713                    "  aaaa,\n"
7714                    "    aaaa  );\n"
7715                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7716                    Style));
7717   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7718             "    aaaa);\n"
7719             "aaa(aaaa, aaaa,\n"
7720             "    aaaa);",
7721             format("aaa(aaaa,  aaaa,\n" // bin-packed
7722                    "    aaaa  );\n"
7723                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7724                    Style));
7725 }
7726 
7727 TEST_F(FormatTest, FormatsBuilderPattern) {
7728   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7729                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7730                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7731                "    .StartsWith(\".init\", ORDER_INIT)\n"
7732                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7733                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7734                "    .Default(ORDER_TEXT);\n");
7735 
7736   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7737                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7738   verifyFormat("aaaaaaa->aaaaaaa\n"
7739                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7740                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7741                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7742   verifyFormat(
7743       "aaaaaaa->aaaaaaa\n"
7744       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7745       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7746   verifyFormat(
7747       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7748       "    aaaaaaaaaaaaaa);");
7749   verifyFormat(
7750       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7751       "    aaaaaa->aaaaaaaaaaaa()\n"
7752       "        ->aaaaaaaaaaaaaaaa(\n"
7753       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7754       "        ->aaaaaaaaaaaaaaaaa();");
7755   verifyGoogleFormat(
7756       "void f() {\n"
7757       "  someo->Add((new util::filetools::Handler(dir))\n"
7758       "                 ->OnEvent1(NewPermanentCallback(\n"
7759       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7760       "                 ->OnEvent2(NewPermanentCallback(\n"
7761       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7762       "                 ->OnEvent3(NewPermanentCallback(\n"
7763       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7764       "                 ->OnEvent5(NewPermanentCallback(\n"
7765       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7766       "                 ->OnEvent6(NewPermanentCallback(\n"
7767       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7768       "}");
7769 
7770   verifyFormat(
7771       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7772   verifyFormat("aaaaaaaaaaaaaaa()\n"
7773                "    .aaaaaaaaaaaaaaa()\n"
7774                "    .aaaaaaaaaaaaaaa()\n"
7775                "    .aaaaaaaaaaaaaaa()\n"
7776                "    .aaaaaaaaaaaaaaa();");
7777   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7778                "    .aaaaaaaaaaaaaaa()\n"
7779                "    .aaaaaaaaaaaaaaa()\n"
7780                "    .aaaaaaaaaaaaaaa();");
7781   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7782                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7783                "    .aaaaaaaaaaaaaaa();");
7784   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7785                "    ->aaaaaaaaaaaaaae(0)\n"
7786                "    ->aaaaaaaaaaaaaaa();");
7787 
7788   // Don't linewrap after very short segments.
7789   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7790                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7791                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7792   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7793                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7794                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7795   verifyFormat("aaa()\n"
7796                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7797                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7798                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7799 
7800   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7801                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7802                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7803   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7804                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7805                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7806 
7807   // Prefer not to break after empty parentheses.
7808   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7809                "    First->LastNewlineOffset);");
7810 
7811   // Prefer not to create "hanging" indents.
7812   verifyFormat(
7813       "return !soooooooooooooome_map\n"
7814       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7815       "            .second;");
7816   verifyFormat(
7817       "return aaaaaaaaaaaaaaaa\n"
7818       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7819       "    .aaaa(aaaaaaaaaaaaaa);");
7820   // No hanging indent here.
7821   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7822                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7823   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7824                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7825   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7826                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7827                getLLVMStyleWithColumns(60));
7828   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7829                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7830                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7831                getLLVMStyleWithColumns(59));
7832   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7833                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7834                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7835 
7836   // Dont break if only closing statements before member call
7837   verifyFormat("test() {\n"
7838                "  ([]() -> {\n"
7839                "    int b = 32;\n"
7840                "    return 3;\n"
7841                "  }).foo();\n"
7842                "}");
7843   verifyFormat("test() {\n"
7844                "  (\n"
7845                "      []() -> {\n"
7846                "        int b = 32;\n"
7847                "        return 3;\n"
7848                "      },\n"
7849                "      foo, bar)\n"
7850                "      .foo();\n"
7851                "}");
7852   verifyFormat("test() {\n"
7853                "  ([]() -> {\n"
7854                "    int b = 32;\n"
7855                "    return 3;\n"
7856                "  })\n"
7857                "      .foo()\n"
7858                "      .bar();\n"
7859                "}");
7860   verifyFormat("test() {\n"
7861                "  ([]() -> {\n"
7862                "    int b = 32;\n"
7863                "    return 3;\n"
7864                "  })\n"
7865                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7866                "           \"bbbb\");\n"
7867                "}",
7868                getLLVMStyleWithColumns(30));
7869 }
7870 
7871 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7872   verifyFormat(
7873       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7874       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7875   verifyFormat(
7876       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7877       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7878 
7879   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7880                "    ccccccccccccccccccccccccc) {\n}");
7881   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7882                "    ccccccccccccccccccccccccc) {\n}");
7883 
7884   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7885                "    ccccccccccccccccccccccccc) {\n}");
7886   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7887                "    ccccccccccccccccccccccccc) {\n}");
7888 
7889   verifyFormat(
7890       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7891       "    ccccccccccccccccccccccccc) {\n}");
7892   verifyFormat(
7893       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7894       "    ccccccccccccccccccccccccc) {\n}");
7895 
7896   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7897                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7898                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7899                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7900   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7901                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7902                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7903                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7904 
7905   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7906                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7907                "    aaaaaaaaaaaaaaa != aa) {\n}");
7908   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7909                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7910                "    aaaaaaaaaaaaaaa != aa) {\n}");
7911 }
7912 
7913 TEST_F(FormatTest, BreaksAfterAssignments) {
7914   verifyFormat(
7915       "unsigned Cost =\n"
7916       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7917       "                        SI->getPointerAddressSpaceee());\n");
7918   verifyFormat(
7919       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7920       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7921 
7922   verifyFormat(
7923       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7924       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7925   verifyFormat("unsigned OriginalStartColumn =\n"
7926                "    SourceMgr.getSpellingColumnNumber(\n"
7927                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7928                "    1;");
7929 }
7930 
7931 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7932   FormatStyle Style = getLLVMStyle();
7933   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7934                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7935                Style);
7936 
7937   Style.PenaltyBreakAssignment = 20;
7938   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7939                "                                 cccccccccccccccccccccccccc;",
7940                Style);
7941 }
7942 
7943 TEST_F(FormatTest, AlignsAfterAssignments) {
7944   verifyFormat(
7945       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7946       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7947   verifyFormat(
7948       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7949       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7950   verifyFormat(
7951       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7952       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7953   verifyFormat(
7954       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7955       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7956   verifyFormat(
7957       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7958       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7959       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7960 }
7961 
7962 TEST_F(FormatTest, AlignsAfterReturn) {
7963   verifyFormat(
7964       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7965       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7966   verifyFormat(
7967       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7968       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7969   verifyFormat(
7970       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7971       "       aaaaaaaaaaaaaaaaaaaaaa();");
7972   verifyFormat(
7973       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7974       "        aaaaaaaaaaaaaaaaaaaaaa());");
7975   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7976                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7977   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7978                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7979                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7980   verifyFormat("return\n"
7981                "    // true if code is one of a or b.\n"
7982                "    code == a || code == b;");
7983 }
7984 
7985 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7986   verifyFormat(
7987       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7988       "                                                aaaaaaaaa aaaaaaa) {}");
7989   verifyFormat(
7990       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7991       "                                               aaaaaaaaaaa aaaaaaaaa);");
7992   verifyFormat(
7993       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7994       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7995   FormatStyle Style = getLLVMStyle();
7996   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7997   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7998                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7999                Style);
8000   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8001                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
8002                Style);
8003   verifyFormat("SomeLongVariableName->someFunction(\n"
8004                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
8005                Style);
8006   verifyFormat(
8007       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
8008       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8009       Style);
8010   verifyFormat(
8011       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
8012       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8013       Style);
8014   verifyFormat(
8015       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
8016       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8017       Style);
8018 
8019   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
8020                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
8021                "        b));",
8022                Style);
8023 
8024   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8025   Style.BinPackArguments = false;
8026   Style.BinPackParameters = false;
8027   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8028                "    aaaaaaaaaaa aaaaaaaa,\n"
8029                "    aaaaaaaaa aaaaaaa,\n"
8030                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8031                Style);
8032   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8033                "    aaaaaaaaaaa aaaaaaaaa,\n"
8034                "    aaaaaaaaaaa aaaaaaaaa,\n"
8035                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8036                Style);
8037   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
8038                "    aaaaaaaaaaaaaaa,\n"
8039                "    aaaaaaaaaaaaaaaaaaaaa,\n"
8040                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8041                Style);
8042   verifyFormat(
8043       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
8044       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8045       Style);
8046   verifyFormat(
8047       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
8048       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8049       Style);
8050   verifyFormat(
8051       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8052       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8053       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
8054       "    aaaaaaaaaaaaaaaa);",
8055       Style);
8056   verifyFormat(
8057       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8058       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8059       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
8060       "    aaaaaaaaaaaaaaaa);",
8061       Style);
8062 }
8063 
8064 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
8065   FormatStyle Style = getLLVMStyleWithColumns(40);
8066   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8067                "          bbbbbbbbbbbbbbbbbbbbbb);",
8068                Style);
8069   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
8070   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8071   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8072                "          bbbbbbbbbbbbbbbbbbbbbb);",
8073                Style);
8074   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8075   Style.AlignOperands = FormatStyle::OAS_Align;
8076   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8077                "          bbbbbbbbbbbbbbbbbbbbbb);",
8078                Style);
8079   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8080   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8081   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8082                "    bbbbbbbbbbbbbbbbbbbbbb);",
8083                Style);
8084 }
8085 
8086 TEST_F(FormatTest, BreaksConditionalExpressions) {
8087   verifyFormat(
8088       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8089       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8090       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8091   verifyFormat(
8092       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8093       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8094       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8095   verifyFormat(
8096       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8097       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8098   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
8099                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8100                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8101   verifyFormat(
8102       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
8103       "                                                    : aaaaaaaaaaaaa);");
8104   verifyFormat(
8105       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8106       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8107       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8108       "                   aaaaaaaaaaaaa);");
8109   verifyFormat(
8110       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8111       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8112       "                   aaaaaaaaaaaaa);");
8113   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8114                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8115                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8116                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8117                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8118   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8119                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8120                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8121                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8122                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8123                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8124                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8125   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8126                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8127                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8128                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8129                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8130   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8131                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8132                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8133   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8134                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8135                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8136                "        : aaaaaaaaaaaaaaaa;");
8137   verifyFormat(
8138       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8139       "    ? aaaaaaaaaaaaaaa\n"
8140       "    : aaaaaaaaaaaaaaa;");
8141   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8142                "          aaaaaaaaa\n"
8143                "      ? b\n"
8144                "      : c);");
8145   verifyFormat("return aaaa == bbbb\n"
8146                "           // comment\n"
8147                "           ? aaaa\n"
8148                "           : bbbb;");
8149   verifyFormat("unsigned Indent =\n"
8150                "    format(TheLine.First,\n"
8151                "           IndentForLevel[TheLine.Level] >= 0\n"
8152                "               ? IndentForLevel[TheLine.Level]\n"
8153                "               : TheLine * 2,\n"
8154                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8155                getLLVMStyleWithColumns(60));
8156   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8157                "                  ? aaaaaaaaaaaaaaa\n"
8158                "                  : bbbbbbbbbbbbbbb //\n"
8159                "                        ? ccccccccccccccc\n"
8160                "                        : ddddddddddddddd;");
8161   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8162                "                  ? aaaaaaaaaaaaaaa\n"
8163                "                  : (bbbbbbbbbbbbbbb //\n"
8164                "                         ? ccccccccccccccc\n"
8165                "                         : ddddddddddddddd);");
8166   verifyFormat(
8167       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8168       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8169       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
8170       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
8171       "                                      : aaaaaaaaaa;");
8172   verifyFormat(
8173       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8174       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
8175       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8176 
8177   FormatStyle NoBinPacking = getLLVMStyle();
8178   NoBinPacking.BinPackArguments = false;
8179   verifyFormat(
8180       "void f() {\n"
8181       "  g(aaa,\n"
8182       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8183       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8184       "        ? aaaaaaaaaaaaaaa\n"
8185       "        : aaaaaaaaaaaaaaa);\n"
8186       "}",
8187       NoBinPacking);
8188   verifyFormat(
8189       "void f() {\n"
8190       "  g(aaa,\n"
8191       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8192       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8193       "        ?: aaaaaaaaaaaaaaa);\n"
8194       "}",
8195       NoBinPacking);
8196 
8197   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
8198                "             // comment.\n"
8199                "             ccccccccccccccccccccccccccccccccccccccc\n"
8200                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8201                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
8202 
8203   // Assignments in conditional expressions. Apparently not uncommon :-(.
8204   verifyFormat("return a != b\n"
8205                "           // comment\n"
8206                "           ? a = b\n"
8207                "           : a = b;");
8208   verifyFormat("return a != b\n"
8209                "           // comment\n"
8210                "           ? a = a != b\n"
8211                "                     // comment\n"
8212                "                     ? a = b\n"
8213                "                     : a\n"
8214                "           : a;\n");
8215   verifyFormat("return a != b\n"
8216                "           // comment\n"
8217                "           ? a\n"
8218                "           : a = a != b\n"
8219                "                     // comment\n"
8220                "                     ? a = b\n"
8221                "                     : a;");
8222 
8223   // Chained conditionals
8224   FormatStyle Style = getLLVMStyleWithColumns(70);
8225   Style.AlignOperands = FormatStyle::OAS_Align;
8226   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8227                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8228                "                        : 3333333333333333;",
8229                Style);
8230   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8231                "       : bbbbbbbbbb     ? 2222222222222222\n"
8232                "                        : 3333333333333333;",
8233                Style);
8234   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
8235                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
8236                "                          : 3333333333333333;",
8237                Style);
8238   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8239                "       : bbbbbbbbbbbbbb ? 222222\n"
8240                "                        : 333333;",
8241                Style);
8242   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8243                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8244                "       : cccccccccccccc ? 3333333333333333\n"
8245                "                        : 4444444444444444;",
8246                Style);
8247   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
8248                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8249                "                        : 3333333333333333;",
8250                Style);
8251   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8252                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8253                "                        : (aaa ? bbb : ccc);",
8254                Style);
8255   verifyFormat(
8256       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8257       "                                             : cccccccccccccccccc)\n"
8258       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8259       "                        : 3333333333333333;",
8260       Style);
8261   verifyFormat(
8262       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8263       "                                             : cccccccccccccccccc)\n"
8264       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8265       "                        : 3333333333333333;",
8266       Style);
8267   verifyFormat(
8268       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8269       "                                             : dddddddddddddddddd)\n"
8270       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8271       "                        : 3333333333333333;",
8272       Style);
8273   verifyFormat(
8274       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8275       "                                             : dddddddddddddddddd)\n"
8276       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8277       "                        : 3333333333333333;",
8278       Style);
8279   verifyFormat(
8280       "return aaaaaaaaa        ? 1111111111111111\n"
8281       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8282       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8283       "                                             : dddddddddddddddddd)\n",
8284       Style);
8285   verifyFormat(
8286       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8287       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8288       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8289       "                                             : cccccccccccccccccc);",
8290       Style);
8291   verifyFormat(
8292       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8293       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8294       "                                             : eeeeeeeeeeeeeeeeee)\n"
8295       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8296       "                        : 3333333333333333;",
8297       Style);
8298   verifyFormat(
8299       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
8300       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8301       "                                             : eeeeeeeeeeeeeeeeee)\n"
8302       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8303       "                        : 3333333333333333;",
8304       Style);
8305   verifyFormat(
8306       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8307       "                           : cccccccccccc    ? dddddddddddddddddd\n"
8308       "                                             : eeeeeeeeeeeeeeeeee)\n"
8309       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8310       "                        : 3333333333333333;",
8311       Style);
8312   verifyFormat(
8313       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8314       "                                             : cccccccccccccccccc\n"
8315       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8316       "                        : 3333333333333333;",
8317       Style);
8318   verifyFormat(
8319       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8320       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
8321       "                                             : eeeeeeeeeeeeeeeeee\n"
8322       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8323       "                        : 3333333333333333;",
8324       Style);
8325   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
8326                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
8327                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
8328                "                                   : eeeeeeeeeeeeeeeeee)\n"
8329                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8330                "                             : 3333333333333333;",
8331                Style);
8332   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
8333                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8334                "             : cccccccccccccccc ? dddddddddddddddddd\n"
8335                "                                : eeeeeeeeeeeeeeeeee\n"
8336                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8337                "                                 : 3333333333333333;",
8338                Style);
8339 
8340   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8341   Style.BreakBeforeTernaryOperators = false;
8342   // FIXME: Aligning the question marks is weird given DontAlign.
8343   // Consider disabling this alignment in this case. Also check whether this
8344   // will render the adjustment from https://reviews.llvm.org/D82199
8345   // unnecessary.
8346   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
8347                "    bbbb                ? cccccccccccccccccc :\n"
8348                "                          ddddd;\n",
8349                Style);
8350 
8351   EXPECT_EQ(
8352       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8353       "    /*\n"
8354       "     */\n"
8355       "    function() {\n"
8356       "      try {\n"
8357       "        return JJJJJJJJJJJJJJ(\n"
8358       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8359       "      }\n"
8360       "    } :\n"
8361       "    function() {};",
8362       format(
8363           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8364           "     /*\n"
8365           "      */\n"
8366           "     function() {\n"
8367           "      try {\n"
8368           "        return JJJJJJJJJJJJJJ(\n"
8369           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8370           "      }\n"
8371           "    } :\n"
8372           "    function() {};",
8373           getGoogleStyle(FormatStyle::LK_JavaScript)));
8374 }
8375 
8376 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
8377   FormatStyle Style = getLLVMStyleWithColumns(70);
8378   Style.BreakBeforeTernaryOperators = false;
8379   verifyFormat(
8380       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8381       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8382       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8383       Style);
8384   verifyFormat(
8385       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8386       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8387       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8388       Style);
8389   verifyFormat(
8390       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8391       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8392       Style);
8393   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
8394                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8395                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8396                Style);
8397   verifyFormat(
8398       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
8399       "                                                      aaaaaaaaaaaaa);",
8400       Style);
8401   verifyFormat(
8402       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8403       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8404       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8405       "                   aaaaaaaaaaaaa);",
8406       Style);
8407   verifyFormat(
8408       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8409       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8410       "                   aaaaaaaaaaaaa);",
8411       Style);
8412   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8413                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8414                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8415                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8416                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8417                Style);
8418   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8419                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8420                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8421                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8422                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8423                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8424                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8425                Style);
8426   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8427                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8428                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8429                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8430                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8431                Style);
8432   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8433                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8434                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8435                Style);
8436   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8437                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8438                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8439                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8440                Style);
8441   verifyFormat(
8442       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8443       "    aaaaaaaaaaaaaaa :\n"
8444       "    aaaaaaaaaaaaaaa;",
8445       Style);
8446   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8447                "          aaaaaaaaa ?\n"
8448                "      b :\n"
8449                "      c);",
8450                Style);
8451   verifyFormat("unsigned Indent =\n"
8452                "    format(TheLine.First,\n"
8453                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8454                "               IndentForLevel[TheLine.Level] :\n"
8455                "               TheLine * 2,\n"
8456                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8457                Style);
8458   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8459                "                  aaaaaaaaaaaaaaa :\n"
8460                "                  bbbbbbbbbbbbbbb ? //\n"
8461                "                      ccccccccccccccc :\n"
8462                "                      ddddddddddddddd;",
8463                Style);
8464   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8465                "                  aaaaaaaaaaaaaaa :\n"
8466                "                  (bbbbbbbbbbbbbbb ? //\n"
8467                "                       ccccccccccccccc :\n"
8468                "                       ddddddddddddddd);",
8469                Style);
8470   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8471                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8472                "            ccccccccccccccccccccccccccc;",
8473                Style);
8474   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8475                "           aaaaa :\n"
8476                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8477                Style);
8478 
8479   // Chained conditionals
8480   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8481                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8482                "                          3333333333333333;",
8483                Style);
8484   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8485                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8486                "                          3333333333333333;",
8487                Style);
8488   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8489                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8490                "                          3333333333333333;",
8491                Style);
8492   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8493                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8494                "                          333333;",
8495                Style);
8496   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8497                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8498                "       cccccccccccccccc ? 3333333333333333 :\n"
8499                "                          4444444444444444;",
8500                Style);
8501   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8502                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8503                "                          3333333333333333;",
8504                Style);
8505   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8506                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8507                "                          (aaa ? bbb : ccc);",
8508                Style);
8509   verifyFormat(
8510       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8511       "                                               cccccccccccccccccc) :\n"
8512       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8513       "                          3333333333333333;",
8514       Style);
8515   verifyFormat(
8516       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8517       "                                               cccccccccccccccccc) :\n"
8518       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8519       "                          3333333333333333;",
8520       Style);
8521   verifyFormat(
8522       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8523       "                                               dddddddddddddddddd) :\n"
8524       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8525       "                          3333333333333333;",
8526       Style);
8527   verifyFormat(
8528       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8529       "                                               dddddddddddddddddd) :\n"
8530       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8531       "                          3333333333333333;",
8532       Style);
8533   verifyFormat(
8534       "return aaaaaaaaa        ? 1111111111111111 :\n"
8535       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8536       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8537       "                                               dddddddddddddddddd)\n",
8538       Style);
8539   verifyFormat(
8540       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8541       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8542       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8543       "                                               cccccccccccccccccc);",
8544       Style);
8545   verifyFormat(
8546       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8547       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8548       "                                               eeeeeeeeeeeeeeeeee) :\n"
8549       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8550       "                          3333333333333333;",
8551       Style);
8552   verifyFormat(
8553       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8554       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8555       "                                               eeeeeeeeeeeeeeeeee) :\n"
8556       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8557       "                          3333333333333333;",
8558       Style);
8559   verifyFormat(
8560       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8561       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8562       "                                               eeeeeeeeeeeeeeeeee) :\n"
8563       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8564       "                          3333333333333333;",
8565       Style);
8566   verifyFormat(
8567       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8568       "                                               cccccccccccccccccc :\n"
8569       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8570       "                          3333333333333333;",
8571       Style);
8572   verifyFormat(
8573       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8574       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8575       "                                               eeeeeeeeeeeeeeeeee :\n"
8576       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8577       "                          3333333333333333;",
8578       Style);
8579   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8580                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8581                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8582                "                                 eeeeeeeeeeeeeeeeee) :\n"
8583                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8584                "                               3333333333333333;",
8585                Style);
8586   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8587                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8588                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8589                "                                  eeeeeeeeeeeeeeeeee :\n"
8590                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8591                "                               3333333333333333;",
8592                Style);
8593 }
8594 
8595 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8596   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8597                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8598   verifyFormat("bool a = true, b = false;");
8599 
8600   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8601                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8602                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8603                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8604   verifyFormat(
8605       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8606       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8607       "     d = e && f;");
8608   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8609                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8610   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8611                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8612   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8613                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8614 
8615   FormatStyle Style = getGoogleStyle();
8616   Style.PointerAlignment = FormatStyle::PAS_Left;
8617   Style.DerivePointerAlignment = false;
8618   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8619                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8620                "    *b = bbbbbbbbbbbbbbbbbbb;",
8621                Style);
8622   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8623                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8624                Style);
8625   verifyFormat("vector<int*> a, b;", Style);
8626   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8627   verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
8628   verifyFormat("if (int *p, *q; p != q) {\n  p = p->next;\n}", Style);
8629   verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n  p = p->next;\n}",
8630                Style);
8631   verifyFormat("switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8632                Style);
8633   verifyFormat(
8634       "/*comment*/ switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8635       Style);
8636 
8637   verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
8638   verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
8639   verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
8640   verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
8641   verifyFormat("switch ([](int* p, int* q) {}()) {\n  default:\n    break;\n}",
8642                Style);
8643 }
8644 
8645 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8646   verifyFormat("arr[foo ? bar : baz];");
8647   verifyFormat("f()[foo ? bar : baz];");
8648   verifyFormat("(a + b)[foo ? bar : baz];");
8649   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8650 }
8651 
8652 TEST_F(FormatTest, AlignsStringLiterals) {
8653   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8654                "                                      \"short literal\");");
8655   verifyFormat(
8656       "looooooooooooooooooooooooongFunction(\n"
8657       "    \"short literal\"\n"
8658       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8659   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8660                "             \" string literals\",\n"
8661                "             and, other, parameters);");
8662   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8663             "      \"5678\";",
8664             format("fun + \"1243\" /* comment */\n"
8665                    "    \"5678\";",
8666                    getLLVMStyleWithColumns(28)));
8667   EXPECT_EQ(
8668       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8669       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8670       "         \"aaaaaaaaaaaaaaaa\";",
8671       format("aaaaaa ="
8672              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8673              "aaaaaaaaaaaaaaaaaaaaa\" "
8674              "\"aaaaaaaaaaaaaaaa\";"));
8675   verifyFormat("a = a + \"a\"\n"
8676                "        \"a\"\n"
8677                "        \"a\";");
8678   verifyFormat("f(\"a\", \"b\"\n"
8679                "       \"c\");");
8680 
8681   verifyFormat(
8682       "#define LL_FORMAT \"ll\"\n"
8683       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8684       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8685 
8686   verifyFormat("#define A(X)          \\\n"
8687                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8688                "  \"ccccc\"",
8689                getLLVMStyleWithColumns(23));
8690   verifyFormat("#define A \"def\"\n"
8691                "f(\"abc\" A \"ghi\"\n"
8692                "  \"jkl\");");
8693 
8694   verifyFormat("f(L\"a\"\n"
8695                "  L\"b\");");
8696   verifyFormat("#define A(X)            \\\n"
8697                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8698                "  L\"ccccc\"",
8699                getLLVMStyleWithColumns(25));
8700 
8701   verifyFormat("f(@\"a\"\n"
8702                "  @\"b\");");
8703   verifyFormat("NSString s = @\"a\"\n"
8704                "             @\"b\"\n"
8705                "             @\"c\";");
8706   verifyFormat("NSString s = @\"a\"\n"
8707                "              \"b\"\n"
8708                "              \"c\";");
8709 }
8710 
8711 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8712   FormatStyle Style = getLLVMStyle();
8713   // No declarations or definitions should be moved to own line.
8714   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8715   verifyFormat("class A {\n"
8716                "  int f() { return 1; }\n"
8717                "  int g();\n"
8718                "};\n"
8719                "int f() { return 1; }\n"
8720                "int g();\n",
8721                Style);
8722 
8723   // All declarations and definitions should have the return type moved to its
8724   // own line.
8725   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8726   Style.TypenameMacros = {"LIST"};
8727   verifyFormat("SomeType\n"
8728                "funcdecl(LIST(uint64_t));",
8729                Style);
8730   verifyFormat("class E {\n"
8731                "  int\n"
8732                "  f() {\n"
8733                "    return 1;\n"
8734                "  }\n"
8735                "  int\n"
8736                "  g();\n"
8737                "};\n"
8738                "int\n"
8739                "f() {\n"
8740                "  return 1;\n"
8741                "}\n"
8742                "int\n"
8743                "g();\n",
8744                Style);
8745 
8746   // Top-level definitions, and no kinds of declarations should have the
8747   // return type moved to its own line.
8748   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8749   verifyFormat("class B {\n"
8750                "  int f() { return 1; }\n"
8751                "  int g();\n"
8752                "};\n"
8753                "int\n"
8754                "f() {\n"
8755                "  return 1;\n"
8756                "}\n"
8757                "int g();\n",
8758                Style);
8759 
8760   // Top-level definitions and declarations should have the return type moved
8761   // to its own line.
8762   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8763   verifyFormat("class C {\n"
8764                "  int f() { return 1; }\n"
8765                "  int g();\n"
8766                "};\n"
8767                "int\n"
8768                "f() {\n"
8769                "  return 1;\n"
8770                "}\n"
8771                "int\n"
8772                "g();\n",
8773                Style);
8774 
8775   // All definitions should have the return type moved to its own line, but no
8776   // kinds of declarations.
8777   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8778   verifyFormat("class D {\n"
8779                "  int\n"
8780                "  f() {\n"
8781                "    return 1;\n"
8782                "  }\n"
8783                "  int g();\n"
8784                "};\n"
8785                "int\n"
8786                "f() {\n"
8787                "  return 1;\n"
8788                "}\n"
8789                "int g();\n",
8790                Style);
8791   verifyFormat("const char *\n"
8792                "f(void) {\n" // Break here.
8793                "  return \"\";\n"
8794                "}\n"
8795                "const char *bar(void);\n", // No break here.
8796                Style);
8797   verifyFormat("template <class T>\n"
8798                "T *\n"
8799                "f(T &c) {\n" // Break here.
8800                "  return NULL;\n"
8801                "}\n"
8802                "template <class T> T *f(T &c);\n", // No break here.
8803                Style);
8804   verifyFormat("class C {\n"
8805                "  int\n"
8806                "  operator+() {\n"
8807                "    return 1;\n"
8808                "  }\n"
8809                "  int\n"
8810                "  operator()() {\n"
8811                "    return 1;\n"
8812                "  }\n"
8813                "};\n",
8814                Style);
8815   verifyFormat("void\n"
8816                "A::operator()() {}\n"
8817                "void\n"
8818                "A::operator>>() {}\n"
8819                "void\n"
8820                "A::operator+() {}\n"
8821                "void\n"
8822                "A::operator*() {}\n"
8823                "void\n"
8824                "A::operator->() {}\n"
8825                "void\n"
8826                "A::operator void *() {}\n"
8827                "void\n"
8828                "A::operator void &() {}\n"
8829                "void\n"
8830                "A::operator void &&() {}\n"
8831                "void\n"
8832                "A::operator char *() {}\n"
8833                "void\n"
8834                "A::operator[]() {}\n"
8835                "void\n"
8836                "A::operator!() {}\n"
8837                "void\n"
8838                "A::operator**() {}\n"
8839                "void\n"
8840                "A::operator<Foo> *() {}\n"
8841                "void\n"
8842                "A::operator<Foo> **() {}\n"
8843                "void\n"
8844                "A::operator<Foo> &() {}\n"
8845                "void\n"
8846                "A::operator void **() {}\n",
8847                Style);
8848   verifyFormat("constexpr auto\n"
8849                "operator()() const -> reference {}\n"
8850                "constexpr auto\n"
8851                "operator>>() const -> reference {}\n"
8852                "constexpr auto\n"
8853                "operator+() const -> reference {}\n"
8854                "constexpr auto\n"
8855                "operator*() const -> reference {}\n"
8856                "constexpr auto\n"
8857                "operator->() const -> reference {}\n"
8858                "constexpr auto\n"
8859                "operator++() const -> reference {}\n"
8860                "constexpr auto\n"
8861                "operator void *() const -> reference {}\n"
8862                "constexpr auto\n"
8863                "operator void **() const -> reference {}\n"
8864                "constexpr auto\n"
8865                "operator void *() const -> reference {}\n"
8866                "constexpr auto\n"
8867                "operator void &() const -> reference {}\n"
8868                "constexpr auto\n"
8869                "operator void &&() const -> reference {}\n"
8870                "constexpr auto\n"
8871                "operator char *() const -> reference {}\n"
8872                "constexpr auto\n"
8873                "operator!() const -> reference {}\n"
8874                "constexpr auto\n"
8875                "operator[]() const -> reference {}\n",
8876                Style);
8877   verifyFormat("void *operator new(std::size_t s);", // No break here.
8878                Style);
8879   verifyFormat("void *\n"
8880                "operator new(std::size_t s) {}",
8881                Style);
8882   verifyFormat("void *\n"
8883                "operator delete[](void *ptr) {}",
8884                Style);
8885   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8886   verifyFormat("const char *\n"
8887                "f(void)\n" // Break here.
8888                "{\n"
8889                "  return \"\";\n"
8890                "}\n"
8891                "const char *bar(void);\n", // No break here.
8892                Style);
8893   verifyFormat("template <class T>\n"
8894                "T *\n"     // Problem here: no line break
8895                "f(T &c)\n" // Break here.
8896                "{\n"
8897                "  return NULL;\n"
8898                "}\n"
8899                "template <class T> T *f(T &c);\n", // No break here.
8900                Style);
8901   verifyFormat("int\n"
8902                "foo(A<bool> a)\n"
8903                "{\n"
8904                "  return a;\n"
8905                "}\n",
8906                Style);
8907   verifyFormat("int\n"
8908                "foo(A<8> a)\n"
8909                "{\n"
8910                "  return a;\n"
8911                "}\n",
8912                Style);
8913   verifyFormat("int\n"
8914                "foo(A<B<bool>, 8> a)\n"
8915                "{\n"
8916                "  return a;\n"
8917                "}\n",
8918                Style);
8919   verifyFormat("int\n"
8920                "foo(A<B<8>, bool> a)\n"
8921                "{\n"
8922                "  return a;\n"
8923                "}\n",
8924                Style);
8925   verifyFormat("int\n"
8926                "foo(A<B<bool>, bool> a)\n"
8927                "{\n"
8928                "  return a;\n"
8929                "}\n",
8930                Style);
8931   verifyFormat("int\n"
8932                "foo(A<B<8>, 8> a)\n"
8933                "{\n"
8934                "  return a;\n"
8935                "}\n",
8936                Style);
8937 
8938   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8939   Style.BraceWrapping.AfterFunction = true;
8940   verifyFormat("int f(i);\n" // No break here.
8941                "int\n"       // Break here.
8942                "f(i)\n"
8943                "{\n"
8944                "  return i + 1;\n"
8945                "}\n"
8946                "int\n" // Break here.
8947                "f(i)\n"
8948                "{\n"
8949                "  return i + 1;\n"
8950                "};",
8951                Style);
8952   verifyFormat("int f(a, b, c);\n" // No break here.
8953                "int\n"             // Break here.
8954                "f(a, b, c)\n"      // Break here.
8955                "short a, b;\n"
8956                "float c;\n"
8957                "{\n"
8958                "  return a + b < c;\n"
8959                "}\n"
8960                "int\n"        // Break here.
8961                "f(a, b, c)\n" // Break here.
8962                "short a, b;\n"
8963                "float c;\n"
8964                "{\n"
8965                "  return a + b < c;\n"
8966                "};",
8967                Style);
8968   verifyFormat("byte *\n" // Break here.
8969                "f(a)\n"   // Break here.
8970                "byte a[];\n"
8971                "{\n"
8972                "  return a;\n"
8973                "}",
8974                Style);
8975   verifyFormat("bool f(int a, int) override;\n"
8976                "Bar g(int a, Bar) final;\n"
8977                "Bar h(a, Bar) final;",
8978                Style);
8979   verifyFormat("int\n"
8980                "f(a)",
8981                Style);
8982   verifyFormat("bool\n"
8983                "f(size_t = 0, bool b = false)\n"
8984                "{\n"
8985                "  return !b;\n"
8986                "}",
8987                Style);
8988 
8989   // The return breaking style doesn't affect:
8990   // * function and object definitions with attribute-like macros
8991   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8992                "    ABSL_GUARDED_BY(mutex) = {};",
8993                getGoogleStyleWithColumns(40));
8994   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8995                "    ABSL_GUARDED_BY(mutex);  // comment",
8996                getGoogleStyleWithColumns(40));
8997   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8998                "    ABSL_GUARDED_BY(mutex1)\n"
8999                "        ABSL_GUARDED_BY(mutex2);",
9000                getGoogleStyleWithColumns(40));
9001   verifyFormat("Tttttt f(int a, int b)\n"
9002                "    ABSL_GUARDED_BY(mutex1)\n"
9003                "        ABSL_GUARDED_BY(mutex2);",
9004                getGoogleStyleWithColumns(40));
9005   // * typedefs
9006   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
9007 
9008   Style = getGNUStyle();
9009 
9010   // Test for comments at the end of function declarations.
9011   verifyFormat("void\n"
9012                "foo (int a, /*abc*/ int b) // def\n"
9013                "{\n"
9014                "}\n",
9015                Style);
9016 
9017   verifyFormat("void\n"
9018                "foo (int a, /* abc */ int b) /* def */\n"
9019                "{\n"
9020                "}\n",
9021                Style);
9022 
9023   // Definitions that should not break after return type
9024   verifyFormat("void foo (int a, int b); // def\n", Style);
9025   verifyFormat("void foo (int a, int b); /* def */\n", Style);
9026   verifyFormat("void foo (int a, int b);\n", Style);
9027 }
9028 
9029 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
9030   FormatStyle NoBreak = getLLVMStyle();
9031   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
9032   FormatStyle Break = getLLVMStyle();
9033   Break.AlwaysBreakBeforeMultilineStrings = true;
9034   verifyFormat("aaaa = \"bbbb\"\n"
9035                "       \"cccc\";",
9036                NoBreak);
9037   verifyFormat("aaaa =\n"
9038                "    \"bbbb\"\n"
9039                "    \"cccc\";",
9040                Break);
9041   verifyFormat("aaaa(\"bbbb\"\n"
9042                "     \"cccc\");",
9043                NoBreak);
9044   verifyFormat("aaaa(\n"
9045                "    \"bbbb\"\n"
9046                "    \"cccc\");",
9047                Break);
9048   verifyFormat("aaaa(qqq, \"bbbb\"\n"
9049                "          \"cccc\");",
9050                NoBreak);
9051   verifyFormat("aaaa(qqq,\n"
9052                "     \"bbbb\"\n"
9053                "     \"cccc\");",
9054                Break);
9055   verifyFormat("aaaa(qqq,\n"
9056                "     L\"bbbb\"\n"
9057                "     L\"cccc\");",
9058                Break);
9059   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
9060                "                      \"bbbb\"));",
9061                Break);
9062   verifyFormat("string s = someFunction(\n"
9063                "    \"abc\"\n"
9064                "    \"abc\");",
9065                Break);
9066 
9067   // As we break before unary operators, breaking right after them is bad.
9068   verifyFormat("string foo = abc ? \"x\"\n"
9069                "                   \"blah blah blah blah blah blah\"\n"
9070                "                 : \"y\";",
9071                Break);
9072 
9073   // Don't break if there is no column gain.
9074   verifyFormat("f(\"aaaa\"\n"
9075                "  \"bbbb\");",
9076                Break);
9077 
9078   // Treat literals with escaped newlines like multi-line string literals.
9079   EXPECT_EQ("x = \"a\\\n"
9080             "b\\\n"
9081             "c\";",
9082             format("x = \"a\\\n"
9083                    "b\\\n"
9084                    "c\";",
9085                    NoBreak));
9086   EXPECT_EQ("xxxx =\n"
9087             "    \"a\\\n"
9088             "b\\\n"
9089             "c\";",
9090             format("xxxx = \"a\\\n"
9091                    "b\\\n"
9092                    "c\";",
9093                    Break));
9094 
9095   EXPECT_EQ("NSString *const kString =\n"
9096             "    @\"aaaa\"\n"
9097             "    @\"bbbb\";",
9098             format("NSString *const kString = @\"aaaa\"\n"
9099                    "@\"bbbb\";",
9100                    Break));
9101 
9102   Break.ColumnLimit = 0;
9103   verifyFormat("const char *hello = \"hello llvm\";", Break);
9104 }
9105 
9106 TEST_F(FormatTest, AlignsPipes) {
9107   verifyFormat(
9108       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9109       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9110       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9111   verifyFormat(
9112       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
9113       "                     << aaaaaaaaaaaaaaaaaaaa;");
9114   verifyFormat(
9115       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9116       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9117   verifyFormat(
9118       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
9119       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9120   verifyFormat(
9121       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
9122       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
9123       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
9124   verifyFormat(
9125       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9126       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9127       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9128   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9129                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9130                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9131                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9132   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
9133                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
9134   verifyFormat(
9135       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9136       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9137   verifyFormat(
9138       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
9139       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
9140 
9141   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
9142                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
9143   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9144                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9145                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
9146                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
9147   verifyFormat("LOG_IF(aaa == //\n"
9148                "       bbb)\n"
9149                "    << a << b;");
9150 
9151   // But sometimes, breaking before the first "<<" is desirable.
9152   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9153                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
9154   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
9155                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9156                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9157   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
9158                "    << BEF << IsTemplate << Description << E->getType();");
9159   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9160                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9161                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9162   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9163                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9164                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9165                "    << aaa;");
9166 
9167   verifyFormat(
9168       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9169       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9170 
9171   // Incomplete string literal.
9172   EXPECT_EQ("llvm::errs() << \"\n"
9173             "             << a;",
9174             format("llvm::errs() << \"\n<<a;"));
9175 
9176   verifyFormat("void f() {\n"
9177                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
9178                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
9179                "}");
9180 
9181   // Handle 'endl'.
9182   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
9183                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9184   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9185 
9186   // Handle '\n'.
9187   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
9188                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9189   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
9190                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
9191   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
9192                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
9193   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9194 }
9195 
9196 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
9197   verifyFormat("return out << \"somepacket = {\\n\"\n"
9198                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
9199                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
9200                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
9201                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
9202                "           << \"}\";");
9203 
9204   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9205                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9206                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
9207   verifyFormat(
9208       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
9209       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
9210       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
9211       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
9212       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
9213   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
9214                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9215   verifyFormat(
9216       "void f() {\n"
9217       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
9218       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
9219       "}");
9220 
9221   // Breaking before the first "<<" is generally not desirable.
9222   verifyFormat(
9223       "llvm::errs()\n"
9224       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9225       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9226       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9227       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9228       getLLVMStyleWithColumns(70));
9229   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9230                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9231                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9232                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9233                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9234                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9235                getLLVMStyleWithColumns(70));
9236 
9237   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9238                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9239                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
9240   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9241                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9242                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
9243   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
9244                "           (aaaa + aaaa);",
9245                getLLVMStyleWithColumns(40));
9246   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
9247                "                  (aaaaaaa + aaaaa));",
9248                getLLVMStyleWithColumns(40));
9249   verifyFormat(
9250       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
9251       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
9252       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
9253 }
9254 
9255 TEST_F(FormatTest, UnderstandsEquals) {
9256   verifyFormat(
9257       "aaaaaaaaaaaaaaaaa =\n"
9258       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9259   verifyFormat(
9260       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9261       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9262   verifyFormat(
9263       "if (a) {\n"
9264       "  f();\n"
9265       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9266       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
9267       "}");
9268 
9269   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9270                "        100000000 + 10000000) {\n}");
9271 }
9272 
9273 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
9274   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9275                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
9276 
9277   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9278                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
9279 
9280   verifyFormat(
9281       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
9282       "                                                          Parameter2);");
9283 
9284   verifyFormat(
9285       "ShortObject->shortFunction(\n"
9286       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
9287       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
9288 
9289   verifyFormat("loooooooooooooongFunction(\n"
9290                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
9291 
9292   verifyFormat(
9293       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
9294       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
9295 
9296   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9297                "    .WillRepeatedly(Return(SomeValue));");
9298   verifyFormat("void f() {\n"
9299                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9300                "      .Times(2)\n"
9301                "      .WillRepeatedly(Return(SomeValue));\n"
9302                "}");
9303   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
9304                "    ccccccccccccccccccccccc);");
9305   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9306                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9307                "          .aaaaa(aaaaa),\n"
9308                "      aaaaaaaaaaaaaaaaaaaaa);");
9309   verifyFormat("void f() {\n"
9310                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9311                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
9312                "}");
9313   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9314                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9315                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9316                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9317                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9318   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9319                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9320                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9321                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
9322                "}");
9323 
9324   // Here, it is not necessary to wrap at "." or "->".
9325   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
9326                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9327   verifyFormat(
9328       "aaaaaaaaaaa->aaaaaaaaa(\n"
9329       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9330       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
9331 
9332   verifyFormat(
9333       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9334       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
9335   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
9336                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9337   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
9338                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9339 
9340   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9341                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9342                "    .a();");
9343 
9344   FormatStyle NoBinPacking = getLLVMStyle();
9345   NoBinPacking.BinPackParameters = false;
9346   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9347                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9348                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
9349                "                         aaaaaaaaaaaaaaaaaaa,\n"
9350                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
9351                NoBinPacking);
9352 
9353   // If there is a subsequent call, change to hanging indentation.
9354   verifyFormat(
9355       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9356       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
9357       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9358   verifyFormat(
9359       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9360       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
9361   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9362                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9363                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9364   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9365                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9366                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9367 }
9368 
9369 TEST_F(FormatTest, WrapsTemplateDeclarations) {
9370   verifyFormat("template <typename T>\n"
9371                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9372   verifyFormat("template <typename T>\n"
9373                "// T should be one of {A, B}.\n"
9374                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9375   verifyFormat(
9376       "template <typename T>\n"
9377       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
9378   verifyFormat("template <typename T>\n"
9379                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
9380                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
9381   verifyFormat(
9382       "template <typename T>\n"
9383       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
9384       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
9385   verifyFormat(
9386       "template <typename T>\n"
9387       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
9388       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
9389       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9390   verifyFormat("template <typename T>\n"
9391                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9392                "    int aaaaaaaaaaaaaaaaaaaaaa);");
9393   verifyFormat(
9394       "template <typename T1, typename T2 = char, typename T3 = char,\n"
9395       "          typename T4 = char>\n"
9396       "void f();");
9397   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
9398                "          template <typename> class cccccccccccccccccccccc,\n"
9399                "          typename ddddddddddddd>\n"
9400                "class C {};");
9401   verifyFormat(
9402       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
9403       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9404 
9405   verifyFormat("void f() {\n"
9406                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
9407                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
9408                "}");
9409 
9410   verifyFormat("template <typename T> class C {};");
9411   verifyFormat("template <typename T> void f();");
9412   verifyFormat("template <typename T> void f() {}");
9413   verifyFormat(
9414       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9415       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9416       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
9417       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9418       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9419       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
9420       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
9421       getLLVMStyleWithColumns(72));
9422   EXPECT_EQ("static_cast<A< //\n"
9423             "    B> *>(\n"
9424             "\n"
9425             ");",
9426             format("static_cast<A<//\n"
9427                    "    B>*>(\n"
9428                    "\n"
9429                    "    );"));
9430   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9431                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
9432 
9433   FormatStyle AlwaysBreak = getLLVMStyle();
9434   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9435   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
9436   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
9437   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
9438   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9439                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9440                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9441   verifyFormat("template <template <typename> class Fooooooo,\n"
9442                "          template <typename> class Baaaaaaar>\n"
9443                "struct C {};",
9444                AlwaysBreak);
9445   verifyFormat("template <typename T> // T can be A, B or C.\n"
9446                "struct C {};",
9447                AlwaysBreak);
9448   verifyFormat("template <enum E> class A {\n"
9449                "public:\n"
9450                "  E *f();\n"
9451                "};");
9452 
9453   FormatStyle NeverBreak = getLLVMStyle();
9454   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9455   verifyFormat("template <typename T> class C {};", NeverBreak);
9456   verifyFormat("template <typename T> void f();", NeverBreak);
9457   verifyFormat("template <typename T> void f() {}", NeverBreak);
9458   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9459                "bbbbbbbbbbbbbbbbbbbb) {}",
9460                NeverBreak);
9461   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9462                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9463                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9464                NeverBreak);
9465   verifyFormat("template <template <typename> class Fooooooo,\n"
9466                "          template <typename> class Baaaaaaar>\n"
9467                "struct C {};",
9468                NeverBreak);
9469   verifyFormat("template <typename T> // T can be A, B or C.\n"
9470                "struct C {};",
9471                NeverBreak);
9472   verifyFormat("template <enum E> class A {\n"
9473                "public:\n"
9474                "  E *f();\n"
9475                "};",
9476                NeverBreak);
9477   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9478   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9479                "bbbbbbbbbbbbbbbbbbbb) {}",
9480                NeverBreak);
9481 }
9482 
9483 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9484   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9485   Style.ColumnLimit = 60;
9486   EXPECT_EQ("// Baseline - no comments.\n"
9487             "template <\n"
9488             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9489             "void f() {}",
9490             format("// Baseline - no comments.\n"
9491                    "template <\n"
9492                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9493                    "void f() {}",
9494                    Style));
9495 
9496   EXPECT_EQ("template <\n"
9497             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9498             "void f() {}",
9499             format("template <\n"
9500                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9501                    "void f() {}",
9502                    Style));
9503 
9504   EXPECT_EQ(
9505       "template <\n"
9506       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9507       "void f() {}",
9508       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9509              "void f() {}",
9510              Style));
9511 
9512   EXPECT_EQ(
9513       "template <\n"
9514       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9515       "                                               // multiline\n"
9516       "void f() {}",
9517       format("template <\n"
9518              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9519              "                                              // multiline\n"
9520              "void f() {}",
9521              Style));
9522 
9523   EXPECT_EQ(
9524       "template <typename aaaaaaaaaa<\n"
9525       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9526       "void f() {}",
9527       format(
9528           "template <\n"
9529           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9530           "void f() {}",
9531           Style));
9532 }
9533 
9534 TEST_F(FormatTest, WrapsTemplateParameters) {
9535   FormatStyle Style = getLLVMStyle();
9536   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9537   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9538   verifyFormat(
9539       "template <typename... a> struct q {};\n"
9540       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9541       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9542       "    y;",
9543       Style);
9544   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9545   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9546   verifyFormat(
9547       "template <typename... a> struct r {};\n"
9548       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9549       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9550       "    y;",
9551       Style);
9552   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9553   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9554   verifyFormat("template <typename... a> struct s {};\n"
9555                "extern s<\n"
9556                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9557                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9558                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9559                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9560                "    y;",
9561                Style);
9562   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9563   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9564   verifyFormat("template <typename... a> struct t {};\n"
9565                "extern t<\n"
9566                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9567                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9568                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9569                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9570                "    y;",
9571                Style);
9572 }
9573 
9574 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9575   verifyFormat(
9576       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9577       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9578   verifyFormat(
9579       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9580       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9581       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9582 
9583   // FIXME: Should we have the extra indent after the second break?
9584   verifyFormat(
9585       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9586       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9587       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9588 
9589   verifyFormat(
9590       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9591       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9592 
9593   // Breaking at nested name specifiers is generally not desirable.
9594   verifyFormat(
9595       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9596       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9597 
9598   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9599                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9600                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9601                "                   aaaaaaaaaaaaaaaaaaaaa);",
9602                getLLVMStyleWithColumns(74));
9603 
9604   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9605                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9606                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9607 }
9608 
9609 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9610   verifyFormat("A<int> a;");
9611   verifyFormat("A<A<A<int>>> a;");
9612   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9613   verifyFormat("bool x = a < 1 || 2 > a;");
9614   verifyFormat("bool x = 5 < f<int>();");
9615   verifyFormat("bool x = f<int>() > 5;");
9616   verifyFormat("bool x = 5 < a<int>::x;");
9617   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9618   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9619 
9620   verifyGoogleFormat("A<A<int>> a;");
9621   verifyGoogleFormat("A<A<A<int>>> a;");
9622   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9623   verifyGoogleFormat("A<A<int> > a;");
9624   verifyGoogleFormat("A<A<A<int> > > a;");
9625   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9626   verifyGoogleFormat("A<::A<int>> a;");
9627   verifyGoogleFormat("A<::A> a;");
9628   verifyGoogleFormat("A< ::A> a;");
9629   verifyGoogleFormat("A< ::A<int> > a;");
9630   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9631   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9632   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9633   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9634   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9635             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9636 
9637   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9638 
9639   // template closer followed by a token that starts with > or =
9640   verifyFormat("bool b = a<1> > 1;");
9641   verifyFormat("bool b = a<1> >= 1;");
9642   verifyFormat("int i = a<1> >> 1;");
9643   FormatStyle Style = getLLVMStyle();
9644   Style.SpaceBeforeAssignmentOperators = false;
9645   verifyFormat("bool b= a<1> == 1;", Style);
9646   verifyFormat("a<int> = 1;", Style);
9647   verifyFormat("a<int> >>= 1;", Style);
9648 
9649   verifyFormat("test < a | b >> c;");
9650   verifyFormat("test<test<a | b>> c;");
9651   verifyFormat("test >> a >> b;");
9652   verifyFormat("test << a >> b;");
9653 
9654   verifyFormat("f<int>();");
9655   verifyFormat("template <typename T> void f() {}");
9656   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9657   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9658                "sizeof(char)>::type>;");
9659   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9660   verifyFormat("f(a.operator()<A>());");
9661   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9662                "      .template operator()<A>());",
9663                getLLVMStyleWithColumns(35));
9664   verifyFormat("bool_constant<a && noexcept(f())>");
9665   verifyFormat("bool_constant<a || noexcept(f())>");
9666 
9667   // Not template parameters.
9668   verifyFormat("return a < b && c > d;");
9669   verifyFormat("void f() {\n"
9670                "  while (a < b && c > d) {\n"
9671                "  }\n"
9672                "}");
9673   verifyFormat("template <typename... Types>\n"
9674                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9675 
9676   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9677                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9678                getLLVMStyleWithColumns(60));
9679   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9680   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9681   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9682   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9683 }
9684 
9685 TEST_F(FormatTest, UnderstandsShiftOperators) {
9686   verifyFormat("if (i < x >> 1)");
9687   verifyFormat("while (i < x >> 1)");
9688   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9689   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9690   verifyFormat(
9691       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9692   verifyFormat("Foo.call<Bar<Function>>()");
9693   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9694   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9695                "++i, v = v >> 1)");
9696   verifyFormat("if (w<u<v<x>>, 1>::t)");
9697 }
9698 
9699 TEST_F(FormatTest, BitshiftOperatorWidth) {
9700   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9701             "                   bar */",
9702             format("int    a=1<<2;  /* foo\n"
9703                    "                   bar */"));
9704 
9705   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9706             "                     bar */",
9707             format("int  b  =256>>1 ;  /* foo\n"
9708                    "                      bar */"));
9709 }
9710 
9711 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9712   verifyFormat("COMPARE(a, ==, b);");
9713   verifyFormat("auto s = sizeof...(Ts) - 1;");
9714 }
9715 
9716 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9717   verifyFormat("int A::*x;");
9718   verifyFormat("int (S::*func)(void *);");
9719   verifyFormat("void f() { int (S::*func)(void *); }");
9720   verifyFormat("typedef bool *(Class::*Member)() const;");
9721   verifyFormat("void f() {\n"
9722                "  (a->*f)();\n"
9723                "  a->*x;\n"
9724                "  (a.*f)();\n"
9725                "  ((*a).*f)();\n"
9726                "  a.*x;\n"
9727                "}");
9728   verifyFormat("void f() {\n"
9729                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9730                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9731                "}");
9732   verifyFormat(
9733       "(aaaaaaaaaa->*bbbbbbb)(\n"
9734       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9735   FormatStyle Style = getLLVMStyle();
9736   Style.PointerAlignment = FormatStyle::PAS_Left;
9737   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9738 }
9739 
9740 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9741   verifyFormat("int a = -2;");
9742   verifyFormat("f(-1, -2, -3);");
9743   verifyFormat("a[-1] = 5;");
9744   verifyFormat("int a = 5 + -2;");
9745   verifyFormat("if (i == -1) {\n}");
9746   verifyFormat("if (i != -1) {\n}");
9747   verifyFormat("if (i > -1) {\n}");
9748   verifyFormat("if (i < -1) {\n}");
9749   verifyFormat("++(a->f());");
9750   verifyFormat("--(a->f());");
9751   verifyFormat("(a->f())++;");
9752   verifyFormat("a[42]++;");
9753   verifyFormat("if (!(a->f())) {\n}");
9754   verifyFormat("if (!+i) {\n}");
9755   verifyFormat("~&a;");
9756 
9757   verifyFormat("a-- > b;");
9758   verifyFormat("b ? -a : c;");
9759   verifyFormat("n * sizeof char16;");
9760   verifyFormat("n * alignof char16;", getGoogleStyle());
9761   verifyFormat("sizeof(char);");
9762   verifyFormat("alignof(char);", getGoogleStyle());
9763 
9764   verifyFormat("return -1;");
9765   verifyFormat("throw -1;");
9766   verifyFormat("switch (a) {\n"
9767                "case -1:\n"
9768                "  break;\n"
9769                "}");
9770   verifyFormat("#define X -1");
9771   verifyFormat("#define X -kConstant");
9772 
9773   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9774   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9775 
9776   verifyFormat("int a = /* confusing comment */ -1;");
9777   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9778   verifyFormat("int a = i /* confusing comment */++;");
9779 
9780   verifyFormat("co_yield -1;");
9781   verifyFormat("co_return -1;");
9782 
9783   // Check that * is not treated as a binary operator when we set
9784   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9785   FormatStyle PASLeftStyle = getLLVMStyle();
9786   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9787   verifyFormat("co_return *a;", PASLeftStyle);
9788   verifyFormat("co_await *a;", PASLeftStyle);
9789   verifyFormat("co_yield *a", PASLeftStyle);
9790   verifyFormat("return *a;", PASLeftStyle);
9791 }
9792 
9793 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9794   verifyFormat("if (!aaaaaaaaaa( // break\n"
9795                "        aaaaa)) {\n"
9796                "}");
9797   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9798                "    aaaaa));");
9799   verifyFormat("*aaa = aaaaaaa( // break\n"
9800                "    bbbbbb);");
9801 }
9802 
9803 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9804   verifyFormat("bool operator<();");
9805   verifyFormat("bool operator>();");
9806   verifyFormat("bool operator=();");
9807   verifyFormat("bool operator==();");
9808   verifyFormat("bool operator!=();");
9809   verifyFormat("int operator+();");
9810   verifyFormat("int operator++();");
9811   verifyFormat("int operator++(int) volatile noexcept;");
9812   verifyFormat("bool operator,();");
9813   verifyFormat("bool operator();");
9814   verifyFormat("bool operator()();");
9815   verifyFormat("bool operator[]();");
9816   verifyFormat("operator bool();");
9817   verifyFormat("operator int();");
9818   verifyFormat("operator void *();");
9819   verifyFormat("operator SomeType<int>();");
9820   verifyFormat("operator SomeType<int, int>();");
9821   verifyFormat("operator SomeType<SomeType<int>>();");
9822   verifyFormat("operator< <>();");
9823   verifyFormat("operator<< <>();");
9824   verifyFormat("< <>");
9825 
9826   verifyFormat("void *operator new(std::size_t size);");
9827   verifyFormat("void *operator new[](std::size_t size);");
9828   verifyFormat("void operator delete(void *ptr);");
9829   verifyFormat("void operator delete[](void *ptr);");
9830   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9831                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9832   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9833                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9834 
9835   verifyFormat(
9836       "ostream &operator<<(ostream &OutputStream,\n"
9837       "                    SomeReallyLongType WithSomeReallyLongValue);");
9838   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9839                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9840                "  return left.group < right.group;\n"
9841                "}");
9842   verifyFormat("SomeType &operator=(const SomeType &S);");
9843   verifyFormat("f.template operator()<int>();");
9844 
9845   verifyGoogleFormat("operator void*();");
9846   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9847   verifyGoogleFormat("operator ::A();");
9848 
9849   verifyFormat("using A::operator+;");
9850   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9851                "int i;");
9852 
9853   // Calling an operator as a member function.
9854   verifyFormat("void f() { a.operator*(); }");
9855   verifyFormat("void f() { a.operator*(b & b); }");
9856   verifyFormat("void f() { a->operator&(a * b); }");
9857   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9858   // TODO: Calling an operator as a non-member function is hard to distinguish.
9859   // https://llvm.org/PR50629
9860   // verifyFormat("void f() { operator*(a & a); }");
9861   // verifyFormat("void f() { operator&(a, b * b); }");
9862 
9863   verifyFormat("::operator delete(foo);");
9864   verifyFormat("::operator new(n * sizeof(foo));");
9865   verifyFormat("foo() { ::operator delete(foo); }");
9866   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9867 }
9868 
9869 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9870   verifyFormat("void A::b() && {}");
9871   verifyFormat("void A::b() &&noexcept {}");
9872   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9873   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9874   verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
9875   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9876   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9877   verifyFormat("Deleted &operator=(const Deleted &) &;");
9878   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9879   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9880   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9881   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9882   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9883   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9884   verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
9885   verifyFormat("void Fn(T const &) const &;");
9886   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9887   verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
9888   verifyFormat("template <typename T>\n"
9889                "void F(T) && = delete;",
9890                getGoogleStyle());
9891   verifyFormat("template <typename T> void operator=(T) &;");
9892   verifyFormat("template <typename T> void operator=(T) const &;");
9893   verifyFormat("template <typename T> void operator=(T) &noexcept;");
9894   verifyFormat("template <typename T> void operator=(T) & = default;");
9895   verifyFormat("template <typename T> void operator=(T) &&;");
9896   verifyFormat("template <typename T> void operator=(T) && = delete;");
9897   verifyFormat("template <typename T> void operator=(T) & {}");
9898   verifyFormat("template <typename T> void operator=(T) && {}");
9899 
9900   FormatStyle AlignLeft = getLLVMStyle();
9901   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9902   verifyFormat("void A::b() && {}", AlignLeft);
9903   verifyFormat("void A::b() && noexcept {}", AlignLeft);
9904   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9905   verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
9906                AlignLeft);
9907   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9908                AlignLeft);
9909   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9910   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9911   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9912   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9913   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9914   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9915   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9916   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9917   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
9918                AlignLeft);
9919   verifyFormat("template <typename T> void operator=(T) &;", AlignLeft);
9920   verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft);
9921   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9922                AlignLeft);
9923   verifyFormat("template <typename T> void operator=(T) & = default;",
9924                AlignLeft);
9925   verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft);
9926   verifyFormat("template <typename T> void operator=(T) && = delete;",
9927                AlignLeft);
9928   verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft);
9929   verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft);
9930 
9931   FormatStyle AlignMiddle = getLLVMStyle();
9932   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9933   verifyFormat("void A::b() && {}", AlignMiddle);
9934   verifyFormat("void A::b() && noexcept {}", AlignMiddle);
9935   verifyFormat("Deleted & operator=(const Deleted &) & = default;",
9936                AlignMiddle);
9937   verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
9938                AlignMiddle);
9939   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
9940                AlignMiddle);
9941   verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
9942   verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
9943   verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
9944   verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
9945   verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
9946   verifyFormat("auto Function(T) & -> void;", AlignMiddle);
9947   verifyFormat("void Fn(T const &) const &;", AlignMiddle);
9948   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
9949   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
9950                AlignMiddle);
9951   verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle);
9952   verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle);
9953   verifyFormat("template <typename T> void operator=(T) & noexcept;",
9954                AlignMiddle);
9955   verifyFormat("template <typename T> void operator=(T) & = default;",
9956                AlignMiddle);
9957   verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle);
9958   verifyFormat("template <typename T> void operator=(T) && = delete;",
9959                AlignMiddle);
9960   verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle);
9961   verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle);
9962 
9963   FormatStyle Spaces = getLLVMStyle();
9964   Spaces.SpacesInCStyleCastParentheses = true;
9965   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9966   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9967   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9968   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9969 
9970   Spaces.SpacesInCStyleCastParentheses = false;
9971   Spaces.SpacesInParentheses = true;
9972   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9973   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9974                Spaces);
9975   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9976   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9977 
9978   FormatStyle BreakTemplate = getLLVMStyle();
9979   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9980 
9981   verifyFormat("struct f {\n"
9982                "  template <class T>\n"
9983                "  int &foo(const std::string &str) &noexcept {}\n"
9984                "};",
9985                BreakTemplate);
9986 
9987   verifyFormat("struct f {\n"
9988                "  template <class T>\n"
9989                "  int &foo(const std::string &str) &&noexcept {}\n"
9990                "};",
9991                BreakTemplate);
9992 
9993   verifyFormat("struct f {\n"
9994                "  template <class T>\n"
9995                "  int &foo(const std::string &str) const &noexcept {}\n"
9996                "};",
9997                BreakTemplate);
9998 
9999   verifyFormat("struct f {\n"
10000                "  template <class T>\n"
10001                "  int &foo(const std::string &str) const &noexcept {}\n"
10002                "};",
10003                BreakTemplate);
10004 
10005   verifyFormat("struct f {\n"
10006                "  template <class T>\n"
10007                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
10008                "};",
10009                BreakTemplate);
10010 
10011   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
10012   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
10013       FormatStyle::BTDS_Yes;
10014   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
10015 
10016   verifyFormat("struct f {\n"
10017                "  template <class T>\n"
10018                "  int& foo(const std::string& str) & noexcept {}\n"
10019                "};",
10020                AlignLeftBreakTemplate);
10021 
10022   verifyFormat("struct f {\n"
10023                "  template <class T>\n"
10024                "  int& foo(const std::string& str) && noexcept {}\n"
10025                "};",
10026                AlignLeftBreakTemplate);
10027 
10028   verifyFormat("struct f {\n"
10029                "  template <class T>\n"
10030                "  int& foo(const std::string& str) const& noexcept {}\n"
10031                "};",
10032                AlignLeftBreakTemplate);
10033 
10034   verifyFormat("struct f {\n"
10035                "  template <class T>\n"
10036                "  int& foo(const std::string& str) const&& noexcept {}\n"
10037                "};",
10038                AlignLeftBreakTemplate);
10039 
10040   verifyFormat("struct f {\n"
10041                "  template <class T>\n"
10042                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
10043                "};",
10044                AlignLeftBreakTemplate);
10045 
10046   // The `&` in `Type&` should not be confused with a trailing `&` of
10047   // DEPRECATED(reason) member function.
10048   verifyFormat("struct f {\n"
10049                "  template <class T>\n"
10050                "  DEPRECATED(reason)\n"
10051                "  Type &foo(arguments) {}\n"
10052                "};",
10053                BreakTemplate);
10054 
10055   verifyFormat("struct f {\n"
10056                "  template <class T>\n"
10057                "  DEPRECATED(reason)\n"
10058                "  Type& foo(arguments) {}\n"
10059                "};",
10060                AlignLeftBreakTemplate);
10061 
10062   verifyFormat("void (*foopt)(int) = &func;");
10063 
10064   FormatStyle DerivePointerAlignment = getLLVMStyle();
10065   DerivePointerAlignment.DerivePointerAlignment = true;
10066   // There's always a space between the function and its trailing qualifiers.
10067   // This isn't evidence for PAS_Right (or for PAS_Left).
10068   std::string Prefix = "void a() &;\n"
10069                        "void b() &;\n";
10070   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10071   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10072   // Same if the function is an overloaded operator, and with &&.
10073   Prefix = "void operator()() &&;\n"
10074            "void operator()() &&;\n";
10075   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10076   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10077   // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
10078   Prefix = "void a() const &;\n"
10079            "void b() const &;\n";
10080   EXPECT_EQ(Prefix + "int *x;",
10081             format(Prefix + "int* x;", DerivePointerAlignment));
10082 }
10083 
10084 TEST_F(FormatTest, UnderstandsNewAndDelete) {
10085   verifyFormat("void f() {\n"
10086                "  A *a = new A;\n"
10087                "  A *a = new (placement) A;\n"
10088                "  delete a;\n"
10089                "  delete (A *)a;\n"
10090                "}");
10091   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10092                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10093   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10094                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10095                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10096   verifyFormat("delete[] h->p;");
10097   verifyFormat("delete[] (void *)p;");
10098 
10099   verifyFormat("void operator delete(void *foo) ATTRIB;");
10100   verifyFormat("void operator new(void *foo) ATTRIB;");
10101   verifyFormat("void operator delete[](void *foo) ATTRIB;");
10102   verifyFormat("void operator delete(void *ptr) noexcept;");
10103 
10104   EXPECT_EQ("void new(link p);\n"
10105             "void delete(link p);\n",
10106             format("void new (link p);\n"
10107                    "void delete (link p);\n"));
10108 }
10109 
10110 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
10111   verifyFormat("int *f(int *a) {}");
10112   verifyFormat("int main(int argc, char **argv) {}");
10113   verifyFormat("Test::Test(int b) : a(b * b) {}");
10114   verifyIndependentOfContext("f(a, *a);");
10115   verifyFormat("void g() { f(*a); }");
10116   verifyIndependentOfContext("int a = b * 10;");
10117   verifyIndependentOfContext("int a = 10 * b;");
10118   verifyIndependentOfContext("int a = b * c;");
10119   verifyIndependentOfContext("int a += b * c;");
10120   verifyIndependentOfContext("int a -= b * c;");
10121   verifyIndependentOfContext("int a *= b * c;");
10122   verifyIndependentOfContext("int a /= b * c;");
10123   verifyIndependentOfContext("int a = *b;");
10124   verifyIndependentOfContext("int a = *b * c;");
10125   verifyIndependentOfContext("int a = b * *c;");
10126   verifyIndependentOfContext("int a = b * (10);");
10127   verifyIndependentOfContext("S << b * (10);");
10128   verifyIndependentOfContext("return 10 * b;");
10129   verifyIndependentOfContext("return *b * *c;");
10130   verifyIndependentOfContext("return a & ~b;");
10131   verifyIndependentOfContext("f(b ? *c : *d);");
10132   verifyIndependentOfContext("int a = b ? *c : *d;");
10133   verifyIndependentOfContext("*b = a;");
10134   verifyIndependentOfContext("a * ~b;");
10135   verifyIndependentOfContext("a * !b;");
10136   verifyIndependentOfContext("a * +b;");
10137   verifyIndependentOfContext("a * -b;");
10138   verifyIndependentOfContext("a * ++b;");
10139   verifyIndependentOfContext("a * --b;");
10140   verifyIndependentOfContext("a[4] * b;");
10141   verifyIndependentOfContext("a[a * a] = 1;");
10142   verifyIndependentOfContext("f() * b;");
10143   verifyIndependentOfContext("a * [self dostuff];");
10144   verifyIndependentOfContext("int x = a * (a + b);");
10145   verifyIndependentOfContext("(a *)(a + b);");
10146   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
10147   verifyIndependentOfContext("int *pa = (int *)&a;");
10148   verifyIndependentOfContext("return sizeof(int **);");
10149   verifyIndependentOfContext("return sizeof(int ******);");
10150   verifyIndependentOfContext("return (int **&)a;");
10151   verifyIndependentOfContext("f((*PointerToArray)[10]);");
10152   verifyFormat("void f(Type (*parameter)[10]) {}");
10153   verifyFormat("void f(Type (&parameter)[10]) {}");
10154   verifyGoogleFormat("return sizeof(int**);");
10155   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
10156   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
10157   verifyFormat("auto a = [](int **&, int ***) {};");
10158   verifyFormat("auto PointerBinding = [](const char *S) {};");
10159   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
10160   verifyFormat("[](const decltype(*a) &value) {}");
10161   verifyFormat("[](const typeof(*a) &value) {}");
10162   verifyFormat("[](const _Atomic(a *) &value) {}");
10163   verifyFormat("[](const __underlying_type(a) &value) {}");
10164   verifyFormat("decltype(a * b) F();");
10165   verifyFormat("typeof(a * b) F();");
10166   verifyFormat("#define MACRO() [](A *a) { return 1; }");
10167   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
10168   verifyIndependentOfContext("typedef void (*f)(int *a);");
10169   verifyIndependentOfContext("int i{a * b};");
10170   verifyIndependentOfContext("aaa && aaa->f();");
10171   verifyIndependentOfContext("int x = ~*p;");
10172   verifyFormat("Constructor() : a(a), area(width * height) {}");
10173   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
10174   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
10175   verifyFormat("void f() { f(a, c * d); }");
10176   verifyFormat("void f() { f(new a(), c * d); }");
10177   verifyFormat("void f(const MyOverride &override);");
10178   verifyFormat("void f(const MyFinal &final);");
10179   verifyIndependentOfContext("bool a = f() && override.f();");
10180   verifyIndependentOfContext("bool a = f() && final.f();");
10181 
10182   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
10183 
10184   verifyIndependentOfContext("A<int *> a;");
10185   verifyIndependentOfContext("A<int **> a;");
10186   verifyIndependentOfContext("A<int *, int *> a;");
10187   verifyIndependentOfContext("A<int *[]> a;");
10188   verifyIndependentOfContext(
10189       "const char *const p = reinterpret_cast<const char *const>(q);");
10190   verifyIndependentOfContext("A<int **, int **> a;");
10191   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
10192   verifyFormat("for (char **a = b; *a; ++a) {\n}");
10193   verifyFormat("for (; a && b;) {\n}");
10194   verifyFormat("bool foo = true && [] { return false; }();");
10195 
10196   verifyFormat(
10197       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10198       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10199 
10200   verifyGoogleFormat("int const* a = &b;");
10201   verifyGoogleFormat("**outparam = 1;");
10202   verifyGoogleFormat("*outparam = a * b;");
10203   verifyGoogleFormat("int main(int argc, char** argv) {}");
10204   verifyGoogleFormat("A<int*> a;");
10205   verifyGoogleFormat("A<int**> a;");
10206   verifyGoogleFormat("A<int*, int*> a;");
10207   verifyGoogleFormat("A<int**, int**> a;");
10208   verifyGoogleFormat("f(b ? *c : *d);");
10209   verifyGoogleFormat("int a = b ? *c : *d;");
10210   verifyGoogleFormat("Type* t = **x;");
10211   verifyGoogleFormat("Type* t = *++*x;");
10212   verifyGoogleFormat("*++*x;");
10213   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
10214   verifyGoogleFormat("Type* t = x++ * y;");
10215   verifyGoogleFormat(
10216       "const char* const p = reinterpret_cast<const char* const>(q);");
10217   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
10218   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
10219   verifyGoogleFormat("template <typename T>\n"
10220                      "void f(int i = 0, SomeType** temps = NULL);");
10221 
10222   FormatStyle Left = getLLVMStyle();
10223   Left.PointerAlignment = FormatStyle::PAS_Left;
10224   verifyFormat("x = *a(x) = *a(y);", Left);
10225   verifyFormat("for (;; *a = b) {\n}", Left);
10226   verifyFormat("return *this += 1;", Left);
10227   verifyFormat("throw *x;", Left);
10228   verifyFormat("delete *x;", Left);
10229   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
10230   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
10231   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
10232   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
10233   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
10234   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
10235   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
10236   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
10237   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
10238 
10239   verifyIndependentOfContext("a = *(x + y);");
10240   verifyIndependentOfContext("a = &(x + y);");
10241   verifyIndependentOfContext("*(x + y).call();");
10242   verifyIndependentOfContext("&(x + y)->call();");
10243   verifyFormat("void f() { &(*I).first; }");
10244 
10245   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
10246   verifyFormat("f(* /* confusing comment */ foo);");
10247   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
10248   verifyFormat("void foo(int * // this is the first paramters\n"
10249                "         ,\n"
10250                "         int second);");
10251   verifyFormat("double term = a * // first\n"
10252                "              b;");
10253   verifyFormat(
10254       "int *MyValues = {\n"
10255       "    *A, // Operator detection might be confused by the '{'\n"
10256       "    *BB // Operator detection might be confused by previous comment\n"
10257       "};");
10258 
10259   verifyIndependentOfContext("if (int *a = &b)");
10260   verifyIndependentOfContext("if (int &a = *b)");
10261   verifyIndependentOfContext("if (a & b[i])");
10262   verifyIndependentOfContext("if constexpr (a & b[i])");
10263   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
10264   verifyIndependentOfContext("if (a * (b * c))");
10265   verifyIndependentOfContext("if constexpr (a * (b * c))");
10266   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
10267   verifyIndependentOfContext("if (a::b::c::d & b[i])");
10268   verifyIndependentOfContext("if (*b[i])");
10269   verifyIndependentOfContext("if (int *a = (&b))");
10270   verifyIndependentOfContext("while (int *a = &b)");
10271   verifyIndependentOfContext("while (a * (b * c))");
10272   verifyIndependentOfContext("size = sizeof *a;");
10273   verifyIndependentOfContext("if (a && (b = c))");
10274   verifyFormat("void f() {\n"
10275                "  for (const int &v : Values) {\n"
10276                "  }\n"
10277                "}");
10278   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
10279   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
10280   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
10281 
10282   verifyFormat("#define A (!a * b)");
10283   verifyFormat("#define MACRO     \\\n"
10284                "  int *i = a * b; \\\n"
10285                "  void f(a *b);",
10286                getLLVMStyleWithColumns(19));
10287 
10288   verifyIndependentOfContext("A = new SomeType *[Length];");
10289   verifyIndependentOfContext("A = new SomeType *[Length]();");
10290   verifyIndependentOfContext("T **t = new T *;");
10291   verifyIndependentOfContext("T **t = new T *();");
10292   verifyGoogleFormat("A = new SomeType*[Length]();");
10293   verifyGoogleFormat("A = new SomeType*[Length];");
10294   verifyGoogleFormat("T** t = new T*;");
10295   verifyGoogleFormat("T** t = new T*();");
10296 
10297   verifyFormat("STATIC_ASSERT((a & b) == 0);");
10298   verifyFormat("STATIC_ASSERT(0 == (a & b));");
10299   verifyFormat("template <bool a, bool b> "
10300                "typename t::if<x && y>::type f() {}");
10301   verifyFormat("template <int *y> f() {}");
10302   verifyFormat("vector<int *> v;");
10303   verifyFormat("vector<int *const> v;");
10304   verifyFormat("vector<int *const **const *> v;");
10305   verifyFormat("vector<int *volatile> v;");
10306   verifyFormat("vector<a *_Nonnull> v;");
10307   verifyFormat("vector<a *_Nullable> v;");
10308   verifyFormat("vector<a *_Null_unspecified> v;");
10309   verifyFormat("vector<a *__ptr32> v;");
10310   verifyFormat("vector<a *__ptr64> v;");
10311   verifyFormat("vector<a *__capability> v;");
10312   FormatStyle TypeMacros = getLLVMStyle();
10313   TypeMacros.TypenameMacros = {"LIST"};
10314   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
10315   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
10316   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
10317   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
10318   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
10319 
10320   FormatStyle CustomQualifier = getLLVMStyle();
10321   // Add identifiers that should not be parsed as a qualifier by default.
10322   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10323   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
10324   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
10325   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
10326   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
10327   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
10328   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
10329   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
10330   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
10331   verifyFormat("vector<a * _NotAQualifier> v;");
10332   verifyFormat("vector<a * __not_a_qualifier> v;");
10333   verifyFormat("vector<a * b> v;");
10334   verifyFormat("foo<b && false>();");
10335   verifyFormat("foo<b & 1>();");
10336   verifyFormat("foo<b & (1)>();");
10337   verifyFormat("foo<b & (~0)>();");
10338   verifyFormat("foo<b & (true)>();");
10339   verifyFormat("foo<b & ((1))>();");
10340   verifyFormat("foo<b & (/*comment*/ 1)>();");
10341   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
10342   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
10343   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
10344   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
10345   verifyFormat(
10346       "template <class T, class = typename std::enable_if<\n"
10347       "                       std::is_integral<T>::value &&\n"
10348       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
10349       "void F();",
10350       getLLVMStyleWithColumns(70));
10351   verifyFormat("template <class T,\n"
10352                "          class = typename std::enable_if<\n"
10353                "              std::is_integral<T>::value &&\n"
10354                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
10355                "          class U>\n"
10356                "void F();",
10357                getLLVMStyleWithColumns(70));
10358   verifyFormat(
10359       "template <class T,\n"
10360       "          class = typename ::std::enable_if<\n"
10361       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
10362       "void F();",
10363       getGoogleStyleWithColumns(68));
10364 
10365   verifyIndependentOfContext("MACRO(int *i);");
10366   verifyIndependentOfContext("MACRO(auto *a);");
10367   verifyIndependentOfContext("MACRO(const A *a);");
10368   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10369   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10370   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10371   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10372   verifyIndependentOfContext("MACRO(A *const a);");
10373   verifyIndependentOfContext("MACRO(A *restrict a);");
10374   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10375   verifyIndependentOfContext("MACRO(A *__restrict a);");
10376   verifyIndependentOfContext("MACRO(A *volatile a);");
10377   verifyIndependentOfContext("MACRO(A *__volatile a);");
10378   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10379   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10380   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10381   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10382   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10383   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10384   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10385   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10386   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10387   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10388   verifyIndependentOfContext("MACRO(A *__capability);");
10389   verifyIndependentOfContext("MACRO(A &__capability);");
10390   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10391   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10392   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10393   // a type declaration:
10394   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10395   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10396   // Also check that TypenameMacros prevents parsing it as multiplication:
10397   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10398   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10399 
10400   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10401   verifyFormat("void f() { f(float{1}, a * a); }");
10402   verifyFormat("void f() { f(float(1), a * a); }");
10403 
10404   verifyFormat("f((void (*)(int))g);");
10405   verifyFormat("f((void (&)(int))g);");
10406   verifyFormat("f((void (^)(int))g);");
10407 
10408   // FIXME: Is there a way to make this work?
10409   // verifyIndependentOfContext("MACRO(A *a);");
10410   verifyFormat("MACRO(A &B);");
10411   verifyFormat("MACRO(A *B);");
10412   verifyFormat("void f() { MACRO(A * B); }");
10413   verifyFormat("void f() { MACRO(A & B); }");
10414 
10415   // This lambda was mis-formatted after D88956 (treating it as a binop):
10416   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10417   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10418   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10419   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10420 
10421   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10422   verifyFormat("return options != nullptr && operator==(*options);");
10423 
10424   EXPECT_EQ("#define OP(x)                                    \\\n"
10425             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10426             "    return s << a.DebugString();                 \\\n"
10427             "  }",
10428             format("#define OP(x) \\\n"
10429                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10430                    "    return s << a.DebugString(); \\\n"
10431                    "  }",
10432                    getLLVMStyleWithColumns(50)));
10433 
10434   // FIXME: We cannot handle this case yet; we might be able to figure out that
10435   // foo<x> d > v; doesn't make sense.
10436   verifyFormat("foo<a<b && c> d> v;");
10437 
10438   FormatStyle PointerMiddle = getLLVMStyle();
10439   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10440   verifyFormat("delete *x;", PointerMiddle);
10441   verifyFormat("int * x;", PointerMiddle);
10442   verifyFormat("int *[] x;", PointerMiddle);
10443   verifyFormat("template <int * y> f() {}", PointerMiddle);
10444   verifyFormat("int * f(int * a) {}", PointerMiddle);
10445   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10446   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10447   verifyFormat("A<int *> a;", PointerMiddle);
10448   verifyFormat("A<int **> a;", PointerMiddle);
10449   verifyFormat("A<int *, int *> a;", PointerMiddle);
10450   verifyFormat("A<int *[]> a;", PointerMiddle);
10451   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10452   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10453   verifyFormat("T ** t = new T *;", PointerMiddle);
10454 
10455   // Member function reference qualifiers aren't binary operators.
10456   verifyFormat("string // break\n"
10457                "operator()() & {}");
10458   verifyFormat("string // break\n"
10459                "operator()() && {}");
10460   verifyGoogleFormat("template <typename T>\n"
10461                      "auto x() & -> int {}");
10462 
10463   // Should be binary operators when used as an argument expression (overloaded
10464   // operator invoked as a member function).
10465   verifyFormat("void f() { a.operator()(a * a); }");
10466   verifyFormat("void f() { a->operator()(a & a); }");
10467   verifyFormat("void f() { a.operator()(*a & *a); }");
10468   verifyFormat("void f() { a->operator()(*a * *a); }");
10469 
10470   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10471   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10472 }
10473 
10474 TEST_F(FormatTest, UnderstandsAttributes) {
10475   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10476   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10477                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10478   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10479   FormatStyle AfterType = getLLVMStyle();
10480   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10481   verifyFormat("__attribute__((nodebug)) void\n"
10482                "foo() {}\n",
10483                AfterType);
10484   verifyFormat("__unused void\n"
10485                "foo() {}",
10486                AfterType);
10487 
10488   FormatStyle CustomAttrs = getLLVMStyle();
10489   CustomAttrs.AttributeMacros.push_back("__unused");
10490   CustomAttrs.AttributeMacros.push_back("__attr1");
10491   CustomAttrs.AttributeMacros.push_back("__attr2");
10492   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10493   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10494   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10495   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10496   // Check that it is parsed as a multiplication without AttributeMacros and
10497   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10498   verifyFormat("vector<SomeType * __attr1> v;");
10499   verifyFormat("vector<SomeType __attr1 *> v;");
10500   verifyFormat("vector<SomeType __attr1 *const> v;");
10501   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10502   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10503   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10504   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10505   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10506   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10507   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10508   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10509 
10510   // Check that these are not parsed as function declarations:
10511   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10512   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10513   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10514   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10515   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10516   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10517   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10518   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10519   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10520   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10521 }
10522 
10523 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10524   // Check that qualifiers on pointers don't break parsing of casts.
10525   verifyFormat("x = (foo *const)*v;");
10526   verifyFormat("x = (foo *volatile)*v;");
10527   verifyFormat("x = (foo *restrict)*v;");
10528   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10529   verifyFormat("x = (foo *_Nonnull)*v;");
10530   verifyFormat("x = (foo *_Nullable)*v;");
10531   verifyFormat("x = (foo *_Null_unspecified)*v;");
10532   verifyFormat("x = (foo *_Nonnull)*v;");
10533   verifyFormat("x = (foo *[[clang::attr]])*v;");
10534   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10535   verifyFormat("x = (foo *__ptr32)*v;");
10536   verifyFormat("x = (foo *__ptr64)*v;");
10537   verifyFormat("x = (foo *__capability)*v;");
10538 
10539   // Check that we handle multiple trailing qualifiers and skip them all to
10540   // determine that the expression is a cast to a pointer type.
10541   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10542   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10543   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10544   StringRef AllQualifiers =
10545       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10546       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10547   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10548   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10549 
10550   // Also check that address-of is not parsed as a binary bitwise-and:
10551   verifyFormat("x = (foo *const)&v;");
10552   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10553   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10554 
10555   // Check custom qualifiers:
10556   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10557   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10558   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10559   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10560   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10561                CustomQualifier);
10562   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10563                CustomQualifier);
10564 
10565   // Check that unknown identifiers result in binary operator parsing:
10566   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10567   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10568 }
10569 
10570 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10571   verifyFormat("SomeType s [[unused]] (InitValue);");
10572   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10573   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10574   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10575   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10576   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10577                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10578   verifyFormat("[[nodiscard]] bool f() { return false; }");
10579   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10580   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10581   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10582   verifyFormat("[[nodiscard]] ::qualified_type f();");
10583 
10584   // Make sure we do not mistake attributes for array subscripts.
10585   verifyFormat("int a() {}\n"
10586                "[[unused]] int b() {}\n");
10587   verifyFormat("NSArray *arr;\n"
10588                "arr[[Foo() bar]];");
10589 
10590   // On the other hand, we still need to correctly find array subscripts.
10591   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10592 
10593   // Make sure that we do not mistake Objective-C method inside array literals
10594   // as attributes, even if those method names are also keywords.
10595   verifyFormat("@[ [foo bar] ];");
10596   verifyFormat("@[ [NSArray class] ];");
10597   verifyFormat("@[ [foo enum] ];");
10598 
10599   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10600 
10601   // Make sure we do not parse attributes as lambda introducers.
10602   FormatStyle MultiLineFunctions = getLLVMStyle();
10603   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10604   verifyFormat("[[unused]] int b() {\n"
10605                "  return 42;\n"
10606                "}\n",
10607                MultiLineFunctions);
10608 }
10609 
10610 TEST_F(FormatTest, AttributeClass) {
10611   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10612   verifyFormat("class S {\n"
10613                "  S(S&&) = default;\n"
10614                "};",
10615                Style);
10616   verifyFormat("class [[nodiscard]] S {\n"
10617                "  S(S&&) = default;\n"
10618                "};",
10619                Style);
10620   verifyFormat("class __attribute((maybeunused)) S {\n"
10621                "  S(S&&) = default;\n"
10622                "};",
10623                Style);
10624   verifyFormat("struct S {\n"
10625                "  S(S&&) = default;\n"
10626                "};",
10627                Style);
10628   verifyFormat("struct [[nodiscard]] S {\n"
10629                "  S(S&&) = default;\n"
10630                "};",
10631                Style);
10632 }
10633 
10634 TEST_F(FormatTest, AttributesAfterMacro) {
10635   FormatStyle Style = getLLVMStyle();
10636   verifyFormat("MACRO;\n"
10637                "__attribute__((maybe_unused)) int foo() {\n"
10638                "  //...\n"
10639                "}");
10640 
10641   verifyFormat("MACRO;\n"
10642                "[[nodiscard]] int foo() {\n"
10643                "  //...\n"
10644                "}");
10645 
10646   EXPECT_EQ("MACRO\n\n"
10647             "__attribute__((maybe_unused)) int foo() {\n"
10648             "  //...\n"
10649             "}",
10650             format("MACRO\n\n"
10651                    "__attribute__((maybe_unused)) int foo() {\n"
10652                    "  //...\n"
10653                    "}"));
10654 
10655   EXPECT_EQ("MACRO\n\n"
10656             "[[nodiscard]] int foo() {\n"
10657             "  //...\n"
10658             "}",
10659             format("MACRO\n\n"
10660                    "[[nodiscard]] int foo() {\n"
10661                    "  //...\n"
10662                    "}"));
10663 }
10664 
10665 TEST_F(FormatTest, AttributePenaltyBreaking) {
10666   FormatStyle Style = getLLVMStyle();
10667   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10668                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10669                Style);
10670   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10671                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10672                Style);
10673   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10674                "shared_ptr<ALongTypeName> &C d) {\n}",
10675                Style);
10676 }
10677 
10678 TEST_F(FormatTest, UnderstandsEllipsis) {
10679   FormatStyle Style = getLLVMStyle();
10680   verifyFormat("int printf(const char *fmt, ...);");
10681   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10682   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10683 
10684   verifyFormat("template <int *...PP> a;", Style);
10685 
10686   Style.PointerAlignment = FormatStyle::PAS_Left;
10687   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10688 
10689   verifyFormat("template <int*... PP> a;", Style);
10690 
10691   Style.PointerAlignment = FormatStyle::PAS_Middle;
10692   verifyFormat("template <int *... PP> a;", Style);
10693 }
10694 
10695 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10696   EXPECT_EQ("int *a;\n"
10697             "int *a;\n"
10698             "int *a;",
10699             format("int *a;\n"
10700                    "int* a;\n"
10701                    "int *a;",
10702                    getGoogleStyle()));
10703   EXPECT_EQ("int* a;\n"
10704             "int* a;\n"
10705             "int* a;",
10706             format("int* a;\n"
10707                    "int* a;\n"
10708                    "int *a;",
10709                    getGoogleStyle()));
10710   EXPECT_EQ("int *a;\n"
10711             "int *a;\n"
10712             "int *a;",
10713             format("int *a;\n"
10714                    "int * a;\n"
10715                    "int *  a;",
10716                    getGoogleStyle()));
10717   EXPECT_EQ("auto x = [] {\n"
10718             "  int *a;\n"
10719             "  int *a;\n"
10720             "  int *a;\n"
10721             "};",
10722             format("auto x=[]{int *a;\n"
10723                    "int * a;\n"
10724                    "int *  a;};",
10725                    getGoogleStyle()));
10726 }
10727 
10728 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10729   verifyFormat("int f(int &&a) {}");
10730   verifyFormat("int f(int a, char &&b) {}");
10731   verifyFormat("void f() { int &&a = b; }");
10732   verifyGoogleFormat("int f(int a, char&& b) {}");
10733   verifyGoogleFormat("void f() { int&& a = b; }");
10734 
10735   verifyIndependentOfContext("A<int &&> a;");
10736   verifyIndependentOfContext("A<int &&, int &&> a;");
10737   verifyGoogleFormat("A<int&&> a;");
10738   verifyGoogleFormat("A<int&&, int&&> a;");
10739 
10740   // Not rvalue references:
10741   verifyFormat("template <bool B, bool C> class A {\n"
10742                "  static_assert(B && C, \"Something is wrong\");\n"
10743                "};");
10744   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10745   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10746   verifyFormat("#define A(a, b) (a && b)");
10747 }
10748 
10749 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10750   verifyFormat("void f() {\n"
10751                "  x[aaaaaaaaa -\n"
10752                "    b] = 23;\n"
10753                "}",
10754                getLLVMStyleWithColumns(15));
10755 }
10756 
10757 TEST_F(FormatTest, FormatsCasts) {
10758   verifyFormat("Type *A = static_cast<Type *>(P);");
10759   verifyFormat("static_cast<Type *>(P);");
10760   verifyFormat("static_cast<Type &>(Fun)(Args);");
10761   verifyFormat("static_cast<Type &>(*Fun)(Args);");
10762   verifyFormat("if (static_cast<int>(A) + B >= 0)\n  ;");
10763   // Check that static_cast<...>(...) does not require the next token to be on
10764   // the same line.
10765   verifyFormat("some_loooong_output << something_something__ << "
10766                "static_cast<const void *>(R)\n"
10767                "                    << something;");
10768   verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
10769   verifyFormat("const_cast<Type &>(*Fun)(Args);");
10770   verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
10771   verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
10772   verifyFormat("Type *A = (Type *)P;");
10773   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10774   verifyFormat("int a = (int)(2.0f);");
10775   verifyFormat("int a = (int)2.0f;");
10776   verifyFormat("x[(int32)y];");
10777   verifyFormat("x = (int32)y;");
10778   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10779   verifyFormat("int a = (int)*b;");
10780   verifyFormat("int a = (int)2.0f;");
10781   verifyFormat("int a = (int)~0;");
10782   verifyFormat("int a = (int)++a;");
10783   verifyFormat("int a = (int)sizeof(int);");
10784   verifyFormat("int a = (int)+2;");
10785   verifyFormat("my_int a = (my_int)2.0f;");
10786   verifyFormat("my_int a = (my_int)sizeof(int);");
10787   verifyFormat("return (my_int)aaa;");
10788   verifyFormat("#define x ((int)-1)");
10789   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10790   verifyFormat("#define p(q) ((int *)&q)");
10791   verifyFormat("fn(a)(b) + 1;");
10792 
10793   verifyFormat("void f() { my_int a = (my_int)*b; }");
10794   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10795   verifyFormat("my_int a = (my_int)~0;");
10796   verifyFormat("my_int a = (my_int)++a;");
10797   verifyFormat("my_int a = (my_int)-2;");
10798   verifyFormat("my_int a = (my_int)1;");
10799   verifyFormat("my_int a = (my_int *)1;");
10800   verifyFormat("my_int a = (const my_int)-1;");
10801   verifyFormat("my_int a = (const my_int *)-1;");
10802   verifyFormat("my_int a = (my_int)(my_int)-1;");
10803   verifyFormat("my_int a = (ns::my_int)-2;");
10804   verifyFormat("case (my_int)ONE:");
10805   verifyFormat("auto x = (X)this;");
10806   // Casts in Obj-C style calls used to not be recognized as such.
10807   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10808 
10809   // FIXME: single value wrapped with paren will be treated as cast.
10810   verifyFormat("void f(int i = (kValue)*kMask) {}");
10811 
10812   verifyFormat("{ (void)F; }");
10813 
10814   // Don't break after a cast's
10815   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10816                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10817                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10818 
10819   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10820   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10821   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10822   verifyFormat("bool *y = (bool *)(void *)(x);");
10823   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10824   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10825   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10826   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10827 
10828   // These are not casts.
10829   verifyFormat("void f(int *) {}");
10830   verifyFormat("f(foo)->b;");
10831   verifyFormat("f(foo).b;");
10832   verifyFormat("f(foo)(b);");
10833   verifyFormat("f(foo)[b];");
10834   verifyFormat("[](foo) { return 4; }(bar);");
10835   verifyFormat("(*funptr)(foo)[4];");
10836   verifyFormat("funptrs[4](foo)[4];");
10837   verifyFormat("void f(int *);");
10838   verifyFormat("void f(int *) = 0;");
10839   verifyFormat("void f(SmallVector<int>) {}");
10840   verifyFormat("void f(SmallVector<int>);");
10841   verifyFormat("void f(SmallVector<int>) = 0;");
10842   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10843   verifyFormat("int a = sizeof(int) * b;");
10844   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10845   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10846   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10847   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10848 
10849   // These are not casts, but at some point were confused with casts.
10850   verifyFormat("virtual void foo(int *) override;");
10851   verifyFormat("virtual void foo(char &) const;");
10852   verifyFormat("virtual void foo(int *a, char *) const;");
10853   verifyFormat("int a = sizeof(int *) + b;");
10854   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10855   verifyFormat("bool b = f(g<int>) && c;");
10856   verifyFormat("typedef void (*f)(int i) func;");
10857   verifyFormat("void operator++(int) noexcept;");
10858   verifyFormat("void operator++(int &) noexcept;");
10859   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10860                "&) noexcept;");
10861   verifyFormat(
10862       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10863   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10864   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10865   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10866   verifyFormat("void operator delete(foo &) noexcept;");
10867   verifyFormat("void operator delete(foo) noexcept;");
10868   verifyFormat("void operator delete(int) noexcept;");
10869   verifyFormat("void operator delete(int &) noexcept;");
10870   verifyFormat("void operator delete(int &) volatile noexcept;");
10871   verifyFormat("void operator delete(int &) const");
10872   verifyFormat("void operator delete(int &) = default");
10873   verifyFormat("void operator delete(int &) = delete");
10874   verifyFormat("void operator delete(int &) [[noreturn]]");
10875   verifyFormat("void operator delete(int &) throw();");
10876   verifyFormat("void operator delete(int &) throw(int);");
10877   verifyFormat("auto operator delete(int &) -> int;");
10878   verifyFormat("auto operator delete(int &) override");
10879   verifyFormat("auto operator delete(int &) final");
10880 
10881   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10882                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10883   // FIXME: The indentation here is not ideal.
10884   verifyFormat(
10885       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10886       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10887       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10888 }
10889 
10890 TEST_F(FormatTest, FormatsFunctionTypes) {
10891   verifyFormat("A<bool()> a;");
10892   verifyFormat("A<SomeType()> a;");
10893   verifyFormat("A<void (*)(int, std::string)> a;");
10894   verifyFormat("A<void *(int)>;");
10895   verifyFormat("void *(*a)(int *, SomeType *);");
10896   verifyFormat("int (*func)(void *);");
10897   verifyFormat("void f() { int (*func)(void *); }");
10898   verifyFormat("template <class CallbackClass>\n"
10899                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10900 
10901   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10902   verifyGoogleFormat("void* (*a)(int);");
10903   verifyGoogleFormat(
10904       "template <class CallbackClass>\n"
10905       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10906 
10907   // Other constructs can look somewhat like function types:
10908   verifyFormat("A<sizeof(*x)> a;");
10909   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10910   verifyFormat("some_var = function(*some_pointer_var)[0];");
10911   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10912   verifyFormat("int x = f(&h)();");
10913   verifyFormat("returnsFunction(&param1, &param2)(param);");
10914   verifyFormat("std::function<\n"
10915                "    LooooooooooongTemplatedType<\n"
10916                "        SomeType>*(\n"
10917                "        LooooooooooooooooongType type)>\n"
10918                "    function;",
10919                getGoogleStyleWithColumns(40));
10920 }
10921 
10922 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10923   verifyFormat("A (*foo_)[6];");
10924   verifyFormat("vector<int> (*foo_)[6];");
10925 }
10926 
10927 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10928   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10929                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10930   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10931                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10932   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10933                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10934 
10935   // Different ways of ()-initializiation.
10936   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10937                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10938   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10939                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10940   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10941                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10942   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10943                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10944 
10945   // Lambdas should not confuse the variable declaration heuristic.
10946   verifyFormat("LooooooooooooooooongType\n"
10947                "    variable(nullptr, [](A *a) {});",
10948                getLLVMStyleWithColumns(40));
10949 }
10950 
10951 TEST_F(FormatTest, BreaksLongDeclarations) {
10952   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10953                "    AnotherNameForTheLongType;");
10954   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10955                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10956   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10957                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10958   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10959                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10960   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10961                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10962   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10963                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10964   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10965                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10966   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10967                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10968   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10969                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10970   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10971                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10972   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10973                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10974   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10975                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10976   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10977                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10978   FormatStyle Indented = getLLVMStyle();
10979   Indented.IndentWrappedFunctionNames = true;
10980   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10981                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10982                Indented);
10983   verifyFormat(
10984       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10985       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10986       Indented);
10987   verifyFormat(
10988       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10989       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10990       Indented);
10991   verifyFormat(
10992       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10993       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10994       Indented);
10995 
10996   // FIXME: Without the comment, this breaks after "(".
10997   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10998                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10999                getGoogleStyle());
11000 
11001   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
11002                "                  int LoooooooooooooooooooongParam2) {}");
11003   verifyFormat(
11004       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
11005       "                                   SourceLocation L, IdentifierIn *II,\n"
11006       "                                   Type *T) {}");
11007   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
11008                "ReallyReaaallyLongFunctionName(\n"
11009                "    const std::string &SomeParameter,\n"
11010                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11011                "        &ReallyReallyLongParameterName,\n"
11012                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11013                "        &AnotherLongParameterName) {}");
11014   verifyFormat("template <typename A>\n"
11015                "SomeLoooooooooooooooooooooongType<\n"
11016                "    typename some_namespace::SomeOtherType<A>::Type>\n"
11017                "Function() {}");
11018 
11019   verifyGoogleFormat(
11020       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
11021       "    aaaaaaaaaaaaaaaaaaaaaaa;");
11022   verifyGoogleFormat(
11023       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
11024       "                                   SourceLocation L) {}");
11025   verifyGoogleFormat(
11026       "some_namespace::LongReturnType\n"
11027       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
11028       "    int first_long_parameter, int second_parameter) {}");
11029 
11030   verifyGoogleFormat("template <typename T>\n"
11031                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11032                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
11033   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11034                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
11035 
11036   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
11037                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11038                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11039   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11040                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11041                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
11042   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11043                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
11044                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
11045                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11046 
11047   verifyFormat("template <typename T> // Templates on own line.\n"
11048                "static int            // Some comment.\n"
11049                "MyFunction(int a);",
11050                getLLVMStyle());
11051 }
11052 
11053 TEST_F(FormatTest, FormatsAccessModifiers) {
11054   FormatStyle Style = getLLVMStyle();
11055   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
11056             FormatStyle::ELBAMS_LogicalBlock);
11057   verifyFormat("struct foo {\n"
11058                "private:\n"
11059                "  void f() {}\n"
11060                "\n"
11061                "private:\n"
11062                "  int i;\n"
11063                "\n"
11064                "protected:\n"
11065                "  int j;\n"
11066                "};\n",
11067                Style);
11068   verifyFormat("struct foo {\n"
11069                "private:\n"
11070                "  void f() {}\n"
11071                "\n"
11072                "private:\n"
11073                "  int i;\n"
11074                "\n"
11075                "protected:\n"
11076                "  int j;\n"
11077                "};\n",
11078                "struct foo {\n"
11079                "private:\n"
11080                "  void f() {}\n"
11081                "private:\n"
11082                "  int i;\n"
11083                "protected:\n"
11084                "  int j;\n"
11085                "};\n",
11086                Style);
11087   verifyFormat("struct foo { /* comment */\n"
11088                "private:\n"
11089                "  int i;\n"
11090                "  // comment\n"
11091                "private:\n"
11092                "  int j;\n"
11093                "};\n",
11094                Style);
11095   verifyFormat("struct foo {\n"
11096                "#ifdef FOO\n"
11097                "#endif\n"
11098                "private:\n"
11099                "  int i;\n"
11100                "#ifdef FOO\n"
11101                "private:\n"
11102                "#endif\n"
11103                "  int j;\n"
11104                "};\n",
11105                Style);
11106   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11107   verifyFormat("struct foo {\n"
11108                "private:\n"
11109                "  void f() {}\n"
11110                "private:\n"
11111                "  int i;\n"
11112                "protected:\n"
11113                "  int j;\n"
11114                "};\n",
11115                Style);
11116   verifyFormat("struct foo {\n"
11117                "private:\n"
11118                "  void f() {}\n"
11119                "private:\n"
11120                "  int i;\n"
11121                "protected:\n"
11122                "  int j;\n"
11123                "};\n",
11124                "struct foo {\n"
11125                "\n"
11126                "private:\n"
11127                "  void f() {}\n"
11128                "\n"
11129                "private:\n"
11130                "  int i;\n"
11131                "\n"
11132                "protected:\n"
11133                "  int j;\n"
11134                "};\n",
11135                Style);
11136   verifyFormat("struct foo { /* comment */\n"
11137                "private:\n"
11138                "  int i;\n"
11139                "  // comment\n"
11140                "private:\n"
11141                "  int j;\n"
11142                "};\n",
11143                "struct foo { /* comment */\n"
11144                "\n"
11145                "private:\n"
11146                "  int i;\n"
11147                "  // comment\n"
11148                "\n"
11149                "private:\n"
11150                "  int j;\n"
11151                "};\n",
11152                Style);
11153   verifyFormat("struct foo {\n"
11154                "#ifdef FOO\n"
11155                "#endif\n"
11156                "private:\n"
11157                "  int i;\n"
11158                "#ifdef FOO\n"
11159                "private:\n"
11160                "#endif\n"
11161                "  int j;\n"
11162                "};\n",
11163                "struct foo {\n"
11164                "#ifdef FOO\n"
11165                "#endif\n"
11166                "\n"
11167                "private:\n"
11168                "  int i;\n"
11169                "#ifdef FOO\n"
11170                "\n"
11171                "private:\n"
11172                "#endif\n"
11173                "  int j;\n"
11174                "};\n",
11175                Style);
11176   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11177   verifyFormat("struct foo {\n"
11178                "private:\n"
11179                "  void f() {}\n"
11180                "\n"
11181                "private:\n"
11182                "  int i;\n"
11183                "\n"
11184                "protected:\n"
11185                "  int j;\n"
11186                "};\n",
11187                Style);
11188   verifyFormat("struct foo {\n"
11189                "private:\n"
11190                "  void f() {}\n"
11191                "\n"
11192                "private:\n"
11193                "  int i;\n"
11194                "\n"
11195                "protected:\n"
11196                "  int j;\n"
11197                "};\n",
11198                "struct foo {\n"
11199                "private:\n"
11200                "  void f() {}\n"
11201                "private:\n"
11202                "  int i;\n"
11203                "protected:\n"
11204                "  int j;\n"
11205                "};\n",
11206                Style);
11207   verifyFormat("struct foo { /* comment */\n"
11208                "private:\n"
11209                "  int i;\n"
11210                "  // comment\n"
11211                "\n"
11212                "private:\n"
11213                "  int j;\n"
11214                "};\n",
11215                "struct foo { /* comment */\n"
11216                "private:\n"
11217                "  int i;\n"
11218                "  // comment\n"
11219                "\n"
11220                "private:\n"
11221                "  int j;\n"
11222                "};\n",
11223                Style);
11224   verifyFormat("struct foo {\n"
11225                "#ifdef FOO\n"
11226                "#endif\n"
11227                "\n"
11228                "private:\n"
11229                "  int i;\n"
11230                "#ifdef FOO\n"
11231                "\n"
11232                "private:\n"
11233                "#endif\n"
11234                "  int j;\n"
11235                "};\n",
11236                "struct foo {\n"
11237                "#ifdef FOO\n"
11238                "#endif\n"
11239                "private:\n"
11240                "  int i;\n"
11241                "#ifdef FOO\n"
11242                "private:\n"
11243                "#endif\n"
11244                "  int j;\n"
11245                "};\n",
11246                Style);
11247   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11248   EXPECT_EQ("struct foo {\n"
11249             "\n"
11250             "private:\n"
11251             "  void f() {}\n"
11252             "\n"
11253             "private:\n"
11254             "  int i;\n"
11255             "\n"
11256             "protected:\n"
11257             "  int j;\n"
11258             "};\n",
11259             format("struct foo {\n"
11260                    "\n"
11261                    "private:\n"
11262                    "  void f() {}\n"
11263                    "\n"
11264                    "private:\n"
11265                    "  int i;\n"
11266                    "\n"
11267                    "protected:\n"
11268                    "  int j;\n"
11269                    "};\n",
11270                    Style));
11271   verifyFormat("struct foo {\n"
11272                "private:\n"
11273                "  void f() {}\n"
11274                "private:\n"
11275                "  int i;\n"
11276                "protected:\n"
11277                "  int j;\n"
11278                "};\n",
11279                Style);
11280   EXPECT_EQ("struct foo { /* comment */\n"
11281             "\n"
11282             "private:\n"
11283             "  int i;\n"
11284             "  // comment\n"
11285             "\n"
11286             "private:\n"
11287             "  int j;\n"
11288             "};\n",
11289             format("struct foo { /* comment */\n"
11290                    "\n"
11291                    "private:\n"
11292                    "  int i;\n"
11293                    "  // comment\n"
11294                    "\n"
11295                    "private:\n"
11296                    "  int j;\n"
11297                    "};\n",
11298                    Style));
11299   verifyFormat("struct foo { /* comment */\n"
11300                "private:\n"
11301                "  int i;\n"
11302                "  // comment\n"
11303                "private:\n"
11304                "  int j;\n"
11305                "};\n",
11306                Style);
11307   EXPECT_EQ("struct foo {\n"
11308             "#ifdef FOO\n"
11309             "#endif\n"
11310             "\n"
11311             "private:\n"
11312             "  int i;\n"
11313             "#ifdef FOO\n"
11314             "\n"
11315             "private:\n"
11316             "#endif\n"
11317             "  int j;\n"
11318             "};\n",
11319             format("struct foo {\n"
11320                    "#ifdef FOO\n"
11321                    "#endif\n"
11322                    "\n"
11323                    "private:\n"
11324                    "  int i;\n"
11325                    "#ifdef FOO\n"
11326                    "\n"
11327                    "private:\n"
11328                    "#endif\n"
11329                    "  int j;\n"
11330                    "};\n",
11331                    Style));
11332   verifyFormat("struct foo {\n"
11333                "#ifdef FOO\n"
11334                "#endif\n"
11335                "private:\n"
11336                "  int i;\n"
11337                "#ifdef FOO\n"
11338                "private:\n"
11339                "#endif\n"
11340                "  int j;\n"
11341                "};\n",
11342                Style);
11343 
11344   FormatStyle NoEmptyLines = getLLVMStyle();
11345   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11346   verifyFormat("struct foo {\n"
11347                "private:\n"
11348                "  void f() {}\n"
11349                "\n"
11350                "private:\n"
11351                "  int i;\n"
11352                "\n"
11353                "public:\n"
11354                "protected:\n"
11355                "  int j;\n"
11356                "};\n",
11357                NoEmptyLines);
11358 
11359   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11360   verifyFormat("struct foo {\n"
11361                "private:\n"
11362                "  void f() {}\n"
11363                "private:\n"
11364                "  int i;\n"
11365                "public:\n"
11366                "protected:\n"
11367                "  int j;\n"
11368                "};\n",
11369                NoEmptyLines);
11370 
11371   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11372   verifyFormat("struct foo {\n"
11373                "private:\n"
11374                "  void f() {}\n"
11375                "\n"
11376                "private:\n"
11377                "  int i;\n"
11378                "\n"
11379                "public:\n"
11380                "\n"
11381                "protected:\n"
11382                "  int j;\n"
11383                "};\n",
11384                NoEmptyLines);
11385 }
11386 
11387 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11388 
11389   FormatStyle Style = getLLVMStyle();
11390   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11391   verifyFormat("struct foo {\n"
11392                "private:\n"
11393                "  void f() {}\n"
11394                "\n"
11395                "private:\n"
11396                "  int i;\n"
11397                "\n"
11398                "protected:\n"
11399                "  int j;\n"
11400                "};\n",
11401                Style);
11402 
11403   // Check if lines are removed.
11404   verifyFormat("struct foo {\n"
11405                "private:\n"
11406                "  void f() {}\n"
11407                "\n"
11408                "private:\n"
11409                "  int i;\n"
11410                "\n"
11411                "protected:\n"
11412                "  int j;\n"
11413                "};\n",
11414                "struct foo {\n"
11415                "private:\n"
11416                "\n"
11417                "  void f() {}\n"
11418                "\n"
11419                "private:\n"
11420                "\n"
11421                "  int i;\n"
11422                "\n"
11423                "protected:\n"
11424                "\n"
11425                "  int j;\n"
11426                "};\n",
11427                Style);
11428 
11429   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11430   verifyFormat("struct foo {\n"
11431                "private:\n"
11432                "\n"
11433                "  void f() {}\n"
11434                "\n"
11435                "private:\n"
11436                "\n"
11437                "  int i;\n"
11438                "\n"
11439                "protected:\n"
11440                "\n"
11441                "  int j;\n"
11442                "};\n",
11443                Style);
11444 
11445   // Check if lines are added.
11446   verifyFormat("struct foo {\n"
11447                "private:\n"
11448                "\n"
11449                "  void f() {}\n"
11450                "\n"
11451                "private:\n"
11452                "\n"
11453                "  int i;\n"
11454                "\n"
11455                "protected:\n"
11456                "\n"
11457                "  int j;\n"
11458                "};\n",
11459                "struct foo {\n"
11460                "private:\n"
11461                "  void f() {}\n"
11462                "\n"
11463                "private:\n"
11464                "  int i;\n"
11465                "\n"
11466                "protected:\n"
11467                "  int j;\n"
11468                "};\n",
11469                Style);
11470 
11471   // Leave tests rely on the code layout, test::messUp can not be used.
11472   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11473   Style.MaxEmptyLinesToKeep = 0u;
11474   verifyFormat("struct foo {\n"
11475                "private:\n"
11476                "  void f() {}\n"
11477                "\n"
11478                "private:\n"
11479                "  int i;\n"
11480                "\n"
11481                "protected:\n"
11482                "  int j;\n"
11483                "};\n",
11484                Style);
11485 
11486   // Check if MaxEmptyLinesToKeep is respected.
11487   EXPECT_EQ("struct foo {\n"
11488             "private:\n"
11489             "  void f() {}\n"
11490             "\n"
11491             "private:\n"
11492             "  int i;\n"
11493             "\n"
11494             "protected:\n"
11495             "  int j;\n"
11496             "};\n",
11497             format("struct foo {\n"
11498                    "private:\n"
11499                    "\n\n\n"
11500                    "  void f() {}\n"
11501                    "\n"
11502                    "private:\n"
11503                    "\n\n\n"
11504                    "  int i;\n"
11505                    "\n"
11506                    "protected:\n"
11507                    "\n\n\n"
11508                    "  int j;\n"
11509                    "};\n",
11510                    Style));
11511 
11512   Style.MaxEmptyLinesToKeep = 1u;
11513   EXPECT_EQ("struct foo {\n"
11514             "private:\n"
11515             "\n"
11516             "  void f() {}\n"
11517             "\n"
11518             "private:\n"
11519             "\n"
11520             "  int i;\n"
11521             "\n"
11522             "protected:\n"
11523             "\n"
11524             "  int j;\n"
11525             "};\n",
11526             format("struct foo {\n"
11527                    "private:\n"
11528                    "\n"
11529                    "  void f() {}\n"
11530                    "\n"
11531                    "private:\n"
11532                    "\n"
11533                    "  int i;\n"
11534                    "\n"
11535                    "protected:\n"
11536                    "\n"
11537                    "  int j;\n"
11538                    "};\n",
11539                    Style));
11540   // Check if no lines are kept.
11541   EXPECT_EQ("struct foo {\n"
11542             "private:\n"
11543             "  void f() {}\n"
11544             "\n"
11545             "private:\n"
11546             "  int i;\n"
11547             "\n"
11548             "protected:\n"
11549             "  int j;\n"
11550             "};\n",
11551             format("struct foo {\n"
11552                    "private:\n"
11553                    "  void f() {}\n"
11554                    "\n"
11555                    "private:\n"
11556                    "  int i;\n"
11557                    "\n"
11558                    "protected:\n"
11559                    "  int j;\n"
11560                    "};\n",
11561                    Style));
11562   // Check if MaxEmptyLinesToKeep is respected.
11563   EXPECT_EQ("struct foo {\n"
11564             "private:\n"
11565             "\n"
11566             "  void f() {}\n"
11567             "\n"
11568             "private:\n"
11569             "\n"
11570             "  int i;\n"
11571             "\n"
11572             "protected:\n"
11573             "\n"
11574             "  int j;\n"
11575             "};\n",
11576             format("struct foo {\n"
11577                    "private:\n"
11578                    "\n\n\n"
11579                    "  void f() {}\n"
11580                    "\n"
11581                    "private:\n"
11582                    "\n\n\n"
11583                    "  int i;\n"
11584                    "\n"
11585                    "protected:\n"
11586                    "\n\n\n"
11587                    "  int j;\n"
11588                    "};\n",
11589                    Style));
11590 
11591   Style.MaxEmptyLinesToKeep = 10u;
11592   EXPECT_EQ("struct foo {\n"
11593             "private:\n"
11594             "\n\n\n"
11595             "  void f() {}\n"
11596             "\n"
11597             "private:\n"
11598             "\n\n\n"
11599             "  int i;\n"
11600             "\n"
11601             "protected:\n"
11602             "\n\n\n"
11603             "  int j;\n"
11604             "};\n",
11605             format("struct foo {\n"
11606                    "private:\n"
11607                    "\n\n\n"
11608                    "  void f() {}\n"
11609                    "\n"
11610                    "private:\n"
11611                    "\n\n\n"
11612                    "  int i;\n"
11613                    "\n"
11614                    "protected:\n"
11615                    "\n\n\n"
11616                    "  int j;\n"
11617                    "};\n",
11618                    Style));
11619 
11620   // Test with comments.
11621   Style = getLLVMStyle();
11622   verifyFormat("struct foo {\n"
11623                "private:\n"
11624                "  // comment\n"
11625                "  void f() {}\n"
11626                "\n"
11627                "private: /* comment */\n"
11628                "  int i;\n"
11629                "};\n",
11630                Style);
11631   verifyFormat("struct foo {\n"
11632                "private:\n"
11633                "  // comment\n"
11634                "  void f() {}\n"
11635                "\n"
11636                "private: /* comment */\n"
11637                "  int i;\n"
11638                "};\n",
11639                "struct foo {\n"
11640                "private:\n"
11641                "\n"
11642                "  // comment\n"
11643                "  void f() {}\n"
11644                "\n"
11645                "private: /* comment */\n"
11646                "\n"
11647                "  int i;\n"
11648                "};\n",
11649                Style);
11650 
11651   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11652   verifyFormat("struct foo {\n"
11653                "private:\n"
11654                "\n"
11655                "  // comment\n"
11656                "  void f() {}\n"
11657                "\n"
11658                "private: /* comment */\n"
11659                "\n"
11660                "  int i;\n"
11661                "};\n",
11662                "struct foo {\n"
11663                "private:\n"
11664                "  // comment\n"
11665                "  void f() {}\n"
11666                "\n"
11667                "private: /* comment */\n"
11668                "  int i;\n"
11669                "};\n",
11670                Style);
11671   verifyFormat("struct foo {\n"
11672                "private:\n"
11673                "\n"
11674                "  // comment\n"
11675                "  void f() {}\n"
11676                "\n"
11677                "private: /* comment */\n"
11678                "\n"
11679                "  int i;\n"
11680                "};\n",
11681                Style);
11682 
11683   // Test with preprocessor defines.
11684   Style = getLLVMStyle();
11685   verifyFormat("struct foo {\n"
11686                "private:\n"
11687                "#ifdef FOO\n"
11688                "#endif\n"
11689                "  void f() {}\n"
11690                "};\n",
11691                Style);
11692   verifyFormat("struct foo {\n"
11693                "private:\n"
11694                "#ifdef FOO\n"
11695                "#endif\n"
11696                "  void f() {}\n"
11697                "};\n",
11698                "struct foo {\n"
11699                "private:\n"
11700                "\n"
11701                "#ifdef FOO\n"
11702                "#endif\n"
11703                "  void f() {}\n"
11704                "};\n",
11705                Style);
11706 
11707   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11708   verifyFormat("struct foo {\n"
11709                "private:\n"
11710                "\n"
11711                "#ifdef FOO\n"
11712                "#endif\n"
11713                "  void f() {}\n"
11714                "};\n",
11715                "struct foo {\n"
11716                "private:\n"
11717                "#ifdef FOO\n"
11718                "#endif\n"
11719                "  void f() {}\n"
11720                "};\n",
11721                Style);
11722   verifyFormat("struct foo {\n"
11723                "private:\n"
11724                "\n"
11725                "#ifdef FOO\n"
11726                "#endif\n"
11727                "  void f() {}\n"
11728                "};\n",
11729                Style);
11730 }
11731 
11732 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11733   // Combined tests of EmptyLineAfterAccessModifier and
11734   // EmptyLineBeforeAccessModifier.
11735   FormatStyle Style = getLLVMStyle();
11736   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11737   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11738   verifyFormat("struct foo {\n"
11739                "private:\n"
11740                "\n"
11741                "protected:\n"
11742                "};\n",
11743                Style);
11744 
11745   Style.MaxEmptyLinesToKeep = 10u;
11746   // Both remove all new lines.
11747   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11748   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11749   verifyFormat("struct foo {\n"
11750                "private:\n"
11751                "protected:\n"
11752                "};\n",
11753                "struct foo {\n"
11754                "private:\n"
11755                "\n\n\n"
11756                "protected:\n"
11757                "};\n",
11758                Style);
11759 
11760   // Leave tests rely on the code layout, test::messUp can not be used.
11761   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11762   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11763   Style.MaxEmptyLinesToKeep = 10u;
11764   EXPECT_EQ("struct foo {\n"
11765             "private:\n"
11766             "\n\n\n"
11767             "protected:\n"
11768             "};\n",
11769             format("struct foo {\n"
11770                    "private:\n"
11771                    "\n\n\n"
11772                    "protected:\n"
11773                    "};\n",
11774                    Style));
11775   Style.MaxEmptyLinesToKeep = 3u;
11776   EXPECT_EQ("struct foo {\n"
11777             "private:\n"
11778             "\n\n\n"
11779             "protected:\n"
11780             "};\n",
11781             format("struct foo {\n"
11782                    "private:\n"
11783                    "\n\n\n"
11784                    "protected:\n"
11785                    "};\n",
11786                    Style));
11787   Style.MaxEmptyLinesToKeep = 1u;
11788   EXPECT_EQ("struct foo {\n"
11789             "private:\n"
11790             "\n\n\n"
11791             "protected:\n"
11792             "};\n",
11793             format("struct foo {\n"
11794                    "private:\n"
11795                    "\n\n\n"
11796                    "protected:\n"
11797                    "};\n",
11798                    Style)); // Based on new lines in original document and not
11799                             // on the setting.
11800 
11801   Style.MaxEmptyLinesToKeep = 10u;
11802   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11803   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11804   // Newlines are kept if they are greater than zero,
11805   // test::messUp removes all new lines which changes the logic
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));
11817 
11818   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11819   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11820   // test::messUp removes all new lines which changes the logic
11821   EXPECT_EQ("struct foo {\n"
11822             "private:\n"
11823             "\n\n\n"
11824             "protected:\n"
11825             "};\n",
11826             format("struct foo {\n"
11827                    "private:\n"
11828                    "\n\n\n"
11829                    "protected:\n"
11830                    "};\n",
11831                    Style));
11832 
11833   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11834   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11835   EXPECT_EQ("struct foo {\n"
11836             "private:\n"
11837             "\n\n\n"
11838             "protected:\n"
11839             "};\n",
11840             format("struct foo {\n"
11841                    "private:\n"
11842                    "\n\n\n"
11843                    "protected:\n"
11844                    "};\n",
11845                    Style)); // test::messUp removes all new lines which changes
11846                             // the logic.
11847 
11848   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11849   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11850   verifyFormat("struct foo {\n"
11851                "private:\n"
11852                "protected:\n"
11853                "};\n",
11854                "struct foo {\n"
11855                "private:\n"
11856                "\n\n\n"
11857                "protected:\n"
11858                "};\n",
11859                Style);
11860 
11861   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11862   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11863   EXPECT_EQ("struct foo {\n"
11864             "private:\n"
11865             "\n\n\n"
11866             "protected:\n"
11867             "};\n",
11868             format("struct foo {\n"
11869                    "private:\n"
11870                    "\n\n\n"
11871                    "protected:\n"
11872                    "};\n",
11873                    Style)); // test::messUp removes all new lines which changes
11874                             // the logic.
11875 
11876   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11877   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11878   verifyFormat("struct foo {\n"
11879                "private:\n"
11880                "protected:\n"
11881                "};\n",
11882                "struct foo {\n"
11883                "private:\n"
11884                "\n\n\n"
11885                "protected:\n"
11886                "};\n",
11887                Style);
11888 
11889   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11890   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11891   verifyFormat("struct foo {\n"
11892                "private:\n"
11893                "protected:\n"
11894                "};\n",
11895                "struct foo {\n"
11896                "private:\n"
11897                "\n\n\n"
11898                "protected:\n"
11899                "};\n",
11900                Style);
11901 
11902   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11903   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11904   verifyFormat("struct foo {\n"
11905                "private:\n"
11906                "protected:\n"
11907                "};\n",
11908                "struct foo {\n"
11909                "private:\n"
11910                "\n\n\n"
11911                "protected:\n"
11912                "};\n",
11913                Style);
11914 
11915   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11916   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11917   verifyFormat("struct foo {\n"
11918                "private:\n"
11919                "protected:\n"
11920                "};\n",
11921                "struct foo {\n"
11922                "private:\n"
11923                "\n\n\n"
11924                "protected:\n"
11925                "};\n",
11926                Style);
11927 }
11928 
11929 TEST_F(FormatTest, FormatsArrays) {
11930   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11931                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11932   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11933                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11934   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11935                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11936   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11937                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11938   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11939                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11940   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11941                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11942                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11943   verifyFormat(
11944       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11945       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11946       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11947   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11948                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11949 
11950   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11951                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11952   verifyFormat(
11953       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11954       "                                  .aaaaaaa[0]\n"
11955       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11956   verifyFormat("a[::b::c];");
11957 
11958   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11959 
11960   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11961   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11962 }
11963 
11964 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11965   verifyFormat("(a)->b();");
11966   verifyFormat("--a;");
11967 }
11968 
11969 TEST_F(FormatTest, HandlesIncludeDirectives) {
11970   verifyFormat("#include <string>\n"
11971                "#include <a/b/c.h>\n"
11972                "#include \"a/b/string\"\n"
11973                "#include \"string.h\"\n"
11974                "#include \"string.h\"\n"
11975                "#include <a-a>\n"
11976                "#include < path with space >\n"
11977                "#include_next <test.h>"
11978                "#include \"abc.h\" // this is included for ABC\n"
11979                "#include \"some long include\" // with a comment\n"
11980                "#include \"some very long include path\"\n"
11981                "#include <some/very/long/include/path>\n",
11982                getLLVMStyleWithColumns(35));
11983   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11984   EXPECT_EQ("#include <a>", format("#include<a>"));
11985 
11986   verifyFormat("#import <string>");
11987   verifyFormat("#import <a/b/c.h>");
11988   verifyFormat("#import \"a/b/string\"");
11989   verifyFormat("#import \"string.h\"");
11990   verifyFormat("#import \"string.h\"");
11991   verifyFormat("#if __has_include(<strstream>)\n"
11992                "#include <strstream>\n"
11993                "#endif");
11994 
11995   verifyFormat("#define MY_IMPORT <a/b>");
11996 
11997   verifyFormat("#if __has_include(<a/b>)");
11998   verifyFormat("#if __has_include_next(<a/b>)");
11999   verifyFormat("#define F __has_include(<a/b>)");
12000   verifyFormat("#define F __has_include_next(<a/b>)");
12001 
12002   // Protocol buffer definition or missing "#".
12003   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
12004                getLLVMStyleWithColumns(30));
12005 
12006   FormatStyle Style = getLLVMStyle();
12007   Style.AlwaysBreakBeforeMultilineStrings = true;
12008   Style.ColumnLimit = 0;
12009   verifyFormat("#import \"abc.h\"", Style);
12010 
12011   // But 'import' might also be a regular C++ namespace.
12012   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12013                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
12014 }
12015 
12016 //===----------------------------------------------------------------------===//
12017 // Error recovery tests.
12018 //===----------------------------------------------------------------------===//
12019 
12020 TEST_F(FormatTest, IncompleteParameterLists) {
12021   FormatStyle NoBinPacking = getLLVMStyle();
12022   NoBinPacking.BinPackParameters = false;
12023   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
12024                "                        double *min_x,\n"
12025                "                        double *max_x,\n"
12026                "                        double *min_y,\n"
12027                "                        double *max_y,\n"
12028                "                        double *min_z,\n"
12029                "                        double *max_z, ) {}",
12030                NoBinPacking);
12031 }
12032 
12033 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
12034   verifyFormat("void f() { return; }\n42");
12035   verifyFormat("void f() {\n"
12036                "  if (0)\n"
12037                "    return;\n"
12038                "}\n"
12039                "42");
12040   verifyFormat("void f() { return }\n42");
12041   verifyFormat("void f() {\n"
12042                "  if (0)\n"
12043                "    return\n"
12044                "}\n"
12045                "42");
12046 }
12047 
12048 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
12049   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
12050   EXPECT_EQ("void f() {\n"
12051             "  if (a)\n"
12052             "    return\n"
12053             "}",
12054             format("void  f  (  )  {  if  ( a )  return  }"));
12055   EXPECT_EQ("namespace N {\n"
12056             "void f()\n"
12057             "}",
12058             format("namespace  N  {  void f()  }"));
12059   EXPECT_EQ("namespace N {\n"
12060             "void f() {}\n"
12061             "void g()\n"
12062             "} // namespace N",
12063             format("namespace N  { void f( ) { } void g( ) }"));
12064 }
12065 
12066 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
12067   verifyFormat("int aaaaaaaa =\n"
12068                "    // Overlylongcomment\n"
12069                "    b;",
12070                getLLVMStyleWithColumns(20));
12071   verifyFormat("function(\n"
12072                "    ShortArgument,\n"
12073                "    LoooooooooooongArgument);\n",
12074                getLLVMStyleWithColumns(20));
12075 }
12076 
12077 TEST_F(FormatTest, IncorrectAccessSpecifier) {
12078   verifyFormat("public:");
12079   verifyFormat("class A {\n"
12080                "public\n"
12081                "  void f() {}\n"
12082                "};");
12083   verifyFormat("public\n"
12084                "int qwerty;");
12085   verifyFormat("public\n"
12086                "B {}");
12087   verifyFormat("public\n"
12088                "{}");
12089   verifyFormat("public\n"
12090                "B { int x; }");
12091 }
12092 
12093 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
12094   verifyFormat("{");
12095   verifyFormat("#})");
12096   verifyNoCrash("(/**/[:!] ?[).");
12097 }
12098 
12099 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
12100   // Found by oss-fuzz:
12101   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
12102   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
12103   Style.ColumnLimit = 60;
12104   verifyNoCrash(
12105       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
12106       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
12107       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
12108       Style);
12109 }
12110 
12111 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
12112   verifyFormat("do {\n}");
12113   verifyFormat("do {\n}\n"
12114                "f();");
12115   verifyFormat("do {\n}\n"
12116                "wheeee(fun);");
12117   verifyFormat("do {\n"
12118                "  f();\n"
12119                "}");
12120 }
12121 
12122 TEST_F(FormatTest, IncorrectCodeMissingParens) {
12123   verifyFormat("if {\n  foo;\n  foo();\n}");
12124   verifyFormat("switch {\n  foo;\n  foo();\n}");
12125   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
12126   verifyIncompleteFormat("ERROR: for target;");
12127   verifyFormat("while {\n  foo;\n  foo();\n}");
12128   verifyFormat("do {\n  foo;\n  foo();\n} while;");
12129 }
12130 
12131 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
12132   verifyIncompleteFormat("namespace {\n"
12133                          "class Foo { Foo (\n"
12134                          "};\n"
12135                          "} // namespace");
12136 }
12137 
12138 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
12139   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
12140   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
12141   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
12142   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
12143 
12144   EXPECT_EQ("{\n"
12145             "  {\n"
12146             "    breakme(\n"
12147             "        qwe);\n"
12148             "  }\n",
12149             format("{\n"
12150                    "    {\n"
12151                    " breakme(qwe);\n"
12152                    "}\n",
12153                    getLLVMStyleWithColumns(10)));
12154 }
12155 
12156 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
12157   verifyFormat("int x = {\n"
12158                "    avariable,\n"
12159                "    b(alongervariable)};",
12160                getLLVMStyleWithColumns(25));
12161 }
12162 
12163 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
12164   verifyFormat("return (a)(b){1, 2, 3};");
12165 }
12166 
12167 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
12168   verifyFormat("vector<int> x{1, 2, 3, 4};");
12169   verifyFormat("vector<int> x{\n"
12170                "    1,\n"
12171                "    2,\n"
12172                "    3,\n"
12173                "    4,\n"
12174                "};");
12175   verifyFormat("vector<T> x{{}, {}, {}, {}};");
12176   verifyFormat("f({1, 2});");
12177   verifyFormat("auto v = Foo{-1};");
12178   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
12179   verifyFormat("Class::Class : member{1, 2, 3} {}");
12180   verifyFormat("new vector<int>{1, 2, 3};");
12181   verifyFormat("new int[3]{1, 2, 3};");
12182   verifyFormat("new int{1};");
12183   verifyFormat("return {arg1, arg2};");
12184   verifyFormat("return {arg1, SomeType{parameter}};");
12185   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
12186   verifyFormat("new T{arg1, arg2};");
12187   verifyFormat("f(MyMap[{composite, key}]);");
12188   verifyFormat("class Class {\n"
12189                "  T member = {arg1, arg2};\n"
12190                "};");
12191   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
12192   verifyFormat("const struct A a = {.a = 1, .b = 2};");
12193   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
12194   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
12195   verifyFormat("int a = std::is_integral<int>{} + 0;");
12196 
12197   verifyFormat("int foo(int i) { return fo1{}(i); }");
12198   verifyFormat("int foo(int i) { return fo1{}(i); }");
12199   verifyFormat("auto i = decltype(x){};");
12200   verifyFormat("auto i = typeof(x){};");
12201   verifyFormat("auto i = _Atomic(x){};");
12202   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
12203   verifyFormat("Node n{1, Node{1000}, //\n"
12204                "       2};");
12205   verifyFormat("Aaaa aaaaaaa{\n"
12206                "    {\n"
12207                "        aaaa,\n"
12208                "    },\n"
12209                "};");
12210   verifyFormat("class C : public D {\n"
12211                "  SomeClass SC{2};\n"
12212                "};");
12213   verifyFormat("class C : public A {\n"
12214                "  class D : public B {\n"
12215                "    void f() { int i{2}; }\n"
12216                "  };\n"
12217                "};");
12218   verifyFormat("#define A {a, a},");
12219   // Don't confuse braced list initializers with compound statements.
12220   verifyFormat(
12221       "class A {\n"
12222       "  A() : a{} {}\n"
12223       "  A(int b) : b(b) {}\n"
12224       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12225       "  int a, b;\n"
12226       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12227       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12228       "{}\n"
12229       "};");
12230 
12231   // Avoid breaking between equal sign and opening brace
12232   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12233   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12234   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12235                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12236                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12237                "     {\"ccccccccccccccccccccc\", 2}};",
12238                AvoidBreakingFirstArgument);
12239 
12240   // Binpacking only if there is no trailing comma
12241   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12242                "                      cccccccccc, dddddddddd};",
12243                getLLVMStyleWithColumns(50));
12244   verifyFormat("const Aaaaaa aaaaa = {\n"
12245                "    aaaaaaaaaaa,\n"
12246                "    bbbbbbbbbbb,\n"
12247                "    ccccccccccc,\n"
12248                "    ddddddddddd,\n"
12249                "};",
12250                getLLVMStyleWithColumns(50));
12251 
12252   // Cases where distinguising braced lists and blocks is hard.
12253   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12254   verifyFormat("void f() {\n"
12255                "  return; // comment\n"
12256                "}\n"
12257                "SomeType t;");
12258   verifyFormat("void f() {\n"
12259                "  if (a) {\n"
12260                "    f();\n"
12261                "  }\n"
12262                "}\n"
12263                "SomeType t;");
12264 
12265   // In combination with BinPackArguments = false.
12266   FormatStyle NoBinPacking = getLLVMStyle();
12267   NoBinPacking.BinPackArguments = false;
12268   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12269                "                      bbbbb,\n"
12270                "                      ccccc,\n"
12271                "                      ddddd,\n"
12272                "                      eeeee,\n"
12273                "                      ffffff,\n"
12274                "                      ggggg,\n"
12275                "                      hhhhhh,\n"
12276                "                      iiiiii,\n"
12277                "                      jjjjjj,\n"
12278                "                      kkkkkk};",
12279                NoBinPacking);
12280   verifyFormat("const Aaaaaa aaaaa = {\n"
12281                "    aaaaa,\n"
12282                "    bbbbb,\n"
12283                "    ccccc,\n"
12284                "    ddddd,\n"
12285                "    eeeee,\n"
12286                "    ffffff,\n"
12287                "    ggggg,\n"
12288                "    hhhhhh,\n"
12289                "    iiiiii,\n"
12290                "    jjjjjj,\n"
12291                "    kkkkkk,\n"
12292                "};",
12293                NoBinPacking);
12294   verifyFormat(
12295       "const Aaaaaa aaaaa = {\n"
12296       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12297       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12298       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12299       "};",
12300       NoBinPacking);
12301 
12302   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12303   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12304             "    CDDDP83848_BMCR_REGISTER,\n"
12305             "    CDDDP83848_BMSR_REGISTER,\n"
12306             "    CDDDP83848_RBR_REGISTER};",
12307             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12308                    "                                CDDDP83848_BMSR_REGISTER,\n"
12309                    "                                CDDDP83848_RBR_REGISTER};",
12310                    NoBinPacking));
12311 
12312   // FIXME: The alignment of these trailing comments might be bad. Then again,
12313   // this might be utterly useless in real code.
12314   verifyFormat("Constructor::Constructor()\n"
12315                "    : some_value{         //\n"
12316                "                 aaaaaaa, //\n"
12317                "                 bbbbbbb} {}");
12318 
12319   // In braced lists, the first comment is always assumed to belong to the
12320   // first element. Thus, it can be moved to the next or previous line as
12321   // appropriate.
12322   EXPECT_EQ("function({// First element:\n"
12323             "          1,\n"
12324             "          // Second element:\n"
12325             "          2});",
12326             format("function({\n"
12327                    "    // First element:\n"
12328                    "    1,\n"
12329                    "    // Second element:\n"
12330                    "    2});"));
12331   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12332             "    // First element:\n"
12333             "    1,\n"
12334             "    // Second element:\n"
12335             "    2};",
12336             format("std::vector<int> MyNumbers{// First element:\n"
12337                    "                           1,\n"
12338                    "                           // Second element:\n"
12339                    "                           2};",
12340                    getLLVMStyleWithColumns(30)));
12341   // A trailing comma should still lead to an enforced line break and no
12342   // binpacking.
12343   EXPECT_EQ("vector<int> SomeVector = {\n"
12344             "    // aaa\n"
12345             "    1,\n"
12346             "    2,\n"
12347             "};",
12348             format("vector<int> SomeVector = { // aaa\n"
12349                    "    1, 2, };"));
12350 
12351   // C++11 brace initializer list l-braces should not be treated any differently
12352   // when breaking before lambda bodies is enabled
12353   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12354   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12355   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12356   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12357   verifyFormat(
12358       "std::runtime_error{\n"
12359       "    \"Long string which will force a break onto the next line...\"};",
12360       BreakBeforeLambdaBody);
12361 
12362   FormatStyle ExtraSpaces = getLLVMStyle();
12363   ExtraSpaces.Cpp11BracedListStyle = false;
12364   ExtraSpaces.ColumnLimit = 75;
12365   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12366   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12367   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12368   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12369   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12370   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12371   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12372   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12373   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12374   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12375   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12376   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12377   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12378   verifyFormat("class Class {\n"
12379                "  T member = { arg1, arg2 };\n"
12380                "};",
12381                ExtraSpaces);
12382   verifyFormat(
12383       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12384       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12385       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12386       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12387       ExtraSpaces);
12388   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12389   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12390                ExtraSpaces);
12391   verifyFormat(
12392       "someFunction(OtherParam,\n"
12393       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12394       "                         param1, param2,\n"
12395       "                         // comment 2\n"
12396       "                         param3, param4 });",
12397       ExtraSpaces);
12398   verifyFormat(
12399       "std::this_thread::sleep_for(\n"
12400       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12401       ExtraSpaces);
12402   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12403                "    aaaaaaa,\n"
12404                "    aaaaaaaaaa,\n"
12405                "    aaaaa,\n"
12406                "    aaaaaaaaaaaaaaa,\n"
12407                "    aaa,\n"
12408                "    aaaaaaaaaa,\n"
12409                "    a,\n"
12410                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12411                "    aaaaaaaaaaaa,\n"
12412                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12413                "    aaaaaaa,\n"
12414                "    a};");
12415   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12416   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12417   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12418 
12419   // Avoid breaking between initializer/equal sign and opening brace
12420   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12421   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12422                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12423                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12424                "  { \"ccccccccccccccccccccc\", 2 }\n"
12425                "};",
12426                ExtraSpaces);
12427   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12428                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12429                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12430                "  { \"ccccccccccccccccccccc\", 2 }\n"
12431                "};",
12432                ExtraSpaces);
12433 
12434   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12435   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12436   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12437   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12438 
12439   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12440   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12441   SpaceBetweenBraces.SpacesInParentheses = true;
12442   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12443   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12444   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12445   verifyFormat("vector< int > x{ // comment 1\n"
12446                "                 1, 2, 3, 4 };",
12447                SpaceBetweenBraces);
12448   SpaceBetweenBraces.ColumnLimit = 20;
12449   EXPECT_EQ("vector< int > x{\n"
12450             "    1, 2, 3, 4 };",
12451             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12452   SpaceBetweenBraces.ColumnLimit = 24;
12453   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12454             "                 3, 4 };",
12455             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12456   EXPECT_EQ("vector< int > x{\n"
12457             "    1,\n"
12458             "    2,\n"
12459             "    3,\n"
12460             "    4,\n"
12461             "};",
12462             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12463   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12464   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12465   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12466 }
12467 
12468 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12469   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12470                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12471                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12472                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12473                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12474                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12475   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12476                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12477                "                 1, 22, 333, 4444, 55555, //\n"
12478                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12479                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12480   verifyFormat(
12481       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12482       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12483       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12484       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12485       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12486       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12487       "                 7777777};");
12488   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12489                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12490                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12491   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12492                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12493                "    // Separating comment.\n"
12494                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12495   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12496                "    // Leading comment\n"
12497                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12498                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12499   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12500                "                 1, 1, 1, 1};",
12501                getLLVMStyleWithColumns(39));
12502   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12503                "                 1, 1, 1, 1};",
12504                getLLVMStyleWithColumns(38));
12505   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12506                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12507                getLLVMStyleWithColumns(43));
12508   verifyFormat(
12509       "static unsigned SomeValues[10][3] = {\n"
12510       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12511       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12512   verifyFormat("static auto fields = new vector<string>{\n"
12513                "    \"aaaaaaaaaaaaa\",\n"
12514                "    \"aaaaaaaaaaaaa\",\n"
12515                "    \"aaaaaaaaaaaa\",\n"
12516                "    \"aaaaaaaaaaaaaa\",\n"
12517                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12518                "    \"aaaaaaaaaaaa\",\n"
12519                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12520                "};");
12521   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12522   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12523                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12524                "                 3, cccccccccccccccccccccc};",
12525                getLLVMStyleWithColumns(60));
12526 
12527   // Trailing commas.
12528   verifyFormat("vector<int> x = {\n"
12529                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12530                "};",
12531                getLLVMStyleWithColumns(39));
12532   verifyFormat("vector<int> x = {\n"
12533                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12534                "};",
12535                getLLVMStyleWithColumns(39));
12536   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12537                "                 1, 1, 1, 1,\n"
12538                "                 /**/ /**/};",
12539                getLLVMStyleWithColumns(39));
12540 
12541   // Trailing comment in the first line.
12542   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12543                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12544                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12545                "    11111111,   22222222,   333333333,   44444444};");
12546   // Trailing comment in the last line.
12547   verifyFormat("int aaaaa[] = {\n"
12548                "    1, 2, 3, // comment\n"
12549                "    4, 5, 6  // comment\n"
12550                "};");
12551 
12552   // With nested lists, we should either format one item per line or all nested
12553   // lists one on line.
12554   // FIXME: For some nested lists, we can do better.
12555   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12556                "        {aaaaaaaaaaaaaaaaaaa},\n"
12557                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12558                "        {aaaaaaaaaaaaaaaaa}};",
12559                getLLVMStyleWithColumns(60));
12560   verifyFormat(
12561       "SomeStruct my_struct_array = {\n"
12562       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12563       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12564       "    {aaa, aaa},\n"
12565       "    {aaa, aaa},\n"
12566       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12567       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12568       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12569 
12570   // No column layout should be used here.
12571   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12572                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12573 
12574   verifyNoCrash("a<,");
12575 
12576   // No braced initializer here.
12577   verifyFormat("void f() {\n"
12578                "  struct Dummy {};\n"
12579                "  f(v);\n"
12580                "}");
12581 
12582   // Long lists should be formatted in columns even if they are nested.
12583   verifyFormat(
12584       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12585       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12586       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12587       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12588       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12589       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12590 
12591   // Allow "single-column" layout even if that violates the column limit. There
12592   // isn't going to be a better way.
12593   verifyFormat("std::vector<int> a = {\n"
12594                "    aaaaaaaa,\n"
12595                "    aaaaaaaa,\n"
12596                "    aaaaaaaa,\n"
12597                "    aaaaaaaa,\n"
12598                "    aaaaaaaaaa,\n"
12599                "    aaaaaaaa,\n"
12600                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12601                getLLVMStyleWithColumns(30));
12602   verifyFormat("vector<int> aaaa = {\n"
12603                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12604                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12605                "    aaaaaa.aaaaaaa,\n"
12606                "    aaaaaa.aaaaaaa,\n"
12607                "    aaaaaa.aaaaaaa,\n"
12608                "    aaaaaa.aaaaaaa,\n"
12609                "};");
12610 
12611   // Don't create hanging lists.
12612   verifyFormat("someFunction(Param, {List1, List2,\n"
12613                "                     List3});",
12614                getLLVMStyleWithColumns(35));
12615   verifyFormat("someFunction(Param, Param,\n"
12616                "             {List1, List2,\n"
12617                "              List3});",
12618                getLLVMStyleWithColumns(35));
12619   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12620                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12621 }
12622 
12623 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12624   FormatStyle DoNotMerge = getLLVMStyle();
12625   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12626 
12627   verifyFormat("void f() { return 42; }");
12628   verifyFormat("void f() {\n"
12629                "  return 42;\n"
12630                "}",
12631                DoNotMerge);
12632   verifyFormat("void f() {\n"
12633                "  // Comment\n"
12634                "}");
12635   verifyFormat("{\n"
12636                "#error {\n"
12637                "  int a;\n"
12638                "}");
12639   verifyFormat("{\n"
12640                "  int a;\n"
12641                "#error {\n"
12642                "}");
12643   verifyFormat("void f() {} // comment");
12644   verifyFormat("void f() { int a; } // comment");
12645   verifyFormat("void f() {\n"
12646                "} // comment",
12647                DoNotMerge);
12648   verifyFormat("void f() {\n"
12649                "  int a;\n"
12650                "} // comment",
12651                DoNotMerge);
12652   verifyFormat("void f() {\n"
12653                "} // comment",
12654                getLLVMStyleWithColumns(15));
12655 
12656   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12657   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12658 
12659   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12660   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12661   verifyFormat("class C {\n"
12662                "  C()\n"
12663                "      : iiiiiiii(nullptr),\n"
12664                "        kkkkkkk(nullptr),\n"
12665                "        mmmmmmm(nullptr),\n"
12666                "        nnnnnnn(nullptr) {}\n"
12667                "};",
12668                getGoogleStyle());
12669 
12670   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12671   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12672   EXPECT_EQ("class C {\n"
12673             "  A() : b(0) {}\n"
12674             "};",
12675             format("class C{A():b(0){}};", NoColumnLimit));
12676   EXPECT_EQ("A()\n"
12677             "    : b(0) {\n"
12678             "}",
12679             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12680 
12681   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12682   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12683       FormatStyle::SFS_None;
12684   EXPECT_EQ("A()\n"
12685             "    : b(0) {\n"
12686             "}",
12687             format("A():b(0){}", DoNotMergeNoColumnLimit));
12688   EXPECT_EQ("A()\n"
12689             "    : b(0) {\n"
12690             "}",
12691             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12692 
12693   verifyFormat("#define A          \\\n"
12694                "  void f() {       \\\n"
12695                "    int i;         \\\n"
12696                "  }",
12697                getLLVMStyleWithColumns(20));
12698   verifyFormat("#define A           \\\n"
12699                "  void f() { int i; }",
12700                getLLVMStyleWithColumns(21));
12701   verifyFormat("#define A            \\\n"
12702                "  void f() {         \\\n"
12703                "    int i;           \\\n"
12704                "  }                  \\\n"
12705                "  int j;",
12706                getLLVMStyleWithColumns(22));
12707   verifyFormat("#define A             \\\n"
12708                "  void f() { int i; } \\\n"
12709                "  int j;",
12710                getLLVMStyleWithColumns(23));
12711 }
12712 
12713 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12714   FormatStyle MergeEmptyOnly = getLLVMStyle();
12715   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12716   verifyFormat("class C {\n"
12717                "  int f() {}\n"
12718                "};",
12719                MergeEmptyOnly);
12720   verifyFormat("class C {\n"
12721                "  int f() {\n"
12722                "    return 42;\n"
12723                "  }\n"
12724                "};",
12725                MergeEmptyOnly);
12726   verifyFormat("int f() {}", MergeEmptyOnly);
12727   verifyFormat("int f() {\n"
12728                "  return 42;\n"
12729                "}",
12730                MergeEmptyOnly);
12731 
12732   // Also verify behavior when BraceWrapping.AfterFunction = true
12733   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12734   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12735   verifyFormat("int f() {}", MergeEmptyOnly);
12736   verifyFormat("class C {\n"
12737                "  int f() {}\n"
12738                "};",
12739                MergeEmptyOnly);
12740 }
12741 
12742 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12743   FormatStyle MergeInlineOnly = getLLVMStyle();
12744   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12745   verifyFormat("class C {\n"
12746                "  int f() { return 42; }\n"
12747                "};",
12748                MergeInlineOnly);
12749   verifyFormat("int f() {\n"
12750                "  return 42;\n"
12751                "}",
12752                MergeInlineOnly);
12753 
12754   // SFS_Inline implies SFS_Empty
12755   verifyFormat("class C {\n"
12756                "  int f() {}\n"
12757                "};",
12758                MergeInlineOnly);
12759   verifyFormat("int f() {}", MergeInlineOnly);
12760   // https://llvm.org/PR54147
12761   verifyFormat("auto lambda = []() {\n"
12762                "  // comment\n"
12763                "  f();\n"
12764                "  g();\n"
12765                "};",
12766                MergeInlineOnly);
12767 
12768   // Also verify behavior when BraceWrapping.AfterFunction = true
12769   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12770   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12771   verifyFormat("class C {\n"
12772                "  int f() { return 42; }\n"
12773                "};",
12774                MergeInlineOnly);
12775   verifyFormat("int f()\n"
12776                "{\n"
12777                "  return 42;\n"
12778                "}",
12779                MergeInlineOnly);
12780 
12781   // SFS_Inline implies SFS_Empty
12782   verifyFormat("int f() {}", MergeInlineOnly);
12783   verifyFormat("class C {\n"
12784                "  int f() {}\n"
12785                "};",
12786                MergeInlineOnly);
12787 
12788   MergeInlineOnly.BraceWrapping.AfterClass = true;
12789   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12790   verifyFormat("class C\n"
12791                "{\n"
12792                "  int f() { return 42; }\n"
12793                "};",
12794                MergeInlineOnly);
12795   verifyFormat("struct C\n"
12796                "{\n"
12797                "  int f() { return 42; }\n"
12798                "};",
12799                MergeInlineOnly);
12800   verifyFormat("int f()\n"
12801                "{\n"
12802                "  return 42;\n"
12803                "}",
12804                MergeInlineOnly);
12805   verifyFormat("int f() {}", MergeInlineOnly);
12806   verifyFormat("class C\n"
12807                "{\n"
12808                "  int f() { return 42; }\n"
12809                "};",
12810                MergeInlineOnly);
12811   verifyFormat("struct C\n"
12812                "{\n"
12813                "  int f() { return 42; }\n"
12814                "};",
12815                MergeInlineOnly);
12816   verifyFormat("struct C\n"
12817                "// comment\n"
12818                "/* comment */\n"
12819                "// comment\n"
12820                "{\n"
12821                "  int f() { return 42; }\n"
12822                "};",
12823                MergeInlineOnly);
12824   verifyFormat("/* comment */ struct C\n"
12825                "{\n"
12826                "  int f() { return 42; }\n"
12827                "};",
12828                MergeInlineOnly);
12829 }
12830 
12831 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12832   FormatStyle MergeInlineOnly = getLLVMStyle();
12833   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12834       FormatStyle::SFS_InlineOnly;
12835   verifyFormat("class C {\n"
12836                "  int f() { return 42; }\n"
12837                "};",
12838                MergeInlineOnly);
12839   verifyFormat("int f() {\n"
12840                "  return 42;\n"
12841                "}",
12842                MergeInlineOnly);
12843 
12844   // SFS_InlineOnly does not imply SFS_Empty
12845   verifyFormat("class C {\n"
12846                "  int f() {}\n"
12847                "};",
12848                MergeInlineOnly);
12849   verifyFormat("int f() {\n"
12850                "}",
12851                MergeInlineOnly);
12852 
12853   // Also verify behavior when BraceWrapping.AfterFunction = true
12854   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12855   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12856   verifyFormat("class C {\n"
12857                "  int f() { return 42; }\n"
12858                "};",
12859                MergeInlineOnly);
12860   verifyFormat("int f()\n"
12861                "{\n"
12862                "  return 42;\n"
12863                "}",
12864                MergeInlineOnly);
12865 
12866   // SFS_InlineOnly does not imply SFS_Empty
12867   verifyFormat("int f()\n"
12868                "{\n"
12869                "}",
12870                MergeInlineOnly);
12871   verifyFormat("class C {\n"
12872                "  int f() {}\n"
12873                "};",
12874                MergeInlineOnly);
12875 }
12876 
12877 TEST_F(FormatTest, SplitEmptyFunction) {
12878   FormatStyle Style = getLLVMStyleWithColumns(40);
12879   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12880   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12881   Style.BraceWrapping.AfterFunction = true;
12882   Style.BraceWrapping.SplitEmptyFunction = false;
12883 
12884   verifyFormat("int f()\n"
12885                "{}",
12886                Style);
12887   verifyFormat("int f()\n"
12888                "{\n"
12889                "  return 42;\n"
12890                "}",
12891                Style);
12892   verifyFormat("int f()\n"
12893                "{\n"
12894                "  // some comment\n"
12895                "}",
12896                Style);
12897 
12898   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12899   verifyFormat("int f() {}", Style);
12900   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12901                "{}",
12902                Style);
12903   verifyFormat("int f()\n"
12904                "{\n"
12905                "  return 0;\n"
12906                "}",
12907                Style);
12908 
12909   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12910   verifyFormat("class Foo {\n"
12911                "  int f() {}\n"
12912                "};\n",
12913                Style);
12914   verifyFormat("class Foo {\n"
12915                "  int f() { return 0; }\n"
12916                "};\n",
12917                Style);
12918   verifyFormat("class Foo {\n"
12919                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12920                "  {}\n"
12921                "};\n",
12922                Style);
12923   verifyFormat("class Foo {\n"
12924                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12925                "  {\n"
12926                "    return 0;\n"
12927                "  }\n"
12928                "};\n",
12929                Style);
12930 
12931   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12932   verifyFormat("int f() {}", Style);
12933   verifyFormat("int f() { return 0; }", Style);
12934   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12935                "{}",
12936                Style);
12937   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12938                "{\n"
12939                "  return 0;\n"
12940                "}",
12941                Style);
12942 }
12943 
12944 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12945   FormatStyle Style = getLLVMStyleWithColumns(40);
12946   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12947   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12948   Style.BraceWrapping.AfterFunction = true;
12949   Style.BraceWrapping.SplitEmptyFunction = true;
12950   Style.BraceWrapping.SplitEmptyRecord = false;
12951 
12952   verifyFormat("class C {};", Style);
12953   verifyFormat("struct C {};", Style);
12954   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12955                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12956                "{\n"
12957                "}",
12958                Style);
12959   verifyFormat("class C {\n"
12960                "  C()\n"
12961                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12962                "        bbbbbbbbbbbbbbbbbbb()\n"
12963                "  {\n"
12964                "  }\n"
12965                "  void\n"
12966                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12967                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12968                "  {\n"
12969                "  }\n"
12970                "};",
12971                Style);
12972 }
12973 
12974 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12975   FormatStyle Style = getLLVMStyle();
12976   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12977   verifyFormat("#ifdef A\n"
12978                "int f() {}\n"
12979                "#else\n"
12980                "int g() {}\n"
12981                "#endif",
12982                Style);
12983 }
12984 
12985 TEST_F(FormatTest, SplitEmptyClass) {
12986   FormatStyle Style = getLLVMStyle();
12987   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12988   Style.BraceWrapping.AfterClass = true;
12989   Style.BraceWrapping.SplitEmptyRecord = false;
12990 
12991   verifyFormat("class Foo\n"
12992                "{};",
12993                Style);
12994   verifyFormat("/* something */ class Foo\n"
12995                "{};",
12996                Style);
12997   verifyFormat("template <typename X> class Foo\n"
12998                "{};",
12999                Style);
13000   verifyFormat("class Foo\n"
13001                "{\n"
13002                "  Foo();\n"
13003                "};",
13004                Style);
13005   verifyFormat("typedef class Foo\n"
13006                "{\n"
13007                "} Foo_t;",
13008                Style);
13009 
13010   Style.BraceWrapping.SplitEmptyRecord = true;
13011   Style.BraceWrapping.AfterStruct = true;
13012   verifyFormat("class rep\n"
13013                "{\n"
13014                "};",
13015                Style);
13016   verifyFormat("struct rep\n"
13017                "{\n"
13018                "};",
13019                Style);
13020   verifyFormat("template <typename T> class rep\n"
13021                "{\n"
13022                "};",
13023                Style);
13024   verifyFormat("template <typename T> struct rep\n"
13025                "{\n"
13026                "};",
13027                Style);
13028   verifyFormat("class rep\n"
13029                "{\n"
13030                "  int x;\n"
13031                "};",
13032                Style);
13033   verifyFormat("struct rep\n"
13034                "{\n"
13035                "  int x;\n"
13036                "};",
13037                Style);
13038   verifyFormat("template <typename T> class rep\n"
13039                "{\n"
13040                "  int x;\n"
13041                "};",
13042                Style);
13043   verifyFormat("template <typename T> struct rep\n"
13044                "{\n"
13045                "  int x;\n"
13046                "};",
13047                Style);
13048   verifyFormat("template <typename T> class rep // Foo\n"
13049                "{\n"
13050                "  int x;\n"
13051                "};",
13052                Style);
13053   verifyFormat("template <typename T> struct rep // Bar\n"
13054                "{\n"
13055                "  int x;\n"
13056                "};",
13057                Style);
13058 
13059   verifyFormat("template <typename T> class rep<T>\n"
13060                "{\n"
13061                "  int x;\n"
13062                "};",
13063                Style);
13064 
13065   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13066                "{\n"
13067                "  int x;\n"
13068                "};",
13069                Style);
13070   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13071                "{\n"
13072                "};",
13073                Style);
13074 
13075   verifyFormat("#include \"stdint.h\"\n"
13076                "namespace rep {}",
13077                Style);
13078   verifyFormat("#include <stdint.h>\n"
13079                "namespace rep {}",
13080                Style);
13081   verifyFormat("#include <stdint.h>\n"
13082                "namespace rep {}",
13083                "#include <stdint.h>\n"
13084                "namespace rep {\n"
13085                "\n"
13086                "\n"
13087                "}",
13088                Style);
13089 }
13090 
13091 TEST_F(FormatTest, SplitEmptyStruct) {
13092   FormatStyle Style = getLLVMStyle();
13093   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13094   Style.BraceWrapping.AfterStruct = true;
13095   Style.BraceWrapping.SplitEmptyRecord = false;
13096 
13097   verifyFormat("struct Foo\n"
13098                "{};",
13099                Style);
13100   verifyFormat("/* something */ struct Foo\n"
13101                "{};",
13102                Style);
13103   verifyFormat("template <typename X> struct Foo\n"
13104                "{};",
13105                Style);
13106   verifyFormat("struct Foo\n"
13107                "{\n"
13108                "  Foo();\n"
13109                "};",
13110                Style);
13111   verifyFormat("typedef struct Foo\n"
13112                "{\n"
13113                "} Foo_t;",
13114                Style);
13115   // typedef struct Bar {} Bar_t;
13116 }
13117 
13118 TEST_F(FormatTest, SplitEmptyUnion) {
13119   FormatStyle Style = getLLVMStyle();
13120   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13121   Style.BraceWrapping.AfterUnion = true;
13122   Style.BraceWrapping.SplitEmptyRecord = false;
13123 
13124   verifyFormat("union Foo\n"
13125                "{};",
13126                Style);
13127   verifyFormat("/* something */ union Foo\n"
13128                "{};",
13129                Style);
13130   verifyFormat("union Foo\n"
13131                "{\n"
13132                "  A,\n"
13133                "};",
13134                Style);
13135   verifyFormat("typedef union Foo\n"
13136                "{\n"
13137                "} Foo_t;",
13138                Style);
13139 }
13140 
13141 TEST_F(FormatTest, SplitEmptyNamespace) {
13142   FormatStyle Style = getLLVMStyle();
13143   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13144   Style.BraceWrapping.AfterNamespace = true;
13145   Style.BraceWrapping.SplitEmptyNamespace = false;
13146 
13147   verifyFormat("namespace Foo\n"
13148                "{};",
13149                Style);
13150   verifyFormat("/* something */ namespace Foo\n"
13151                "{};",
13152                Style);
13153   verifyFormat("inline namespace Foo\n"
13154                "{};",
13155                Style);
13156   verifyFormat("/* something */ inline namespace Foo\n"
13157                "{};",
13158                Style);
13159   verifyFormat("export namespace Foo\n"
13160                "{};",
13161                Style);
13162   verifyFormat("namespace Foo\n"
13163                "{\n"
13164                "void Bar();\n"
13165                "};",
13166                Style);
13167 }
13168 
13169 TEST_F(FormatTest, NeverMergeShortRecords) {
13170   FormatStyle Style = getLLVMStyle();
13171 
13172   verifyFormat("class Foo {\n"
13173                "  Foo();\n"
13174                "};",
13175                Style);
13176   verifyFormat("typedef class Foo {\n"
13177                "  Foo();\n"
13178                "} Foo_t;",
13179                Style);
13180   verifyFormat("struct Foo {\n"
13181                "  Foo();\n"
13182                "};",
13183                Style);
13184   verifyFormat("typedef struct Foo {\n"
13185                "  Foo();\n"
13186                "} Foo_t;",
13187                Style);
13188   verifyFormat("union Foo {\n"
13189                "  A,\n"
13190                "};",
13191                Style);
13192   verifyFormat("typedef union Foo {\n"
13193                "  A,\n"
13194                "} Foo_t;",
13195                Style);
13196   verifyFormat("namespace Foo {\n"
13197                "void Bar();\n"
13198                "};",
13199                Style);
13200 
13201   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13202   Style.BraceWrapping.AfterClass = true;
13203   Style.BraceWrapping.AfterStruct = true;
13204   Style.BraceWrapping.AfterUnion = true;
13205   Style.BraceWrapping.AfterNamespace = true;
13206   verifyFormat("class Foo\n"
13207                "{\n"
13208                "  Foo();\n"
13209                "};",
13210                Style);
13211   verifyFormat("typedef class Foo\n"
13212                "{\n"
13213                "  Foo();\n"
13214                "} Foo_t;",
13215                Style);
13216   verifyFormat("struct Foo\n"
13217                "{\n"
13218                "  Foo();\n"
13219                "};",
13220                Style);
13221   verifyFormat("typedef struct Foo\n"
13222                "{\n"
13223                "  Foo();\n"
13224                "} Foo_t;",
13225                Style);
13226   verifyFormat("union Foo\n"
13227                "{\n"
13228                "  A,\n"
13229                "};",
13230                Style);
13231   verifyFormat("typedef union Foo\n"
13232                "{\n"
13233                "  A,\n"
13234                "} Foo_t;",
13235                Style);
13236   verifyFormat("namespace Foo\n"
13237                "{\n"
13238                "void Bar();\n"
13239                "};",
13240                Style);
13241 }
13242 
13243 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13244   // Elaborate type variable declarations.
13245   verifyFormat("struct foo a = {bar};\nint n;");
13246   verifyFormat("class foo a = {bar};\nint n;");
13247   verifyFormat("union foo a = {bar};\nint n;");
13248 
13249   // Elaborate types inside function definitions.
13250   verifyFormat("struct foo f() {}\nint n;");
13251   verifyFormat("class foo f() {}\nint n;");
13252   verifyFormat("union foo f() {}\nint n;");
13253 
13254   // Templates.
13255   verifyFormat("template <class X> void f() {}\nint n;");
13256   verifyFormat("template <struct X> void f() {}\nint n;");
13257   verifyFormat("template <union X> void f() {}\nint n;");
13258 
13259   // Actual definitions...
13260   verifyFormat("struct {\n} n;");
13261   verifyFormat(
13262       "template <template <class T, class Y>, class Z> class X {\n} n;");
13263   verifyFormat("union Z {\n  int n;\n} x;");
13264   verifyFormat("class MACRO Z {\n} n;");
13265   verifyFormat("class MACRO(X) Z {\n} n;");
13266   verifyFormat("class __attribute__(X) Z {\n} n;");
13267   verifyFormat("class __declspec(X) Z {\n} n;");
13268   verifyFormat("class A##B##C {\n} n;");
13269   verifyFormat("class alignas(16) Z {\n} n;");
13270   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13271   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13272 
13273   // Redefinition from nested context:
13274   verifyFormat("class A::B::C {\n} n;");
13275 
13276   // Template definitions.
13277   verifyFormat(
13278       "template <typename F>\n"
13279       "Matcher(const Matcher<F> &Other,\n"
13280       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13281       "                             !is_same<F, T>::value>::type * = 0)\n"
13282       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13283 
13284   // FIXME: This is still incorrectly handled at the formatter side.
13285   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13286   verifyFormat("int i = SomeFunction(a<b, a> b);");
13287 
13288   // FIXME:
13289   // This now gets parsed incorrectly as class definition.
13290   // verifyFormat("class A<int> f() {\n}\nint n;");
13291 
13292   // Elaborate types where incorrectly parsing the structural element would
13293   // break the indent.
13294   verifyFormat("if (true)\n"
13295                "  class X x;\n"
13296                "else\n"
13297                "  f();\n");
13298 
13299   // This is simply incomplete. Formatting is not important, but must not crash.
13300   verifyFormat("class A:");
13301 }
13302 
13303 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13304   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13305             format("#error Leave     all         white!!!!! space* alone!\n"));
13306   EXPECT_EQ(
13307       "#warning Leave     all         white!!!!! space* alone!\n",
13308       format("#warning Leave     all         white!!!!! space* alone!\n"));
13309   EXPECT_EQ("#error 1", format("  #  error   1"));
13310   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13311 }
13312 
13313 TEST_F(FormatTest, FormatHashIfExpressions) {
13314   verifyFormat("#if AAAA && BBBB");
13315   verifyFormat("#if (AAAA && BBBB)");
13316   verifyFormat("#elif (AAAA && BBBB)");
13317   // FIXME: Come up with a better indentation for #elif.
13318   verifyFormat(
13319       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13320       "    defined(BBBBBBBB)\n"
13321       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13322       "    defined(BBBBBBBB)\n"
13323       "#endif",
13324       getLLVMStyleWithColumns(65));
13325 }
13326 
13327 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13328   FormatStyle AllowsMergedIf = getGoogleStyle();
13329   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13330       FormatStyle::SIS_WithoutElse;
13331   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13332   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13333   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13334   EXPECT_EQ("if (true) return 42;",
13335             format("if (true)\nreturn 42;", AllowsMergedIf));
13336   FormatStyle ShortMergedIf = AllowsMergedIf;
13337   ShortMergedIf.ColumnLimit = 25;
13338   verifyFormat("#define A \\\n"
13339                "  if (true) return 42;",
13340                ShortMergedIf);
13341   verifyFormat("#define A \\\n"
13342                "  f();    \\\n"
13343                "  if (true)\n"
13344                "#define B",
13345                ShortMergedIf);
13346   verifyFormat("#define A \\\n"
13347                "  f();    \\\n"
13348                "  if (true)\n"
13349                "g();",
13350                ShortMergedIf);
13351   verifyFormat("{\n"
13352                "#ifdef A\n"
13353                "  // Comment\n"
13354                "  if (true) continue;\n"
13355                "#endif\n"
13356                "  // Comment\n"
13357                "  if (true) continue;\n"
13358                "}",
13359                ShortMergedIf);
13360   ShortMergedIf.ColumnLimit = 33;
13361   verifyFormat("#define A \\\n"
13362                "  if constexpr (true) return 42;",
13363                ShortMergedIf);
13364   verifyFormat("#define A \\\n"
13365                "  if CONSTEXPR (true) return 42;",
13366                ShortMergedIf);
13367   ShortMergedIf.ColumnLimit = 29;
13368   verifyFormat("#define A                   \\\n"
13369                "  if (aaaaaaaaaa) return 1; \\\n"
13370                "  return 2;",
13371                ShortMergedIf);
13372   ShortMergedIf.ColumnLimit = 28;
13373   verifyFormat("#define A         \\\n"
13374                "  if (aaaaaaaaaa) \\\n"
13375                "    return 1;     \\\n"
13376                "  return 2;",
13377                ShortMergedIf);
13378   verifyFormat("#define A                \\\n"
13379                "  if constexpr (aaaaaaa) \\\n"
13380                "    return 1;            \\\n"
13381                "  return 2;",
13382                ShortMergedIf);
13383   verifyFormat("#define A                \\\n"
13384                "  if CONSTEXPR (aaaaaaa) \\\n"
13385                "    return 1;            \\\n"
13386                "  return 2;",
13387                ShortMergedIf);
13388 }
13389 
13390 TEST_F(FormatTest, FormatStarDependingOnContext) {
13391   verifyFormat("void f(int *a);");
13392   verifyFormat("void f() { f(fint * b); }");
13393   verifyFormat("class A {\n  void f(int *a);\n};");
13394   verifyFormat("class A {\n  int *a;\n};");
13395   verifyFormat("namespace a {\n"
13396                "namespace b {\n"
13397                "class A {\n"
13398                "  void f() {}\n"
13399                "  int *a;\n"
13400                "};\n"
13401                "} // namespace b\n"
13402                "} // namespace a");
13403 }
13404 
13405 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13406   verifyFormat("while");
13407   verifyFormat("operator");
13408 }
13409 
13410 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13411   // This code would be painfully slow to format if we didn't skip it.
13412   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
13413                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13414                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13415                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13416                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13417                    "A(1, 1)\n"
13418                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13419                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13420                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13421                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13422                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13423                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13424                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13425                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13426                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13427                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13428   // Deeply nested part is untouched, rest is formatted.
13429   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13430             format(std::string("int    i;\n") + Code + "int    j;\n",
13431                    getLLVMStyle(), SC_ExpectIncomplete));
13432 }
13433 
13434 //===----------------------------------------------------------------------===//
13435 // Objective-C tests.
13436 //===----------------------------------------------------------------------===//
13437 
13438 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13439   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13440   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13441             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13442   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13443   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13444   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13445             format("-(NSInteger)Method3:(id)anObject;"));
13446   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13447             format("-(NSInteger)Method4:(id)anObject;"));
13448   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13449             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13450   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13451             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13452   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13453             "forAllCells:(BOOL)flag;",
13454             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13455                    "forAllCells:(BOOL)flag;"));
13456 
13457   // Very long objectiveC method declaration.
13458   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13459                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13460   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13461                "                    inRange:(NSRange)range\n"
13462                "                   outRange:(NSRange)out_range\n"
13463                "                  outRange1:(NSRange)out_range1\n"
13464                "                  outRange2:(NSRange)out_range2\n"
13465                "                  outRange3:(NSRange)out_range3\n"
13466                "                  outRange4:(NSRange)out_range4\n"
13467                "                  outRange5:(NSRange)out_range5\n"
13468                "                  outRange6:(NSRange)out_range6\n"
13469                "                  outRange7:(NSRange)out_range7\n"
13470                "                  outRange8:(NSRange)out_range8\n"
13471                "                  outRange9:(NSRange)out_range9;");
13472 
13473   // When the function name has to be wrapped.
13474   FormatStyle Style = getLLVMStyle();
13475   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13476   // and always indents instead.
13477   Style.IndentWrappedFunctionNames = false;
13478   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13479                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13480                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13481                "}",
13482                Style);
13483   Style.IndentWrappedFunctionNames = true;
13484   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13485                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13486                "               anotherName:(NSString)dddddddddddddd {\n"
13487                "}",
13488                Style);
13489 
13490   verifyFormat("- (int)sum:(vector<int>)numbers;");
13491   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13492   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13493   // protocol lists (but not for template classes):
13494   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13495 
13496   verifyFormat("- (int (*)())foo:(int (*)())f;");
13497   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13498 
13499   // If there's no return type (very rare in practice!), LLVM and Google style
13500   // agree.
13501   verifyFormat("- foo;");
13502   verifyFormat("- foo:(int)f;");
13503   verifyGoogleFormat("- foo:(int)foo;");
13504 }
13505 
13506 TEST_F(FormatTest, BreaksStringLiterals) {
13507   EXPECT_EQ("\"some text \"\n"
13508             "\"other\";",
13509             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13510   EXPECT_EQ("\"some text \"\n"
13511             "\"other\";",
13512             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13513   EXPECT_EQ(
13514       "#define A  \\\n"
13515       "  \"some \"  \\\n"
13516       "  \"text \"  \\\n"
13517       "  \"other\";",
13518       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13519   EXPECT_EQ(
13520       "#define A  \\\n"
13521       "  \"so \"    \\\n"
13522       "  \"text \"  \\\n"
13523       "  \"other\";",
13524       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13525 
13526   EXPECT_EQ("\"some text\"",
13527             format("\"some text\"", getLLVMStyleWithColumns(1)));
13528   EXPECT_EQ("\"some text\"",
13529             format("\"some text\"", getLLVMStyleWithColumns(11)));
13530   EXPECT_EQ("\"some \"\n"
13531             "\"text\"",
13532             format("\"some text\"", getLLVMStyleWithColumns(10)));
13533   EXPECT_EQ("\"some \"\n"
13534             "\"text\"",
13535             format("\"some text\"", getLLVMStyleWithColumns(7)));
13536   EXPECT_EQ("\"some\"\n"
13537             "\" tex\"\n"
13538             "\"t\"",
13539             format("\"some text\"", getLLVMStyleWithColumns(6)));
13540   EXPECT_EQ("\"some\"\n"
13541             "\" tex\"\n"
13542             "\" and\"",
13543             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13544   EXPECT_EQ("\"some\"\n"
13545             "\"/tex\"\n"
13546             "\"/and\"",
13547             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13548 
13549   EXPECT_EQ("variable =\n"
13550             "    \"long string \"\n"
13551             "    \"literal\";",
13552             format("variable = \"long string literal\";",
13553                    getLLVMStyleWithColumns(20)));
13554 
13555   EXPECT_EQ("variable = f(\n"
13556             "    \"long string \"\n"
13557             "    \"literal\",\n"
13558             "    short,\n"
13559             "    loooooooooooooooooooong);",
13560             format("variable = f(\"long string literal\", short, "
13561                    "loooooooooooooooooooong);",
13562                    getLLVMStyleWithColumns(20)));
13563 
13564   EXPECT_EQ(
13565       "f(g(\"long string \"\n"
13566       "    \"literal\"),\n"
13567       "  b);",
13568       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13569   EXPECT_EQ("f(g(\"long string \"\n"
13570             "    \"literal\",\n"
13571             "    a),\n"
13572             "  b);",
13573             format("f(g(\"long string literal\", a), b);",
13574                    getLLVMStyleWithColumns(20)));
13575   EXPECT_EQ(
13576       "f(\"one two\".split(\n"
13577       "    variable));",
13578       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13579   EXPECT_EQ("f(\"one two three four five six \"\n"
13580             "  \"seven\".split(\n"
13581             "      really_looooong_variable));",
13582             format("f(\"one two three four five six seven\"."
13583                    "split(really_looooong_variable));",
13584                    getLLVMStyleWithColumns(33)));
13585 
13586   EXPECT_EQ("f(\"some \"\n"
13587             "  \"text\",\n"
13588             "  other);",
13589             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13590 
13591   // Only break as a last resort.
13592   verifyFormat(
13593       "aaaaaaaaaaaaaaaaaaaa(\n"
13594       "    aaaaaaaaaaaaaaaaaaaa,\n"
13595       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13596 
13597   EXPECT_EQ("\"splitmea\"\n"
13598             "\"trandomp\"\n"
13599             "\"oint\"",
13600             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13601 
13602   EXPECT_EQ("\"split/\"\n"
13603             "\"pathat/\"\n"
13604             "\"slashes\"",
13605             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13606 
13607   EXPECT_EQ("\"split/\"\n"
13608             "\"pathat/\"\n"
13609             "\"slashes\"",
13610             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13611   EXPECT_EQ("\"split at \"\n"
13612             "\"spaces/at/\"\n"
13613             "\"slashes.at.any$\"\n"
13614             "\"non-alphanumeric%\"\n"
13615             "\"1111111111characte\"\n"
13616             "\"rs\"",
13617             format("\"split at "
13618                    "spaces/at/"
13619                    "slashes.at."
13620                    "any$non-"
13621                    "alphanumeric%"
13622                    "1111111111characte"
13623                    "rs\"",
13624                    getLLVMStyleWithColumns(20)));
13625 
13626   // Verify that splitting the strings understands
13627   // Style::AlwaysBreakBeforeMultilineStrings.
13628   EXPECT_EQ("aaaaaaaaaaaa(\n"
13629             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13630             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13631             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13632                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13633                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13634                    getGoogleStyle()));
13635   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13636             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13637             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13638                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13639                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13640                    getGoogleStyle()));
13641   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13642             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13643             format("llvm::outs() << "
13644                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13645                    "aaaaaaaaaaaaaaaaaaa\";"));
13646   EXPECT_EQ("ffff(\n"
13647             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13648             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13649             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13650                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13651                    getGoogleStyle()));
13652 
13653   FormatStyle Style = getLLVMStyleWithColumns(12);
13654   Style.BreakStringLiterals = false;
13655   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13656 
13657   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13658   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13659   EXPECT_EQ("#define A \\\n"
13660             "  \"some \" \\\n"
13661             "  \"text \" \\\n"
13662             "  \"other\";",
13663             format("#define A \"some text other\";", AlignLeft));
13664 }
13665 
13666 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13667   EXPECT_EQ("C a = \"some more \"\n"
13668             "      \"text\";",
13669             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13670 }
13671 
13672 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13673   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13674   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13675   EXPECT_EQ("int i = a(b());",
13676             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13677 }
13678 
13679 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13680   EXPECT_EQ(
13681       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13682       "(\n"
13683       "    \"x\t\");",
13684       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13685              "aaaaaaa("
13686              "\"x\t\");"));
13687 }
13688 
13689 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13690   EXPECT_EQ(
13691       "u8\"utf8 string \"\n"
13692       "u8\"literal\";",
13693       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13694   EXPECT_EQ(
13695       "u\"utf16 string \"\n"
13696       "u\"literal\";",
13697       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13698   EXPECT_EQ(
13699       "U\"utf32 string \"\n"
13700       "U\"literal\";",
13701       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13702   EXPECT_EQ("L\"wide string \"\n"
13703             "L\"literal\";",
13704             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13705   EXPECT_EQ("@\"NSString \"\n"
13706             "@\"literal\";",
13707             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13708   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13709 
13710   // This input makes clang-format try to split the incomplete unicode escape
13711   // sequence, which used to lead to a crasher.
13712   verifyNoCrash(
13713       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13714       getLLVMStyleWithColumns(60));
13715 }
13716 
13717 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13718   FormatStyle Style = getGoogleStyleWithColumns(15);
13719   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13720   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13721   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13722   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13723   EXPECT_EQ("u8R\"x(raw literal)x\";",
13724             format("u8R\"x(raw literal)x\";", Style));
13725 }
13726 
13727 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13728   FormatStyle Style = getLLVMStyleWithColumns(20);
13729   EXPECT_EQ(
13730       "_T(\"aaaaaaaaaaaaaa\")\n"
13731       "_T(\"aaaaaaaaaaaaaa\")\n"
13732       "_T(\"aaaaaaaaaaaa\")",
13733       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13734   EXPECT_EQ("f(x,\n"
13735             "  _T(\"aaaaaaaaaaaa\")\n"
13736             "  _T(\"aaa\"),\n"
13737             "  z);",
13738             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13739 
13740   // FIXME: Handle embedded spaces in one iteration.
13741   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13742   //            "_T(\"aaaaaaaaaaaaa\")\n"
13743   //            "_T(\"aaaaaaaaaaaaa\")\n"
13744   //            "_T(\"a\")",
13745   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13746   //                   getLLVMStyleWithColumns(20)));
13747   EXPECT_EQ(
13748       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13749       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13750   EXPECT_EQ("f(\n"
13751             "#if !TEST\n"
13752             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13753             "#endif\n"
13754             ");",
13755             format("f(\n"
13756                    "#if !TEST\n"
13757                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13758                    "#endif\n"
13759                    ");"));
13760   EXPECT_EQ("f(\n"
13761             "\n"
13762             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13763             format("f(\n"
13764                    "\n"
13765                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13766   // Regression test for accessing tokens past the end of a vector in the
13767   // TokenLexer.
13768   verifyNoCrash(R"(_T(
13769 "
13770 )
13771 )");
13772 }
13773 
13774 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13775   // In a function call with two operands, the second can be broken with no line
13776   // break before it.
13777   EXPECT_EQ(
13778       "func(a, \"long long \"\n"
13779       "        \"long long\");",
13780       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13781   // In a function call with three operands, the second must be broken with a
13782   // line break before it.
13783   EXPECT_EQ("func(a,\n"
13784             "     \"long long long \"\n"
13785             "     \"long\",\n"
13786             "     c);",
13787             format("func(a, \"long long long long\", c);",
13788                    getLLVMStyleWithColumns(24)));
13789   // In a function call with three operands, the third must be broken with a
13790   // line break before it.
13791   EXPECT_EQ("func(a, b,\n"
13792             "     \"long long long \"\n"
13793             "     \"long\");",
13794             format("func(a, b, \"long long long long\");",
13795                    getLLVMStyleWithColumns(24)));
13796   // In a function call with three operands, both the second and the third must
13797   // be broken with a line break before them.
13798   EXPECT_EQ("func(a,\n"
13799             "     \"long long long \"\n"
13800             "     \"long\",\n"
13801             "     \"long long long \"\n"
13802             "     \"long\");",
13803             format("func(a, \"long long long long\", \"long long long long\");",
13804                    getLLVMStyleWithColumns(24)));
13805   // In a chain of << with two operands, the second can be broken with no line
13806   // break before it.
13807   EXPECT_EQ("a << \"line line \"\n"
13808             "     \"line\";",
13809             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13810   // In a chain of << with three operands, the second can be broken with no line
13811   // break before it.
13812   EXPECT_EQ(
13813       "abcde << \"line \"\n"
13814       "         \"line line\"\n"
13815       "      << c;",
13816       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13817   // In a chain of << with three operands, the third must be broken with a line
13818   // break before it.
13819   EXPECT_EQ(
13820       "a << b\n"
13821       "  << \"line line \"\n"
13822       "     \"line\";",
13823       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13824   // In a chain of << with three operands, the second can be broken with no line
13825   // break before it and the third must be broken with a line break before it.
13826   EXPECT_EQ("abcd << \"line line \"\n"
13827             "        \"line\"\n"
13828             "     << \"line line \"\n"
13829             "        \"line\";",
13830             format("abcd << \"line line line\" << \"line line line\";",
13831                    getLLVMStyleWithColumns(20)));
13832   // In a chain of binary operators with two operands, the second can be broken
13833   // with no line break before it.
13834   EXPECT_EQ(
13835       "abcd + \"line line \"\n"
13836       "       \"line line\";",
13837       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13838   // In a chain of binary operators with three operands, the second must be
13839   // broken with a line break before it.
13840   EXPECT_EQ("abcd +\n"
13841             "    \"line line \"\n"
13842             "    \"line line\" +\n"
13843             "    e;",
13844             format("abcd + \"line line line line\" + e;",
13845                    getLLVMStyleWithColumns(20)));
13846   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13847   // the first must be broken with a line break before it.
13848   FormatStyle Style = getLLVMStyleWithColumns(25);
13849   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13850   EXPECT_EQ("someFunction(\n"
13851             "    \"long long long \"\n"
13852             "    \"long\",\n"
13853             "    a);",
13854             format("someFunction(\"long long long long\", a);", Style));
13855 }
13856 
13857 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13858   EXPECT_EQ(
13859       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13860       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13861       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13862       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13863              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13864              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13865 }
13866 
13867 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13868   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13869             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13870   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13871             "multiline raw string literal xxxxxxxxxxxxxx\n"
13872             ")x\",\n"
13873             "              a),\n"
13874             "            b);",
13875             format("fffffffffff(g(R\"x(\n"
13876                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13877                    ")x\", a), b);",
13878                    getGoogleStyleWithColumns(20)));
13879   EXPECT_EQ("fffffffffff(\n"
13880             "    g(R\"x(qqq\n"
13881             "multiline raw string literal xxxxxxxxxxxxxx\n"
13882             ")x\",\n"
13883             "      a),\n"
13884             "    b);",
13885             format("fffffffffff(g(R\"x(qqq\n"
13886                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13887                    ")x\", a), b);",
13888                    getGoogleStyleWithColumns(20)));
13889 
13890   EXPECT_EQ("fffffffffff(R\"x(\n"
13891             "multiline raw string literal xxxxxxxxxxxxxx\n"
13892             ")x\");",
13893             format("fffffffffff(R\"x(\n"
13894                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13895                    ")x\");",
13896                    getGoogleStyleWithColumns(20)));
13897   EXPECT_EQ("fffffffffff(R\"x(\n"
13898             "multiline raw string literal xxxxxxxxxxxxxx\n"
13899             ")x\" + bbbbbb);",
13900             format("fffffffffff(R\"x(\n"
13901                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13902                    ")x\" +   bbbbbb);",
13903                    getGoogleStyleWithColumns(20)));
13904   EXPECT_EQ("fffffffffff(\n"
13905             "    R\"x(\n"
13906             "multiline raw string literal xxxxxxxxxxxxxx\n"
13907             ")x\" +\n"
13908             "    bbbbbb);",
13909             format("fffffffffff(\n"
13910                    " R\"x(\n"
13911                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13912                    ")x\" + bbbbbb);",
13913                    getGoogleStyleWithColumns(20)));
13914   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13915             format("fffffffffff(\n"
13916                    " R\"(single line raw string)\" + bbbbbb);"));
13917 }
13918 
13919 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13920   verifyFormat("string a = \"unterminated;");
13921   EXPECT_EQ("function(\"unterminated,\n"
13922             "         OtherParameter);",
13923             format("function(  \"unterminated,\n"
13924                    "    OtherParameter);"));
13925 }
13926 
13927 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13928   FormatStyle Style = getLLVMStyle();
13929   Style.Standard = FormatStyle::LS_Cpp03;
13930   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13931             format("#define x(_a) printf(\"foo\"_a);", Style));
13932 }
13933 
13934 TEST_F(FormatTest, CppLexVersion) {
13935   FormatStyle Style = getLLVMStyle();
13936   // Formatting of x * y differs if x is a type.
13937   verifyFormat("void foo() { MACRO(a * b); }", Style);
13938   verifyFormat("void foo() { MACRO(int *b); }", Style);
13939 
13940   // LLVM style uses latest lexer.
13941   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13942   Style.Standard = FormatStyle::LS_Cpp17;
13943   // But in c++17, char8_t isn't a keyword.
13944   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13945 }
13946 
13947 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13948 
13949 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13950   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13951             "             \"ddeeefff\");",
13952             format("someFunction(\"aaabbbcccdddeeefff\");",
13953                    getLLVMStyleWithColumns(25)));
13954   EXPECT_EQ("someFunction1234567890(\n"
13955             "    \"aaabbbcccdddeeefff\");",
13956             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13957                    getLLVMStyleWithColumns(26)));
13958   EXPECT_EQ("someFunction1234567890(\n"
13959             "    \"aaabbbcccdddeeeff\"\n"
13960             "    \"f\");",
13961             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13962                    getLLVMStyleWithColumns(25)));
13963   EXPECT_EQ("someFunction1234567890(\n"
13964             "    \"aaabbbcccdddeeeff\"\n"
13965             "    \"f\");",
13966             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13967                    getLLVMStyleWithColumns(24)));
13968   EXPECT_EQ("someFunction(\n"
13969             "    \"aaabbbcc ddde \"\n"
13970             "    \"efff\");",
13971             format("someFunction(\"aaabbbcc ddde efff\");",
13972                    getLLVMStyleWithColumns(25)));
13973   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13974             "             \"ddeeefff\");",
13975             format("someFunction(\"aaabbbccc ddeeefff\");",
13976                    getLLVMStyleWithColumns(25)));
13977   EXPECT_EQ("someFunction1234567890(\n"
13978             "    \"aaabb \"\n"
13979             "    \"cccdddeeefff\");",
13980             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13981                    getLLVMStyleWithColumns(25)));
13982   EXPECT_EQ("#define A          \\\n"
13983             "  string s =       \\\n"
13984             "      \"123456789\"  \\\n"
13985             "      \"0\";         \\\n"
13986             "  int i;",
13987             format("#define A string s = \"1234567890\"; int i;",
13988                    getLLVMStyleWithColumns(20)));
13989   EXPECT_EQ("someFunction(\n"
13990             "    \"aaabbbcc \"\n"
13991             "    \"dddeeefff\");",
13992             format("someFunction(\"aaabbbcc dddeeefff\");",
13993                    getLLVMStyleWithColumns(25)));
13994 }
13995 
13996 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13997   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13998   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13999   EXPECT_EQ("\"test\"\n"
14000             "\"\\n\"",
14001             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
14002   EXPECT_EQ("\"tes\\\\\"\n"
14003             "\"n\"",
14004             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
14005   EXPECT_EQ("\"\\\\\\\\\"\n"
14006             "\"\\n\"",
14007             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
14008   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
14009   EXPECT_EQ("\"\\uff01\"\n"
14010             "\"test\"",
14011             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
14012   EXPECT_EQ("\"\\Uff01ff02\"",
14013             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
14014   EXPECT_EQ("\"\\x000000000001\"\n"
14015             "\"next\"",
14016             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
14017   EXPECT_EQ("\"\\x000000000001next\"",
14018             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
14019   EXPECT_EQ("\"\\x000000000001\"",
14020             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
14021   EXPECT_EQ("\"test\"\n"
14022             "\"\\000000\"\n"
14023             "\"000001\"",
14024             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
14025   EXPECT_EQ("\"test\\000\"\n"
14026             "\"00000000\"\n"
14027             "\"1\"",
14028             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
14029 }
14030 
14031 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
14032   verifyFormat("void f() {\n"
14033                "  return g() {}\n"
14034                "  void h() {}");
14035   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
14036                "g();\n"
14037                "}");
14038 }
14039 
14040 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
14041   verifyFormat(
14042       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
14043 }
14044 
14045 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
14046   verifyFormat("class X {\n"
14047                "  void f() {\n"
14048                "  }\n"
14049                "};",
14050                getLLVMStyleWithColumns(12));
14051 }
14052 
14053 TEST_F(FormatTest, ConfigurableIndentWidth) {
14054   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
14055   EightIndent.IndentWidth = 8;
14056   EightIndent.ContinuationIndentWidth = 8;
14057   verifyFormat("void f() {\n"
14058                "        someFunction();\n"
14059                "        if (true) {\n"
14060                "                f();\n"
14061                "        }\n"
14062                "}",
14063                EightIndent);
14064   verifyFormat("class X {\n"
14065                "        void f() {\n"
14066                "        }\n"
14067                "};",
14068                EightIndent);
14069   verifyFormat("int x[] = {\n"
14070                "        call(),\n"
14071                "        call()};",
14072                EightIndent);
14073 }
14074 
14075 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
14076   verifyFormat("double\n"
14077                "f();",
14078                getLLVMStyleWithColumns(8));
14079 }
14080 
14081 TEST_F(FormatTest, ConfigurableUseOfTab) {
14082   FormatStyle Tab = getLLVMStyleWithColumns(42);
14083   Tab.IndentWidth = 8;
14084   Tab.UseTab = FormatStyle::UT_Always;
14085   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14086 
14087   EXPECT_EQ("if (aaaaaaaa && // q\n"
14088             "    bb)\t\t// w\n"
14089             "\t;",
14090             format("if (aaaaaaaa &&// q\n"
14091                    "bb)// w\n"
14092                    ";",
14093                    Tab));
14094   EXPECT_EQ("if (aaa && bbb) // w\n"
14095             "\t;",
14096             format("if(aaa&&bbb)// w\n"
14097                    ";",
14098                    Tab));
14099 
14100   verifyFormat("class X {\n"
14101                "\tvoid f() {\n"
14102                "\t\tsomeFunction(parameter1,\n"
14103                "\t\t\t     parameter2);\n"
14104                "\t}\n"
14105                "};",
14106                Tab);
14107   verifyFormat("#define A                        \\\n"
14108                "\tvoid f() {               \\\n"
14109                "\t\tsomeFunction(    \\\n"
14110                "\t\t    parameter1,  \\\n"
14111                "\t\t    parameter2); \\\n"
14112                "\t}",
14113                Tab);
14114   verifyFormat("int a;\t      // x\n"
14115                "int bbbbbbbb; // x\n",
14116                Tab);
14117 
14118   Tab.TabWidth = 4;
14119   Tab.IndentWidth = 8;
14120   verifyFormat("class TabWidth4Indent8 {\n"
14121                "\t\tvoid f() {\n"
14122                "\t\t\t\tsomeFunction(parameter1,\n"
14123                "\t\t\t\t\t\t\t parameter2);\n"
14124                "\t\t}\n"
14125                "};",
14126                Tab);
14127 
14128   Tab.TabWidth = 4;
14129   Tab.IndentWidth = 4;
14130   verifyFormat("class TabWidth4Indent4 {\n"
14131                "\tvoid f() {\n"
14132                "\t\tsomeFunction(parameter1,\n"
14133                "\t\t\t\t\t parameter2);\n"
14134                "\t}\n"
14135                "};",
14136                Tab);
14137 
14138   Tab.TabWidth = 8;
14139   Tab.IndentWidth = 4;
14140   verifyFormat("class TabWidth8Indent4 {\n"
14141                "    void f() {\n"
14142                "\tsomeFunction(parameter1,\n"
14143                "\t\t     parameter2);\n"
14144                "    }\n"
14145                "};",
14146                Tab);
14147 
14148   Tab.TabWidth = 8;
14149   Tab.IndentWidth = 8;
14150   EXPECT_EQ("/*\n"
14151             "\t      a\t\tcomment\n"
14152             "\t      in multiple lines\n"
14153             "       */",
14154             format("   /*\t \t \n"
14155                    " \t \t a\t\tcomment\t \t\n"
14156                    " \t \t in multiple lines\t\n"
14157                    " \t  */",
14158                    Tab));
14159 
14160   Tab.UseTab = FormatStyle::UT_ForIndentation;
14161   verifyFormat("{\n"
14162                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14163                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14164                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14165                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14166                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14167                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14168                "};",
14169                Tab);
14170   verifyFormat("enum AA {\n"
14171                "\ta1, // Force multiple lines\n"
14172                "\ta2,\n"
14173                "\ta3\n"
14174                "};",
14175                Tab);
14176   EXPECT_EQ("if (aaaaaaaa && // q\n"
14177             "    bb)         // w\n"
14178             "\t;",
14179             format("if (aaaaaaaa &&// q\n"
14180                    "bb)// w\n"
14181                    ";",
14182                    Tab));
14183   verifyFormat("class X {\n"
14184                "\tvoid f() {\n"
14185                "\t\tsomeFunction(parameter1,\n"
14186                "\t\t             parameter2);\n"
14187                "\t}\n"
14188                "};",
14189                Tab);
14190   verifyFormat("{\n"
14191                "\tQ(\n"
14192                "\t    {\n"
14193                "\t\t    int a;\n"
14194                "\t\t    someFunction(aaaaaaaa,\n"
14195                "\t\t                 bbbbbbb);\n"
14196                "\t    },\n"
14197                "\t    p);\n"
14198                "}",
14199                Tab);
14200   EXPECT_EQ("{\n"
14201             "\t/* aaaa\n"
14202             "\t   bbbb */\n"
14203             "}",
14204             format("{\n"
14205                    "/* aaaa\n"
14206                    "   bbbb */\n"
14207                    "}",
14208                    Tab));
14209   EXPECT_EQ("{\n"
14210             "\t/*\n"
14211             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14212             "\t  bbbbbbbbbbbbb\n"
14213             "\t*/\n"
14214             "}",
14215             format("{\n"
14216                    "/*\n"
14217                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14218                    "*/\n"
14219                    "}",
14220                    Tab));
14221   EXPECT_EQ("{\n"
14222             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14223             "\t// bbbbbbbbbbbbb\n"
14224             "}",
14225             format("{\n"
14226                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14227                    "}",
14228                    Tab));
14229   EXPECT_EQ("{\n"
14230             "\t/*\n"
14231             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14232             "\t  bbbbbbbbbbbbb\n"
14233             "\t*/\n"
14234             "}",
14235             format("{\n"
14236                    "\t/*\n"
14237                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14238                    "\t*/\n"
14239                    "}",
14240                    Tab));
14241   EXPECT_EQ("{\n"
14242             "\t/*\n"
14243             "\n"
14244             "\t*/\n"
14245             "}",
14246             format("{\n"
14247                    "\t/*\n"
14248                    "\n"
14249                    "\t*/\n"
14250                    "}",
14251                    Tab));
14252   EXPECT_EQ("{\n"
14253             "\t/*\n"
14254             " asdf\n"
14255             "\t*/\n"
14256             "}",
14257             format("{\n"
14258                    "\t/*\n"
14259                    " asdf\n"
14260                    "\t*/\n"
14261                    "}",
14262                    Tab));
14263 
14264   verifyFormat("void f() {\n"
14265                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14266                "\t            : bbbbbbbbbbbbbbbbbb\n"
14267                "}",
14268                Tab);
14269   FormatStyle TabNoBreak = Tab;
14270   TabNoBreak.BreakBeforeTernaryOperators = false;
14271   verifyFormat("void f() {\n"
14272                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14273                "\t              bbbbbbbbbbbbbbbbbb\n"
14274                "}",
14275                TabNoBreak);
14276   verifyFormat("void f() {\n"
14277                "\treturn true ?\n"
14278                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14279                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14280                "}",
14281                TabNoBreak);
14282 
14283   Tab.UseTab = FormatStyle::UT_Never;
14284   EXPECT_EQ("/*\n"
14285             "              a\t\tcomment\n"
14286             "              in multiple lines\n"
14287             "       */",
14288             format("   /*\t \t \n"
14289                    " \t \t a\t\tcomment\t \t\n"
14290                    " \t \t in multiple lines\t\n"
14291                    " \t  */",
14292                    Tab));
14293   EXPECT_EQ("/* some\n"
14294             "   comment */",
14295             format(" \t \t /* some\n"
14296                    " \t \t    comment */",
14297                    Tab));
14298   EXPECT_EQ("int a; /* some\n"
14299             "   comment */",
14300             format(" \t \t int a; /* some\n"
14301                    " \t \t    comment */",
14302                    Tab));
14303 
14304   EXPECT_EQ("int a; /* some\n"
14305             "comment */",
14306             format(" \t \t int\ta; /* some\n"
14307                    " \t \t    comment */",
14308                    Tab));
14309   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14310             "    comment */",
14311             format(" \t \t f(\"\t\t\"); /* some\n"
14312                    " \t \t    comment */",
14313                    Tab));
14314   EXPECT_EQ("{\n"
14315             "        /*\n"
14316             "         * Comment\n"
14317             "         */\n"
14318             "        int i;\n"
14319             "}",
14320             format("{\n"
14321                    "\t/*\n"
14322                    "\t * Comment\n"
14323                    "\t */\n"
14324                    "\t int i;\n"
14325                    "}",
14326                    Tab));
14327 
14328   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14329   Tab.TabWidth = 8;
14330   Tab.IndentWidth = 8;
14331   EXPECT_EQ("if (aaaaaaaa && // q\n"
14332             "    bb)         // w\n"
14333             "\t;",
14334             format("if (aaaaaaaa &&// q\n"
14335                    "bb)// w\n"
14336                    ";",
14337                    Tab));
14338   EXPECT_EQ("if (aaa && bbb) // w\n"
14339             "\t;",
14340             format("if(aaa&&bbb)// w\n"
14341                    ";",
14342                    Tab));
14343   verifyFormat("class X {\n"
14344                "\tvoid f() {\n"
14345                "\t\tsomeFunction(parameter1,\n"
14346                "\t\t\t     parameter2);\n"
14347                "\t}\n"
14348                "};",
14349                Tab);
14350   verifyFormat("#define A                        \\\n"
14351                "\tvoid f() {               \\\n"
14352                "\t\tsomeFunction(    \\\n"
14353                "\t\t    parameter1,  \\\n"
14354                "\t\t    parameter2); \\\n"
14355                "\t}",
14356                Tab);
14357   Tab.TabWidth = 4;
14358   Tab.IndentWidth = 8;
14359   verifyFormat("class TabWidth4Indent8 {\n"
14360                "\t\tvoid f() {\n"
14361                "\t\t\t\tsomeFunction(parameter1,\n"
14362                "\t\t\t\t\t\t\t parameter2);\n"
14363                "\t\t}\n"
14364                "};",
14365                Tab);
14366   Tab.TabWidth = 4;
14367   Tab.IndentWidth = 4;
14368   verifyFormat("class TabWidth4Indent4 {\n"
14369                "\tvoid f() {\n"
14370                "\t\tsomeFunction(parameter1,\n"
14371                "\t\t\t\t\t parameter2);\n"
14372                "\t}\n"
14373                "};",
14374                Tab);
14375   Tab.TabWidth = 8;
14376   Tab.IndentWidth = 4;
14377   verifyFormat("class TabWidth8Indent4 {\n"
14378                "    void f() {\n"
14379                "\tsomeFunction(parameter1,\n"
14380                "\t\t     parameter2);\n"
14381                "    }\n"
14382                "};",
14383                Tab);
14384   Tab.TabWidth = 8;
14385   Tab.IndentWidth = 8;
14386   EXPECT_EQ("/*\n"
14387             "\t      a\t\tcomment\n"
14388             "\t      in multiple lines\n"
14389             "       */",
14390             format("   /*\t \t \n"
14391                    " \t \t a\t\tcomment\t \t\n"
14392                    " \t \t in multiple lines\t\n"
14393                    " \t  */",
14394                    Tab));
14395   verifyFormat("{\n"
14396                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14397                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14398                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14399                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14400                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14401                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14402                "};",
14403                Tab);
14404   verifyFormat("enum AA {\n"
14405                "\ta1, // Force multiple lines\n"
14406                "\ta2,\n"
14407                "\ta3\n"
14408                "};",
14409                Tab);
14410   EXPECT_EQ("if (aaaaaaaa && // q\n"
14411             "    bb)         // w\n"
14412             "\t;",
14413             format("if (aaaaaaaa &&// q\n"
14414                    "bb)// w\n"
14415                    ";",
14416                    Tab));
14417   verifyFormat("class X {\n"
14418                "\tvoid f() {\n"
14419                "\t\tsomeFunction(parameter1,\n"
14420                "\t\t\t     parameter2);\n"
14421                "\t}\n"
14422                "};",
14423                Tab);
14424   verifyFormat("{\n"
14425                "\tQ(\n"
14426                "\t    {\n"
14427                "\t\t    int a;\n"
14428                "\t\t    someFunction(aaaaaaaa,\n"
14429                "\t\t\t\t bbbbbbb);\n"
14430                "\t    },\n"
14431                "\t    p);\n"
14432                "}",
14433                Tab);
14434   EXPECT_EQ("{\n"
14435             "\t/* aaaa\n"
14436             "\t   bbbb */\n"
14437             "}",
14438             format("{\n"
14439                    "/* aaaa\n"
14440                    "   bbbb */\n"
14441                    "}",
14442                    Tab));
14443   EXPECT_EQ("{\n"
14444             "\t/*\n"
14445             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14446             "\t  bbbbbbbbbbbbb\n"
14447             "\t*/\n"
14448             "}",
14449             format("{\n"
14450                    "/*\n"
14451                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14452                    "*/\n"
14453                    "}",
14454                    Tab));
14455   EXPECT_EQ("{\n"
14456             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14457             "\t// bbbbbbbbbbbbb\n"
14458             "}",
14459             format("{\n"
14460                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14461                    "}",
14462                    Tab));
14463   EXPECT_EQ("{\n"
14464             "\t/*\n"
14465             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14466             "\t  bbbbbbbbbbbbb\n"
14467             "\t*/\n"
14468             "}",
14469             format("{\n"
14470                    "\t/*\n"
14471                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14472                    "\t*/\n"
14473                    "}",
14474                    Tab));
14475   EXPECT_EQ("{\n"
14476             "\t/*\n"
14477             "\n"
14478             "\t*/\n"
14479             "}",
14480             format("{\n"
14481                    "\t/*\n"
14482                    "\n"
14483                    "\t*/\n"
14484                    "}",
14485                    Tab));
14486   EXPECT_EQ("{\n"
14487             "\t/*\n"
14488             " asdf\n"
14489             "\t*/\n"
14490             "}",
14491             format("{\n"
14492                    "\t/*\n"
14493                    " asdf\n"
14494                    "\t*/\n"
14495                    "}",
14496                    Tab));
14497   EXPECT_EQ("/* some\n"
14498             "   comment */",
14499             format(" \t \t /* some\n"
14500                    " \t \t    comment */",
14501                    Tab));
14502   EXPECT_EQ("int a; /* some\n"
14503             "   comment */",
14504             format(" \t \t int a; /* some\n"
14505                    " \t \t    comment */",
14506                    Tab));
14507   EXPECT_EQ("int a; /* some\n"
14508             "comment */",
14509             format(" \t \t int\ta; /* some\n"
14510                    " \t \t    comment */",
14511                    Tab));
14512   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14513             "    comment */",
14514             format(" \t \t f(\"\t\t\"); /* some\n"
14515                    " \t \t    comment */",
14516                    Tab));
14517   EXPECT_EQ("{\n"
14518             "\t/*\n"
14519             "\t * Comment\n"
14520             "\t */\n"
14521             "\tint i;\n"
14522             "}",
14523             format("{\n"
14524                    "\t/*\n"
14525                    "\t * Comment\n"
14526                    "\t */\n"
14527                    "\t int i;\n"
14528                    "}",
14529                    Tab));
14530   Tab.TabWidth = 2;
14531   Tab.IndentWidth = 2;
14532   EXPECT_EQ("{\n"
14533             "\t/* aaaa\n"
14534             "\t\t bbbb */\n"
14535             "}",
14536             format("{\n"
14537                    "/* aaaa\n"
14538                    "\t bbbb */\n"
14539                    "}",
14540                    Tab));
14541   EXPECT_EQ("{\n"
14542             "\t/*\n"
14543             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14544             "\t\tbbbbbbbbbbbbb\n"
14545             "\t*/\n"
14546             "}",
14547             format("{\n"
14548                    "/*\n"
14549                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14550                    "*/\n"
14551                    "}",
14552                    Tab));
14553   Tab.AlignConsecutiveAssignments.Enabled = true;
14554   Tab.AlignConsecutiveDeclarations.Enabled = true;
14555   Tab.TabWidth = 4;
14556   Tab.IndentWidth = 4;
14557   verifyFormat("class Assign {\n"
14558                "\tvoid f() {\n"
14559                "\t\tint         x      = 123;\n"
14560                "\t\tint         random = 4;\n"
14561                "\t\tstd::string alphabet =\n"
14562                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14563                "\t}\n"
14564                "};",
14565                Tab);
14566 
14567   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14568   Tab.TabWidth = 8;
14569   Tab.IndentWidth = 8;
14570   EXPECT_EQ("if (aaaaaaaa && // q\n"
14571             "    bb)         // w\n"
14572             "\t;",
14573             format("if (aaaaaaaa &&// q\n"
14574                    "bb)// w\n"
14575                    ";",
14576                    Tab));
14577   EXPECT_EQ("if (aaa && bbb) // w\n"
14578             "\t;",
14579             format("if(aaa&&bbb)// w\n"
14580                    ";",
14581                    Tab));
14582   verifyFormat("class X {\n"
14583                "\tvoid f() {\n"
14584                "\t\tsomeFunction(parameter1,\n"
14585                "\t\t             parameter2);\n"
14586                "\t}\n"
14587                "};",
14588                Tab);
14589   verifyFormat("#define A                        \\\n"
14590                "\tvoid f() {               \\\n"
14591                "\t\tsomeFunction(    \\\n"
14592                "\t\t    parameter1,  \\\n"
14593                "\t\t    parameter2); \\\n"
14594                "\t}",
14595                Tab);
14596   Tab.TabWidth = 4;
14597   Tab.IndentWidth = 8;
14598   verifyFormat("class TabWidth4Indent8 {\n"
14599                "\t\tvoid f() {\n"
14600                "\t\t\t\tsomeFunction(parameter1,\n"
14601                "\t\t\t\t             parameter2);\n"
14602                "\t\t}\n"
14603                "};",
14604                Tab);
14605   Tab.TabWidth = 4;
14606   Tab.IndentWidth = 4;
14607   verifyFormat("class TabWidth4Indent4 {\n"
14608                "\tvoid f() {\n"
14609                "\t\tsomeFunction(parameter1,\n"
14610                "\t\t             parameter2);\n"
14611                "\t}\n"
14612                "};",
14613                Tab);
14614   Tab.TabWidth = 8;
14615   Tab.IndentWidth = 4;
14616   verifyFormat("class TabWidth8Indent4 {\n"
14617                "    void f() {\n"
14618                "\tsomeFunction(parameter1,\n"
14619                "\t             parameter2);\n"
14620                "    }\n"
14621                "};",
14622                Tab);
14623   Tab.TabWidth = 8;
14624   Tab.IndentWidth = 8;
14625   EXPECT_EQ("/*\n"
14626             "              a\t\tcomment\n"
14627             "              in multiple lines\n"
14628             "       */",
14629             format("   /*\t \t \n"
14630                    " \t \t a\t\tcomment\t \t\n"
14631                    " \t \t in multiple lines\t\n"
14632                    " \t  */",
14633                    Tab));
14634   verifyFormat("{\n"
14635                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14636                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14637                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14638                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14639                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14640                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14641                "};",
14642                Tab);
14643   verifyFormat("enum AA {\n"
14644                "\ta1, // Force multiple lines\n"
14645                "\ta2,\n"
14646                "\ta3\n"
14647                "};",
14648                Tab);
14649   EXPECT_EQ("if (aaaaaaaa && // q\n"
14650             "    bb)         // w\n"
14651             "\t;",
14652             format("if (aaaaaaaa &&// q\n"
14653                    "bb)// w\n"
14654                    ";",
14655                    Tab));
14656   verifyFormat("class X {\n"
14657                "\tvoid f() {\n"
14658                "\t\tsomeFunction(parameter1,\n"
14659                "\t\t             parameter2);\n"
14660                "\t}\n"
14661                "};",
14662                Tab);
14663   verifyFormat("{\n"
14664                "\tQ(\n"
14665                "\t    {\n"
14666                "\t\t    int a;\n"
14667                "\t\t    someFunction(aaaaaaaa,\n"
14668                "\t\t                 bbbbbbb);\n"
14669                "\t    },\n"
14670                "\t    p);\n"
14671                "}",
14672                Tab);
14673   EXPECT_EQ("{\n"
14674             "\t/* aaaa\n"
14675             "\t   bbbb */\n"
14676             "}",
14677             format("{\n"
14678                    "/* aaaa\n"
14679                    "   bbbb */\n"
14680                    "}",
14681                    Tab));
14682   EXPECT_EQ("{\n"
14683             "\t/*\n"
14684             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14685             "\t  bbbbbbbbbbbbb\n"
14686             "\t*/\n"
14687             "}",
14688             format("{\n"
14689                    "/*\n"
14690                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14691                    "*/\n"
14692                    "}",
14693                    Tab));
14694   EXPECT_EQ("{\n"
14695             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14696             "\t// bbbbbbbbbbbbb\n"
14697             "}",
14698             format("{\n"
14699                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14700                    "}",
14701                    Tab));
14702   EXPECT_EQ("{\n"
14703             "\t/*\n"
14704             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14705             "\t  bbbbbbbbbbbbb\n"
14706             "\t*/\n"
14707             "}",
14708             format("{\n"
14709                    "\t/*\n"
14710                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14711                    "\t*/\n"
14712                    "}",
14713                    Tab));
14714   EXPECT_EQ("{\n"
14715             "\t/*\n"
14716             "\n"
14717             "\t*/\n"
14718             "}",
14719             format("{\n"
14720                    "\t/*\n"
14721                    "\n"
14722                    "\t*/\n"
14723                    "}",
14724                    Tab));
14725   EXPECT_EQ("{\n"
14726             "\t/*\n"
14727             " asdf\n"
14728             "\t*/\n"
14729             "}",
14730             format("{\n"
14731                    "\t/*\n"
14732                    " asdf\n"
14733                    "\t*/\n"
14734                    "}",
14735                    Tab));
14736   EXPECT_EQ("/* some\n"
14737             "   comment */",
14738             format(" \t \t /* some\n"
14739                    " \t \t    comment */",
14740                    Tab));
14741   EXPECT_EQ("int a; /* some\n"
14742             "   comment */",
14743             format(" \t \t int a; /* some\n"
14744                    " \t \t    comment */",
14745                    Tab));
14746   EXPECT_EQ("int a; /* some\n"
14747             "comment */",
14748             format(" \t \t int\ta; /* some\n"
14749                    " \t \t    comment */",
14750                    Tab));
14751   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14752             "    comment */",
14753             format(" \t \t f(\"\t\t\"); /* some\n"
14754                    " \t \t    comment */",
14755                    Tab));
14756   EXPECT_EQ("{\n"
14757             "\t/*\n"
14758             "\t * Comment\n"
14759             "\t */\n"
14760             "\tint i;\n"
14761             "}",
14762             format("{\n"
14763                    "\t/*\n"
14764                    "\t * Comment\n"
14765                    "\t */\n"
14766                    "\t int i;\n"
14767                    "}",
14768                    Tab));
14769   Tab.TabWidth = 2;
14770   Tab.IndentWidth = 2;
14771   EXPECT_EQ("{\n"
14772             "\t/* aaaa\n"
14773             "\t   bbbb */\n"
14774             "}",
14775             format("{\n"
14776                    "/* aaaa\n"
14777                    "   bbbb */\n"
14778                    "}",
14779                    Tab));
14780   EXPECT_EQ("{\n"
14781             "\t/*\n"
14782             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14783             "\t  bbbbbbbbbbbbb\n"
14784             "\t*/\n"
14785             "}",
14786             format("{\n"
14787                    "/*\n"
14788                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14789                    "*/\n"
14790                    "}",
14791                    Tab));
14792   Tab.AlignConsecutiveAssignments.Enabled = true;
14793   Tab.AlignConsecutiveDeclarations.Enabled = true;
14794   Tab.TabWidth = 4;
14795   Tab.IndentWidth = 4;
14796   verifyFormat("class Assign {\n"
14797                "\tvoid f() {\n"
14798                "\t\tint         x      = 123;\n"
14799                "\t\tint         random = 4;\n"
14800                "\t\tstd::string alphabet =\n"
14801                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14802                "\t}\n"
14803                "};",
14804                Tab);
14805   Tab.AlignOperands = FormatStyle::OAS_Align;
14806   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14807                "                 cccccccccccccccccccc;",
14808                Tab);
14809   // no alignment
14810   verifyFormat("int aaaaaaaaaa =\n"
14811                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14812                Tab);
14813   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14814                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14815                "                        : 333333333333333;",
14816                Tab);
14817   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14818   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14819   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14820                "               + cccccccccccccccccccc;",
14821                Tab);
14822 }
14823 
14824 TEST_F(FormatTest, ZeroTabWidth) {
14825   FormatStyle Tab = getLLVMStyleWithColumns(42);
14826   Tab.IndentWidth = 8;
14827   Tab.UseTab = FormatStyle::UT_Never;
14828   Tab.TabWidth = 0;
14829   EXPECT_EQ("void a(){\n"
14830             "    // line starts with '\t'\n"
14831             "};",
14832             format("void a(){\n"
14833                    "\t// line starts with '\t'\n"
14834                    "};",
14835                    Tab));
14836 
14837   EXPECT_EQ("void a(){\n"
14838             "    // line starts with '\t'\n"
14839             "};",
14840             format("void a(){\n"
14841                    "\t\t// line starts with '\t'\n"
14842                    "};",
14843                    Tab));
14844 
14845   Tab.UseTab = FormatStyle::UT_ForIndentation;
14846   EXPECT_EQ("void a(){\n"
14847             "    // line starts with '\t'\n"
14848             "};",
14849             format("void a(){\n"
14850                    "\t// line starts with '\t'\n"
14851                    "};",
14852                    Tab));
14853 
14854   EXPECT_EQ("void a(){\n"
14855             "    // line starts with '\t'\n"
14856             "};",
14857             format("void a(){\n"
14858                    "\t\t// line starts with '\t'\n"
14859                    "};",
14860                    Tab));
14861 
14862   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14863   EXPECT_EQ("void a(){\n"
14864             "    // line starts with '\t'\n"
14865             "};",
14866             format("void a(){\n"
14867                    "\t// line starts with '\t'\n"
14868                    "};",
14869                    Tab));
14870 
14871   EXPECT_EQ("void a(){\n"
14872             "    // line starts with '\t'\n"
14873             "};",
14874             format("void a(){\n"
14875                    "\t\t// line starts with '\t'\n"
14876                    "};",
14877                    Tab));
14878 
14879   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14880   EXPECT_EQ("void a(){\n"
14881             "    // line starts with '\t'\n"
14882             "};",
14883             format("void a(){\n"
14884                    "\t// line starts with '\t'\n"
14885                    "};",
14886                    Tab));
14887 
14888   EXPECT_EQ("void a(){\n"
14889             "    // line starts with '\t'\n"
14890             "};",
14891             format("void a(){\n"
14892                    "\t\t// line starts with '\t'\n"
14893                    "};",
14894                    Tab));
14895 
14896   Tab.UseTab = FormatStyle::UT_Always;
14897   EXPECT_EQ("void a(){\n"
14898             "// line starts with '\t'\n"
14899             "};",
14900             format("void a(){\n"
14901                    "\t// line starts with '\t'\n"
14902                    "};",
14903                    Tab));
14904 
14905   EXPECT_EQ("void a(){\n"
14906             "// line starts with '\t'\n"
14907             "};",
14908             format("void a(){\n"
14909                    "\t\t// line starts with '\t'\n"
14910                    "};",
14911                    Tab));
14912 }
14913 
14914 TEST_F(FormatTest, CalculatesOriginalColumn) {
14915   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14916             "q\"; /* some\n"
14917             "       comment */",
14918             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14919                    "q\"; /* some\n"
14920                    "       comment */",
14921                    getLLVMStyle()));
14922   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14923             "/* some\n"
14924             "   comment */",
14925             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14926                    " /* some\n"
14927                    "    comment */",
14928                    getLLVMStyle()));
14929   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14930             "qqq\n"
14931             "/* some\n"
14932             "   comment */",
14933             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14934                    "qqq\n"
14935                    " /* some\n"
14936                    "    comment */",
14937                    getLLVMStyle()));
14938   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14939             "wwww; /* some\n"
14940             "         comment */",
14941             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14942                    "wwww; /* some\n"
14943                    "         comment */",
14944                    getLLVMStyle()));
14945 }
14946 
14947 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14948   FormatStyle NoSpace = getLLVMStyle();
14949   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14950 
14951   verifyFormat("while(true)\n"
14952                "  continue;",
14953                NoSpace);
14954   verifyFormat("for(;;)\n"
14955                "  continue;",
14956                NoSpace);
14957   verifyFormat("if(true)\n"
14958                "  f();\n"
14959                "else if(true)\n"
14960                "  f();",
14961                NoSpace);
14962   verifyFormat("do {\n"
14963                "  do_something();\n"
14964                "} while(something());",
14965                NoSpace);
14966   verifyFormat("switch(x) {\n"
14967                "default:\n"
14968                "  break;\n"
14969                "}",
14970                NoSpace);
14971   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14972   verifyFormat("size_t x = sizeof(x);", NoSpace);
14973   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14974   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14975   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14976   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14977   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14978   verifyFormat("alignas(128) char a[128];", NoSpace);
14979   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14980   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14981   verifyFormat("int f() throw(Deprecated);", NoSpace);
14982   verifyFormat("typedef void (*cb)(int);", NoSpace);
14983   verifyFormat("T A::operator()();", NoSpace);
14984   verifyFormat("X A::operator++(T);", NoSpace);
14985   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14986 
14987   FormatStyle Space = getLLVMStyle();
14988   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14989 
14990   verifyFormat("int f ();", Space);
14991   verifyFormat("void f (int a, T b) {\n"
14992                "  while (true)\n"
14993                "    continue;\n"
14994                "}",
14995                Space);
14996   verifyFormat("if (true)\n"
14997                "  f ();\n"
14998                "else if (true)\n"
14999                "  f ();",
15000                Space);
15001   verifyFormat("do {\n"
15002                "  do_something ();\n"
15003                "} while (something ());",
15004                Space);
15005   verifyFormat("switch (x) {\n"
15006                "default:\n"
15007                "  break;\n"
15008                "}",
15009                Space);
15010   verifyFormat("A::A () : a (1) {}", Space);
15011   verifyFormat("void f () __attribute__ ((asdf));", Space);
15012   verifyFormat("*(&a + 1);\n"
15013                "&((&a)[1]);\n"
15014                "a[(b + c) * d];\n"
15015                "(((a + 1) * 2) + 3) * 4;",
15016                Space);
15017   verifyFormat("#define A(x) x", Space);
15018   verifyFormat("#define A (x) x", Space);
15019   verifyFormat("#if defined(x)\n"
15020                "#endif",
15021                Space);
15022   verifyFormat("auto i = std::make_unique<int> (5);", Space);
15023   verifyFormat("size_t x = sizeof (x);", Space);
15024   verifyFormat("auto f (int x) -> decltype (x);", Space);
15025   verifyFormat("auto f (int x) -> typeof (x);", Space);
15026   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
15027   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
15028   verifyFormat("int f (T x) noexcept (x.create ());", Space);
15029   verifyFormat("alignas (128) char a[128];", Space);
15030   verifyFormat("size_t x = alignof (MyType);", Space);
15031   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
15032   verifyFormat("int f () throw (Deprecated);", Space);
15033   verifyFormat("typedef void (*cb) (int);", Space);
15034   // FIXME these tests regressed behaviour.
15035   // verifyFormat("T A::operator() ();", Space);
15036   // verifyFormat("X A::operator++ (T);", Space);
15037   verifyFormat("auto lambda = [] () { return 0; };", Space);
15038   verifyFormat("int x = int (y);", Space);
15039 
15040   FormatStyle SomeSpace = getLLVMStyle();
15041   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
15042 
15043   verifyFormat("[]() -> float {}", SomeSpace);
15044   verifyFormat("[] (auto foo) {}", SomeSpace);
15045   verifyFormat("[foo]() -> int {}", SomeSpace);
15046   verifyFormat("int f();", SomeSpace);
15047   verifyFormat("void f (int a, T b) {\n"
15048                "  while (true)\n"
15049                "    continue;\n"
15050                "}",
15051                SomeSpace);
15052   verifyFormat("if (true)\n"
15053                "  f();\n"
15054                "else if (true)\n"
15055                "  f();",
15056                SomeSpace);
15057   verifyFormat("do {\n"
15058                "  do_something();\n"
15059                "} while (something());",
15060                SomeSpace);
15061   verifyFormat("switch (x) {\n"
15062                "default:\n"
15063                "  break;\n"
15064                "}",
15065                SomeSpace);
15066   verifyFormat("A::A() : a (1) {}", SomeSpace);
15067   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
15068   verifyFormat("*(&a + 1);\n"
15069                "&((&a)[1]);\n"
15070                "a[(b + c) * d];\n"
15071                "(((a + 1) * 2) + 3) * 4;",
15072                SomeSpace);
15073   verifyFormat("#define A(x) x", SomeSpace);
15074   verifyFormat("#define A (x) x", SomeSpace);
15075   verifyFormat("#if defined(x)\n"
15076                "#endif",
15077                SomeSpace);
15078   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
15079   verifyFormat("size_t x = sizeof (x);", SomeSpace);
15080   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
15081   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
15082   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
15083   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
15084   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
15085   verifyFormat("alignas (128) char a[128];", SomeSpace);
15086   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
15087   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15088                SomeSpace);
15089   verifyFormat("int f() throw (Deprecated);", SomeSpace);
15090   verifyFormat("typedef void (*cb) (int);", SomeSpace);
15091   verifyFormat("T A::operator()();", SomeSpace);
15092   // FIXME these tests regressed behaviour.
15093   // verifyFormat("X A::operator++ (T);", SomeSpace);
15094   verifyFormat("int x = int (y);", SomeSpace);
15095   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
15096 
15097   FormatStyle SpaceControlStatements = getLLVMStyle();
15098   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15099   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
15100 
15101   verifyFormat("while (true)\n"
15102                "  continue;",
15103                SpaceControlStatements);
15104   verifyFormat("if (true)\n"
15105                "  f();\n"
15106                "else if (true)\n"
15107                "  f();",
15108                SpaceControlStatements);
15109   verifyFormat("for (;;) {\n"
15110                "  do_something();\n"
15111                "}",
15112                SpaceControlStatements);
15113   verifyFormat("do {\n"
15114                "  do_something();\n"
15115                "} while (something());",
15116                SpaceControlStatements);
15117   verifyFormat("switch (x) {\n"
15118                "default:\n"
15119                "  break;\n"
15120                "}",
15121                SpaceControlStatements);
15122 
15123   FormatStyle SpaceFuncDecl = getLLVMStyle();
15124   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15125   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
15126 
15127   verifyFormat("int f ();", SpaceFuncDecl);
15128   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
15129   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
15130   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
15131   verifyFormat("#define A(x) x", SpaceFuncDecl);
15132   verifyFormat("#define A (x) x", SpaceFuncDecl);
15133   verifyFormat("#if defined(x)\n"
15134                "#endif",
15135                SpaceFuncDecl);
15136   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
15137   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
15138   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
15139   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
15140   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
15141   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
15142   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
15143   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
15144   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
15145   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15146                SpaceFuncDecl);
15147   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
15148   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
15149   // FIXME these tests regressed behaviour.
15150   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
15151   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
15152   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
15153   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
15154   verifyFormat("int x = int(y);", SpaceFuncDecl);
15155   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15156                SpaceFuncDecl);
15157 
15158   FormatStyle SpaceFuncDef = getLLVMStyle();
15159   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15160   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
15161 
15162   verifyFormat("int f();", SpaceFuncDef);
15163   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
15164   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
15165   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
15166   verifyFormat("#define A(x) x", SpaceFuncDef);
15167   verifyFormat("#define A (x) x", SpaceFuncDef);
15168   verifyFormat("#if defined(x)\n"
15169                "#endif",
15170                SpaceFuncDef);
15171   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
15172   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
15173   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
15174   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
15175   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
15176   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
15177   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
15178   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
15179   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
15180   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15181                SpaceFuncDef);
15182   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
15183   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
15184   verifyFormat("T A::operator()();", SpaceFuncDef);
15185   verifyFormat("X A::operator++(T);", SpaceFuncDef);
15186   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
15187   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
15188   verifyFormat("int x = int(y);", SpaceFuncDef);
15189   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15190                SpaceFuncDef);
15191 
15192   FormatStyle SpaceIfMacros = getLLVMStyle();
15193   SpaceIfMacros.IfMacros.clear();
15194   SpaceIfMacros.IfMacros.push_back("MYIF");
15195   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15196   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15197   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15198   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15199   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15200 
15201   FormatStyle SpaceForeachMacros = getLLVMStyle();
15202   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15203             FormatStyle::SBS_Never);
15204   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15205   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15206   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15207   verifyFormat("for (;;) {\n"
15208                "}",
15209                SpaceForeachMacros);
15210   verifyFormat("foreach (Item *item, itemlist) {\n"
15211                "}",
15212                SpaceForeachMacros);
15213   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15214                "}",
15215                SpaceForeachMacros);
15216   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15217                "}",
15218                SpaceForeachMacros);
15219   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15220 
15221   FormatStyle SomeSpace2 = getLLVMStyle();
15222   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15223   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15224   verifyFormat("[]() -> float {}", SomeSpace2);
15225   verifyFormat("[] (auto foo) {}", SomeSpace2);
15226   verifyFormat("[foo]() -> int {}", SomeSpace2);
15227   verifyFormat("int f();", SomeSpace2);
15228   verifyFormat("void f (int a, T b) {\n"
15229                "  while (true)\n"
15230                "    continue;\n"
15231                "}",
15232                SomeSpace2);
15233   verifyFormat("if (true)\n"
15234                "  f();\n"
15235                "else if (true)\n"
15236                "  f();",
15237                SomeSpace2);
15238   verifyFormat("do {\n"
15239                "  do_something();\n"
15240                "} while (something());",
15241                SomeSpace2);
15242   verifyFormat("switch (x) {\n"
15243                "default:\n"
15244                "  break;\n"
15245                "}",
15246                SomeSpace2);
15247   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15248   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15249   verifyFormat("*(&a + 1);\n"
15250                "&((&a)[1]);\n"
15251                "a[(b + c) * d];\n"
15252                "(((a + 1) * 2) + 3) * 4;",
15253                SomeSpace2);
15254   verifyFormat("#define A(x) x", SomeSpace2);
15255   verifyFormat("#define A (x) x", SomeSpace2);
15256   verifyFormat("#if defined(x)\n"
15257                "#endif",
15258                SomeSpace2);
15259   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15260   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15261   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15262   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15263   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15264   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15265   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15266   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15267   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15268   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15269                SomeSpace2);
15270   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15271   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15272   verifyFormat("T A::operator()();", SomeSpace2);
15273   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15274   verifyFormat("int x = int (y);", SomeSpace2);
15275   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15276 
15277   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15278   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15279   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15280       .AfterOverloadedOperator = true;
15281 
15282   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15283   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15284   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15285   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15286 
15287   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15288       .AfterOverloadedOperator = false;
15289 
15290   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15291   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15292   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15293   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15294 
15295   auto SpaceAfterRequires = getLLVMStyle();
15296   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15297   EXPECT_FALSE(
15298       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15299   EXPECT_FALSE(
15300       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15301   verifyFormat("void f(auto x)\n"
15302                "  requires requires(int i) { x + i; }\n"
15303                "{}",
15304                SpaceAfterRequires);
15305   verifyFormat("void f(auto x)\n"
15306                "  requires(requires(int i) { x + i; })\n"
15307                "{}",
15308                SpaceAfterRequires);
15309   verifyFormat("if (requires(int i) { x + i; })\n"
15310                "  return;",
15311                SpaceAfterRequires);
15312   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15313   verifyFormat("template <typename T>\n"
15314                "  requires(Foo<T>)\n"
15315                "class Bar;",
15316                SpaceAfterRequires);
15317 
15318   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15319   verifyFormat("void f(auto x)\n"
15320                "  requires requires(int i) { x + i; }\n"
15321                "{}",
15322                SpaceAfterRequires);
15323   verifyFormat("void f(auto x)\n"
15324                "  requires (requires(int i) { x + i; })\n"
15325                "{}",
15326                SpaceAfterRequires);
15327   verifyFormat("if (requires(int i) { x + i; })\n"
15328                "  return;",
15329                SpaceAfterRequires);
15330   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15331   verifyFormat("template <typename T>\n"
15332                "  requires (Foo<T>)\n"
15333                "class Bar;",
15334                SpaceAfterRequires);
15335 
15336   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15337   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15338   verifyFormat("void f(auto x)\n"
15339                "  requires requires (int i) { x + i; }\n"
15340                "{}",
15341                SpaceAfterRequires);
15342   verifyFormat("void f(auto x)\n"
15343                "  requires(requires (int i) { x + i; })\n"
15344                "{}",
15345                SpaceAfterRequires);
15346   verifyFormat("if (requires (int i) { x + i; })\n"
15347                "  return;",
15348                SpaceAfterRequires);
15349   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15350   verifyFormat("template <typename T>\n"
15351                "  requires(Foo<T>)\n"
15352                "class Bar;",
15353                SpaceAfterRequires);
15354 
15355   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15356   verifyFormat("void f(auto x)\n"
15357                "  requires requires (int i) { x + i; }\n"
15358                "{}",
15359                SpaceAfterRequires);
15360   verifyFormat("void f(auto x)\n"
15361                "  requires (requires (int i) { x + i; })\n"
15362                "{}",
15363                SpaceAfterRequires);
15364   verifyFormat("if (requires (int i) { x + i; })\n"
15365                "  return;",
15366                SpaceAfterRequires);
15367   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15368   verifyFormat("template <typename T>\n"
15369                "  requires (Foo<T>)\n"
15370                "class Bar;",
15371                SpaceAfterRequires);
15372 }
15373 
15374 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15375   FormatStyle Spaces = getLLVMStyle();
15376   Spaces.SpaceAfterLogicalNot = true;
15377 
15378   verifyFormat("bool x = ! y", Spaces);
15379   verifyFormat("if (! isFailure())", Spaces);
15380   verifyFormat("if (! (a && b))", Spaces);
15381   verifyFormat("\"Error!\"", Spaces);
15382   verifyFormat("! ! x", Spaces);
15383 }
15384 
15385 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15386   FormatStyle Spaces = getLLVMStyle();
15387 
15388   Spaces.SpacesInParentheses = true;
15389   verifyFormat("do_something( ::globalVar );", Spaces);
15390   verifyFormat("call( x, y, z );", Spaces);
15391   verifyFormat("call();", Spaces);
15392   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15393   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15394                Spaces);
15395   verifyFormat("while ( (bool)1 )\n"
15396                "  continue;",
15397                Spaces);
15398   verifyFormat("for ( ;; )\n"
15399                "  continue;",
15400                Spaces);
15401   verifyFormat("if ( true )\n"
15402                "  f();\n"
15403                "else if ( true )\n"
15404                "  f();",
15405                Spaces);
15406   verifyFormat("do {\n"
15407                "  do_something( (int)i );\n"
15408                "} while ( something() );",
15409                Spaces);
15410   verifyFormat("switch ( x ) {\n"
15411                "default:\n"
15412                "  break;\n"
15413                "}",
15414                Spaces);
15415 
15416   Spaces.SpacesInParentheses = false;
15417   Spaces.SpacesInCStyleCastParentheses = true;
15418   verifyFormat("Type *A = ( Type * )P;", Spaces);
15419   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15420   verifyFormat("x = ( int32 )y;", Spaces);
15421   verifyFormat("int a = ( int )(2.0f);", Spaces);
15422   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15423   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15424   verifyFormat("#define x (( int )-1)", Spaces);
15425 
15426   // Run the first set of tests again with:
15427   Spaces.SpacesInParentheses = false;
15428   Spaces.SpaceInEmptyParentheses = true;
15429   Spaces.SpacesInCStyleCastParentheses = true;
15430   verifyFormat("call(x, y, z);", Spaces);
15431   verifyFormat("call( );", Spaces);
15432   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15433   verifyFormat("while (( bool )1)\n"
15434                "  continue;",
15435                Spaces);
15436   verifyFormat("for (;;)\n"
15437                "  continue;",
15438                Spaces);
15439   verifyFormat("if (true)\n"
15440                "  f( );\n"
15441                "else if (true)\n"
15442                "  f( );",
15443                Spaces);
15444   verifyFormat("do {\n"
15445                "  do_something(( int )i);\n"
15446                "} while (something( ));",
15447                Spaces);
15448   verifyFormat("switch (x) {\n"
15449                "default:\n"
15450                "  break;\n"
15451                "}",
15452                Spaces);
15453 
15454   // Run the first set of tests again with:
15455   Spaces.SpaceAfterCStyleCast = true;
15456   verifyFormat("call(x, y, z);", Spaces);
15457   verifyFormat("call( );", Spaces);
15458   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15459   verifyFormat("while (( bool ) 1)\n"
15460                "  continue;",
15461                Spaces);
15462   verifyFormat("for (;;)\n"
15463                "  continue;",
15464                Spaces);
15465   verifyFormat("if (true)\n"
15466                "  f( );\n"
15467                "else if (true)\n"
15468                "  f( );",
15469                Spaces);
15470   verifyFormat("do {\n"
15471                "  do_something(( int ) i);\n"
15472                "} while (something( ));",
15473                Spaces);
15474   verifyFormat("switch (x) {\n"
15475                "default:\n"
15476                "  break;\n"
15477                "}",
15478                Spaces);
15479   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15480   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15481   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15482   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15483   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15484 
15485   // Run subset of tests again with:
15486   Spaces.SpacesInCStyleCastParentheses = false;
15487   Spaces.SpaceAfterCStyleCast = true;
15488   verifyFormat("while ((bool) 1)\n"
15489                "  continue;",
15490                Spaces);
15491   verifyFormat("do {\n"
15492                "  do_something((int) i);\n"
15493                "} while (something( ));",
15494                Spaces);
15495 
15496   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15497   verifyFormat("size_t idx = (size_t) a;", Spaces);
15498   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15499   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15500   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15501   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15502   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15503   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15504   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15505   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15506   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15507   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15508   Spaces.ColumnLimit = 80;
15509   Spaces.IndentWidth = 4;
15510   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15511   verifyFormat("void foo( ) {\n"
15512                "    size_t foo = (*(function))(\n"
15513                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15514                "BarrrrrrrrrrrrLong,\n"
15515                "        FoooooooooLooooong);\n"
15516                "}",
15517                Spaces);
15518   Spaces.SpaceAfterCStyleCast = false;
15519   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15520   verifyFormat("size_t idx = (size_t)a;", Spaces);
15521   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15522   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15523   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15524   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15525   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15526 
15527   verifyFormat("void foo( ) {\n"
15528                "    size_t foo = (*(function))(\n"
15529                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15530                "BarrrrrrrrrrrrLong,\n"
15531                "        FoooooooooLooooong);\n"
15532                "}",
15533                Spaces);
15534 }
15535 
15536 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15537   verifyFormat("int a[5];");
15538   verifyFormat("a[3] += 42;");
15539 
15540   FormatStyle Spaces = getLLVMStyle();
15541   Spaces.SpacesInSquareBrackets = true;
15542   // Not lambdas.
15543   verifyFormat("int a[ 5 ];", Spaces);
15544   verifyFormat("a[ 3 ] += 42;", Spaces);
15545   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15546   verifyFormat("double &operator[](int i) { return 0; }\n"
15547                "int i;",
15548                Spaces);
15549   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15550   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15551   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15552   // Lambdas.
15553   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15554   verifyFormat("return [ i, args... ] {};", Spaces);
15555   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15556   verifyFormat("int foo = [ = ]() {};", Spaces);
15557   verifyFormat("int foo = [ & ]() {};", Spaces);
15558   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15559   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15560 }
15561 
15562 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15563   FormatStyle NoSpaceStyle = getLLVMStyle();
15564   verifyFormat("int a[5];", NoSpaceStyle);
15565   verifyFormat("a[3] += 42;", NoSpaceStyle);
15566 
15567   verifyFormat("int a[1];", NoSpaceStyle);
15568   verifyFormat("int 1 [a];", NoSpaceStyle);
15569   verifyFormat("int a[1][2];", NoSpaceStyle);
15570   verifyFormat("a[7] = 5;", NoSpaceStyle);
15571   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15572   verifyFormat("f([] {})", NoSpaceStyle);
15573 
15574   FormatStyle Space = getLLVMStyle();
15575   Space.SpaceBeforeSquareBrackets = true;
15576   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15577   verifyFormat("return [i, args...] {};", Space);
15578 
15579   verifyFormat("int a [5];", Space);
15580   verifyFormat("a [3] += 42;", Space);
15581   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15582   verifyFormat("double &operator[](int i) { return 0; }\n"
15583                "int i;",
15584                Space);
15585   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15586   verifyFormat("int i = a [a][a]->f();", Space);
15587   verifyFormat("int i = (*b) [a]->f();", Space);
15588 
15589   verifyFormat("int a [1];", Space);
15590   verifyFormat("int 1 [a];", Space);
15591   verifyFormat("int a [1][2];", Space);
15592   verifyFormat("a [7] = 5;", Space);
15593   verifyFormat("int a = (f()) [23];", Space);
15594   verifyFormat("f([] {})", Space);
15595 }
15596 
15597 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15598   verifyFormat("int a = 5;");
15599   verifyFormat("a += 42;");
15600   verifyFormat("a or_eq 8;");
15601 
15602   FormatStyle Spaces = getLLVMStyle();
15603   Spaces.SpaceBeforeAssignmentOperators = false;
15604   verifyFormat("int a= 5;", Spaces);
15605   verifyFormat("a+= 42;", Spaces);
15606   verifyFormat("a or_eq 8;", Spaces);
15607 }
15608 
15609 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15610   verifyFormat("class Foo : public Bar {};");
15611   verifyFormat("Foo::Foo() : foo(1) {}");
15612   verifyFormat("for (auto a : b) {\n}");
15613   verifyFormat("int x = a ? b : c;");
15614   verifyFormat("{\n"
15615                "label0:\n"
15616                "  int x = 0;\n"
15617                "}");
15618   verifyFormat("switch (x) {\n"
15619                "case 1:\n"
15620                "default:\n"
15621                "}");
15622   verifyFormat("switch (allBraces) {\n"
15623                "case 1: {\n"
15624                "  break;\n"
15625                "}\n"
15626                "case 2: {\n"
15627                "  [[fallthrough]];\n"
15628                "}\n"
15629                "default: {\n"
15630                "  break;\n"
15631                "}\n"
15632                "}");
15633 
15634   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15635   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15636   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15637   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15638   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15639   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15640   verifyFormat("{\n"
15641                "label1:\n"
15642                "  int x = 0;\n"
15643                "}",
15644                CtorInitializerStyle);
15645   verifyFormat("switch (x) {\n"
15646                "case 1:\n"
15647                "default:\n"
15648                "}",
15649                CtorInitializerStyle);
15650   verifyFormat("switch (allBraces) {\n"
15651                "case 1: {\n"
15652                "  break;\n"
15653                "}\n"
15654                "case 2: {\n"
15655                "  [[fallthrough]];\n"
15656                "}\n"
15657                "default: {\n"
15658                "  break;\n"
15659                "}\n"
15660                "}",
15661                CtorInitializerStyle);
15662   CtorInitializerStyle.BreakConstructorInitializers =
15663       FormatStyle::BCIS_AfterColon;
15664   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15665                "    aaaaaaaaaaaaaaaa(1),\n"
15666                "    bbbbbbbbbbbbbbbb(2) {}",
15667                CtorInitializerStyle);
15668   CtorInitializerStyle.BreakConstructorInitializers =
15669       FormatStyle::BCIS_BeforeComma;
15670   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15671                "    : aaaaaaaaaaaaaaaa(1)\n"
15672                "    , bbbbbbbbbbbbbbbb(2) {}",
15673                CtorInitializerStyle);
15674   CtorInitializerStyle.BreakConstructorInitializers =
15675       FormatStyle::BCIS_BeforeColon;
15676   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15677                "    : aaaaaaaaaaaaaaaa(1),\n"
15678                "      bbbbbbbbbbbbbbbb(2) {}",
15679                CtorInitializerStyle);
15680   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15681   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15682                ": aaaaaaaaaaaaaaaa(1),\n"
15683                "  bbbbbbbbbbbbbbbb(2) {}",
15684                CtorInitializerStyle);
15685 
15686   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15687   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15688   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15689   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15690   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15691   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15692   verifyFormat("{\n"
15693                "label2:\n"
15694                "  int x = 0;\n"
15695                "}",
15696                InheritanceStyle);
15697   verifyFormat("switch (x) {\n"
15698                "case 1:\n"
15699                "default:\n"
15700                "}",
15701                InheritanceStyle);
15702   verifyFormat("switch (allBraces) {\n"
15703                "case 1: {\n"
15704                "  break;\n"
15705                "}\n"
15706                "case 2: {\n"
15707                "  [[fallthrough]];\n"
15708                "}\n"
15709                "default: {\n"
15710                "  break;\n"
15711                "}\n"
15712                "}",
15713                InheritanceStyle);
15714   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15715   verifyFormat("class Foooooooooooooooooooooo\n"
15716                "    : public aaaaaaaaaaaaaaaaaa,\n"
15717                "      public bbbbbbbbbbbbbbbbbb {\n"
15718                "}",
15719                InheritanceStyle);
15720   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15721   verifyFormat("class Foooooooooooooooooooooo:\n"
15722                "    public aaaaaaaaaaaaaaaaaa,\n"
15723                "    public bbbbbbbbbbbbbbbbbb {\n"
15724                "}",
15725                InheritanceStyle);
15726   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15727   verifyFormat("class Foooooooooooooooooooooo\n"
15728                "    : public aaaaaaaaaaaaaaaaaa\n"
15729                "    , public bbbbbbbbbbbbbbbbbb {\n"
15730                "}",
15731                InheritanceStyle);
15732   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15733   verifyFormat("class Foooooooooooooooooooooo\n"
15734                "    : public aaaaaaaaaaaaaaaaaa,\n"
15735                "      public bbbbbbbbbbbbbbbbbb {\n"
15736                "}",
15737                InheritanceStyle);
15738   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15739   verifyFormat("class Foooooooooooooooooooooo\n"
15740                ": public aaaaaaaaaaaaaaaaaa,\n"
15741                "  public bbbbbbbbbbbbbbbbbb {}",
15742                InheritanceStyle);
15743 
15744   FormatStyle ForLoopStyle = getLLVMStyle();
15745   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15746   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15747   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15748   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15749   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15750   verifyFormat("{\n"
15751                "label2:\n"
15752                "  int x = 0;\n"
15753                "}",
15754                ForLoopStyle);
15755   verifyFormat("switch (x) {\n"
15756                "case 1:\n"
15757                "default:\n"
15758                "}",
15759                ForLoopStyle);
15760   verifyFormat("switch (allBraces) {\n"
15761                "case 1: {\n"
15762                "  break;\n"
15763                "}\n"
15764                "case 2: {\n"
15765                "  [[fallthrough]];\n"
15766                "}\n"
15767                "default: {\n"
15768                "  break;\n"
15769                "}\n"
15770                "}",
15771                ForLoopStyle);
15772 
15773   FormatStyle CaseStyle = getLLVMStyle();
15774   CaseStyle.SpaceBeforeCaseColon = true;
15775   verifyFormat("class Foo : public Bar {};", CaseStyle);
15776   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15777   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15778   verifyFormat("int x = a ? b : c;", CaseStyle);
15779   verifyFormat("switch (x) {\n"
15780                "case 1 :\n"
15781                "default :\n"
15782                "}",
15783                CaseStyle);
15784   verifyFormat("switch (allBraces) {\n"
15785                "case 1 : {\n"
15786                "  break;\n"
15787                "}\n"
15788                "case 2 : {\n"
15789                "  [[fallthrough]];\n"
15790                "}\n"
15791                "default : {\n"
15792                "  break;\n"
15793                "}\n"
15794                "}",
15795                CaseStyle);
15796 
15797   FormatStyle NoSpaceStyle = getLLVMStyle();
15798   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15799   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15800   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15801   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15802   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15803   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15804   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15805   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15806   verifyFormat("{\n"
15807                "label3:\n"
15808                "  int x = 0;\n"
15809                "}",
15810                NoSpaceStyle);
15811   verifyFormat("switch (x) {\n"
15812                "case 1:\n"
15813                "default:\n"
15814                "}",
15815                NoSpaceStyle);
15816   verifyFormat("switch (allBraces) {\n"
15817                "case 1: {\n"
15818                "  break;\n"
15819                "}\n"
15820                "case 2: {\n"
15821                "  [[fallthrough]];\n"
15822                "}\n"
15823                "default: {\n"
15824                "  break;\n"
15825                "}\n"
15826                "}",
15827                NoSpaceStyle);
15828 
15829   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15830   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15831   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15832   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15833   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15834   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15835   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15836   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15837   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15838   verifyFormat("{\n"
15839                "label3:\n"
15840                "  int x = 0;\n"
15841                "}",
15842                InvertedSpaceStyle);
15843   verifyFormat("switch (x) {\n"
15844                "case 1 :\n"
15845                "case 2 : {\n"
15846                "  break;\n"
15847                "}\n"
15848                "default :\n"
15849                "  break;\n"
15850                "}",
15851                InvertedSpaceStyle);
15852   verifyFormat("switch (allBraces) {\n"
15853                "case 1 : {\n"
15854                "  break;\n"
15855                "}\n"
15856                "case 2 : {\n"
15857                "  [[fallthrough]];\n"
15858                "}\n"
15859                "default : {\n"
15860                "  break;\n"
15861                "}\n"
15862                "}",
15863                InvertedSpaceStyle);
15864 }
15865 
15866 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15867   FormatStyle Style = getLLVMStyle();
15868 
15869   Style.PointerAlignment = FormatStyle::PAS_Left;
15870   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15871   verifyFormat("void* const* x = NULL;", Style);
15872 
15873 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15874   do {                                                                         \
15875     Style.PointerAlignment = FormatStyle::Pointers;                            \
15876     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15877     verifyFormat(Code, Style);                                                 \
15878   } while (false)
15879 
15880   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15881   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15882   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15883 
15884   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15885   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15886   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15887 
15888   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15889   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15890   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15891 
15892   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15893   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15894   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15895 
15896   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15897   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15898                         SAPQ_Default);
15899   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15900                         SAPQ_Default);
15901 
15902   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15903   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15904                         SAPQ_Before);
15905   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15906                         SAPQ_Before);
15907 
15908   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15909   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15910   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15911                         SAPQ_After);
15912 
15913   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15914   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15915   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15916 
15917 #undef verifyQualifierSpaces
15918 
15919   FormatStyle Spaces = getLLVMStyle();
15920   Spaces.AttributeMacros.push_back("qualified");
15921   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15922   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15923   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15924   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15925   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15926   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15927   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15928   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15929   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15930   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15931   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15932   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15933   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15934 
15935   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15936   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15937   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15938   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15939   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15940   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15941   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15942   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15943   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15944   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15945   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15946   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15947   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15948   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15949   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15950 
15951   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15952   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15953   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15954   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15955   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15956   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15957   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15958   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15959 }
15960 
15961 TEST_F(FormatTest, AlignConsecutiveMacros) {
15962   FormatStyle Style = getLLVMStyle();
15963   Style.AlignConsecutiveAssignments.Enabled = true;
15964   Style.AlignConsecutiveDeclarations.Enabled = true;
15965 
15966   verifyFormat("#define a 3\n"
15967                "#define bbbb 4\n"
15968                "#define ccc (5)",
15969                Style);
15970 
15971   verifyFormat("#define f(x) (x * x)\n"
15972                "#define fff(x, y, z) (x * y + z)\n"
15973                "#define ffff(x, y) (x - y)",
15974                Style);
15975 
15976   verifyFormat("#define foo(x, y) (x + y)\n"
15977                "#define bar (5, 6)(2 + 2)",
15978                Style);
15979 
15980   verifyFormat("#define a 3\n"
15981                "#define bbbb 4\n"
15982                "#define ccc (5)\n"
15983                "#define f(x) (x * x)\n"
15984                "#define fff(x, y, z) (x * y + z)\n"
15985                "#define ffff(x, y) (x - y)",
15986                Style);
15987 
15988   Style.AlignConsecutiveMacros.Enabled = true;
15989   verifyFormat("#define a    3\n"
15990                "#define bbbb 4\n"
15991                "#define ccc  (5)",
15992                Style);
15993 
15994   verifyFormat("#define f(x)         (x * x)\n"
15995                "#define fff(x, y, z) (x * y + z)\n"
15996                "#define ffff(x, y)   (x - y)",
15997                Style);
15998 
15999   verifyFormat("#define foo(x, y) (x + y)\n"
16000                "#define bar       (5, 6)(2 + 2)",
16001                Style);
16002 
16003   verifyFormat("#define a            3\n"
16004                "#define bbbb         4\n"
16005                "#define ccc          (5)\n"
16006                "#define f(x)         (x * x)\n"
16007                "#define fff(x, y, z) (x * y + z)\n"
16008                "#define ffff(x, y)   (x - y)",
16009                Style);
16010 
16011   verifyFormat("#define a         5\n"
16012                "#define foo(x, y) (x + y)\n"
16013                "#define CCC       (6)\n"
16014                "auto lambda = []() {\n"
16015                "  auto  ii = 0;\n"
16016                "  float j  = 0;\n"
16017                "  return 0;\n"
16018                "};\n"
16019                "int   i  = 0;\n"
16020                "float i2 = 0;\n"
16021                "auto  v  = type{\n"
16022                "    i = 1,   //\n"
16023                "    (i = 2), //\n"
16024                "    i = 3    //\n"
16025                "};",
16026                Style);
16027 
16028   Style.AlignConsecutiveMacros.Enabled = false;
16029   Style.ColumnLimit = 20;
16030 
16031   verifyFormat("#define a          \\\n"
16032                "  \"aabbbbbbbbbbbb\"\n"
16033                "#define D          \\\n"
16034                "  \"aabbbbbbbbbbbb\" \\\n"
16035                "  \"ccddeeeeeeeee\"\n"
16036                "#define B          \\\n"
16037                "  \"QQQQQQQQQQQQQ\"  \\\n"
16038                "  \"FFFFFFFFFFFFF\"  \\\n"
16039                "  \"LLLLLLLL\"\n",
16040                Style);
16041 
16042   Style.AlignConsecutiveMacros.Enabled = true;
16043   verifyFormat("#define a          \\\n"
16044                "  \"aabbbbbbbbbbbb\"\n"
16045                "#define D          \\\n"
16046                "  \"aabbbbbbbbbbbb\" \\\n"
16047                "  \"ccddeeeeeeeee\"\n"
16048                "#define B          \\\n"
16049                "  \"QQQQQQQQQQQQQ\"  \\\n"
16050                "  \"FFFFFFFFFFFFF\"  \\\n"
16051                "  \"LLLLLLLL\"\n",
16052                Style);
16053 
16054   // Test across comments
16055   Style.MaxEmptyLinesToKeep = 10;
16056   Style.ReflowComments = false;
16057   Style.AlignConsecutiveMacros.AcrossComments = true;
16058   EXPECT_EQ("#define a    3\n"
16059             "// line comment\n"
16060             "#define bbbb 4\n"
16061             "#define ccc  (5)",
16062             format("#define a 3\n"
16063                    "// line comment\n"
16064                    "#define bbbb 4\n"
16065                    "#define ccc (5)",
16066                    Style));
16067 
16068   EXPECT_EQ("#define a    3\n"
16069             "/* block comment */\n"
16070             "#define bbbb 4\n"
16071             "#define ccc  (5)",
16072             format("#define a  3\n"
16073                    "/* block comment */\n"
16074                    "#define bbbb 4\n"
16075                    "#define ccc (5)",
16076                    Style));
16077 
16078   EXPECT_EQ("#define a    3\n"
16079             "/* multi-line *\n"
16080             " * block comment */\n"
16081             "#define bbbb 4\n"
16082             "#define ccc  (5)",
16083             format("#define a 3\n"
16084                    "/* multi-line *\n"
16085                    " * block comment */\n"
16086                    "#define bbbb 4\n"
16087                    "#define ccc (5)",
16088                    Style));
16089 
16090   EXPECT_EQ("#define a    3\n"
16091             "// multi-line line comment\n"
16092             "//\n"
16093             "#define bbbb 4\n"
16094             "#define ccc  (5)",
16095             format("#define a  3\n"
16096                    "// multi-line line comment\n"
16097                    "//\n"
16098                    "#define bbbb 4\n"
16099                    "#define ccc (5)",
16100                    Style));
16101 
16102   EXPECT_EQ("#define a 3\n"
16103             "// empty lines still break.\n"
16104             "\n"
16105             "#define bbbb 4\n"
16106             "#define ccc  (5)",
16107             format("#define a     3\n"
16108                    "// empty lines still break.\n"
16109                    "\n"
16110                    "#define bbbb     4\n"
16111                    "#define ccc  (5)",
16112                    Style));
16113 
16114   // Test across empty lines
16115   Style.AlignConsecutiveMacros.AcrossComments = false;
16116   Style.AlignConsecutiveMacros.AcrossEmptyLines = true;
16117   EXPECT_EQ("#define a    3\n"
16118             "\n"
16119             "#define bbbb 4\n"
16120             "#define ccc  (5)",
16121             format("#define a 3\n"
16122                    "\n"
16123                    "#define bbbb 4\n"
16124                    "#define ccc (5)",
16125                    Style));
16126 
16127   EXPECT_EQ("#define a    3\n"
16128             "\n"
16129             "\n"
16130             "\n"
16131             "#define bbbb 4\n"
16132             "#define ccc  (5)",
16133             format("#define a        3\n"
16134                    "\n"
16135                    "\n"
16136                    "\n"
16137                    "#define bbbb 4\n"
16138                    "#define ccc (5)",
16139                    Style));
16140 
16141   EXPECT_EQ("#define a 3\n"
16142             "// comments should break alignment\n"
16143             "//\n"
16144             "#define bbbb 4\n"
16145             "#define ccc  (5)",
16146             format("#define a        3\n"
16147                    "// comments should break alignment\n"
16148                    "//\n"
16149                    "#define bbbb 4\n"
16150                    "#define ccc (5)",
16151                    Style));
16152 
16153   // Test across empty lines and comments
16154   Style.AlignConsecutiveMacros.AcrossComments = true;
16155   verifyFormat("#define a    3\n"
16156                "\n"
16157                "// line comment\n"
16158                "#define bbbb 4\n"
16159                "#define ccc  (5)",
16160                Style);
16161 
16162   EXPECT_EQ("#define a    3\n"
16163             "\n"
16164             "\n"
16165             "/* multi-line *\n"
16166             " * block comment */\n"
16167             "\n"
16168             "\n"
16169             "#define bbbb 4\n"
16170             "#define ccc  (5)",
16171             format("#define a 3\n"
16172                    "\n"
16173                    "\n"
16174                    "/* multi-line *\n"
16175                    " * block comment */\n"
16176                    "\n"
16177                    "\n"
16178                    "#define bbbb 4\n"
16179                    "#define ccc (5)",
16180                    Style));
16181 
16182   EXPECT_EQ("#define a    3\n"
16183             "\n"
16184             "\n"
16185             "/* multi-line *\n"
16186             " * block comment */\n"
16187             "\n"
16188             "\n"
16189             "#define bbbb 4\n"
16190             "#define ccc  (5)",
16191             format("#define a 3\n"
16192                    "\n"
16193                    "\n"
16194                    "/* multi-line *\n"
16195                    " * block comment */\n"
16196                    "\n"
16197                    "\n"
16198                    "#define bbbb 4\n"
16199                    "#define ccc       (5)",
16200                    Style));
16201 }
16202 
16203 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16204   FormatStyle Alignment = getLLVMStyle();
16205   Alignment.AlignConsecutiveMacros.Enabled = true;
16206   Alignment.AlignConsecutiveAssignments.Enabled = true;
16207   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16208 
16209   Alignment.MaxEmptyLinesToKeep = 10;
16210   /* Test alignment across empty lines */
16211   EXPECT_EQ("int a           = 5;\n"
16212             "\n"
16213             "int oneTwoThree = 123;",
16214             format("int a       = 5;\n"
16215                    "\n"
16216                    "int oneTwoThree= 123;",
16217                    Alignment));
16218   EXPECT_EQ("int a           = 5;\n"
16219             "int one         = 1;\n"
16220             "\n"
16221             "int oneTwoThree = 123;",
16222             format("int a = 5;\n"
16223                    "int one = 1;\n"
16224                    "\n"
16225                    "int oneTwoThree = 123;",
16226                    Alignment));
16227   EXPECT_EQ("int a           = 5;\n"
16228             "int one         = 1;\n"
16229             "\n"
16230             "int oneTwoThree = 123;\n"
16231             "int oneTwo      = 12;",
16232             format("int a = 5;\n"
16233                    "int one = 1;\n"
16234                    "\n"
16235                    "int oneTwoThree = 123;\n"
16236                    "int oneTwo = 12;",
16237                    Alignment));
16238 
16239   /* Test across comments */
16240   EXPECT_EQ("int a = 5;\n"
16241             "/* block comment */\n"
16242             "int oneTwoThree = 123;",
16243             format("int a = 5;\n"
16244                    "/* block comment */\n"
16245                    "int oneTwoThree=123;",
16246                    Alignment));
16247 
16248   EXPECT_EQ("int a = 5;\n"
16249             "// line comment\n"
16250             "int oneTwoThree = 123;",
16251             format("int a = 5;\n"
16252                    "// line comment\n"
16253                    "int oneTwoThree=123;",
16254                    Alignment));
16255 
16256   /* Test across comments and newlines */
16257   EXPECT_EQ("int a = 5;\n"
16258             "\n"
16259             "/* block comment */\n"
16260             "int oneTwoThree = 123;",
16261             format("int a = 5;\n"
16262                    "\n"
16263                    "/* block comment */\n"
16264                    "int oneTwoThree=123;",
16265                    Alignment));
16266 
16267   EXPECT_EQ("int a = 5;\n"
16268             "\n"
16269             "// line comment\n"
16270             "int oneTwoThree = 123;",
16271             format("int a = 5;\n"
16272                    "\n"
16273                    "// line comment\n"
16274                    "int oneTwoThree=123;",
16275                    Alignment));
16276 }
16277 
16278 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16279   FormatStyle Alignment = getLLVMStyle();
16280   Alignment.AlignConsecutiveDeclarations.Enabled = true;
16281   Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true;
16282   Alignment.AlignConsecutiveDeclarations.AcrossComments = true;
16283 
16284   Alignment.MaxEmptyLinesToKeep = 10;
16285   /* Test alignment across empty lines */
16286   EXPECT_EQ("int         a = 5;\n"
16287             "\n"
16288             "float const oneTwoThree = 123;",
16289             format("int a = 5;\n"
16290                    "\n"
16291                    "float const oneTwoThree = 123;",
16292                    Alignment));
16293   EXPECT_EQ("int         a = 5;\n"
16294             "float const one = 1;\n"
16295             "\n"
16296             "int         oneTwoThree = 123;",
16297             format("int a = 5;\n"
16298                    "float const one = 1;\n"
16299                    "\n"
16300                    "int oneTwoThree = 123;",
16301                    Alignment));
16302 
16303   /* Test across comments */
16304   EXPECT_EQ("float const a = 5;\n"
16305             "/* block comment */\n"
16306             "int         oneTwoThree = 123;",
16307             format("float const a = 5;\n"
16308                    "/* block comment */\n"
16309                    "int oneTwoThree=123;",
16310                    Alignment));
16311 
16312   EXPECT_EQ("float const a = 5;\n"
16313             "// line comment\n"
16314             "int         oneTwoThree = 123;",
16315             format("float const a = 5;\n"
16316                    "// line comment\n"
16317                    "int oneTwoThree=123;",
16318                    Alignment));
16319 
16320   /* Test across comments and newlines */
16321   EXPECT_EQ("float const a = 5;\n"
16322             "\n"
16323             "/* block comment */\n"
16324             "int         oneTwoThree = 123;",
16325             format("float const a = 5;\n"
16326                    "\n"
16327                    "/* block comment */\n"
16328                    "int         oneTwoThree=123;",
16329                    Alignment));
16330 
16331   EXPECT_EQ("float const a = 5;\n"
16332             "\n"
16333             "// line comment\n"
16334             "int         oneTwoThree = 123;",
16335             format("float const a = 5;\n"
16336                    "\n"
16337                    "// line comment\n"
16338                    "int oneTwoThree=123;",
16339                    Alignment));
16340 }
16341 
16342 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16343   FormatStyle Alignment = getLLVMStyle();
16344   Alignment.AlignConsecutiveBitFields.Enabled = true;
16345   Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true;
16346   Alignment.AlignConsecutiveBitFields.AcrossComments = true;
16347 
16348   Alignment.MaxEmptyLinesToKeep = 10;
16349   /* Test alignment across empty lines */
16350   EXPECT_EQ("int a            : 5;\n"
16351             "\n"
16352             "int longbitfield : 6;",
16353             format("int a : 5;\n"
16354                    "\n"
16355                    "int longbitfield : 6;",
16356                    Alignment));
16357   EXPECT_EQ("int a            : 5;\n"
16358             "int one          : 1;\n"
16359             "\n"
16360             "int longbitfield : 6;",
16361             format("int a : 5;\n"
16362                    "int one : 1;\n"
16363                    "\n"
16364                    "int longbitfield : 6;",
16365                    Alignment));
16366 
16367   /* Test across comments */
16368   EXPECT_EQ("int a            : 5;\n"
16369             "/* block comment */\n"
16370             "int longbitfield : 6;",
16371             format("int a : 5;\n"
16372                    "/* block comment */\n"
16373                    "int longbitfield : 6;",
16374                    Alignment));
16375   EXPECT_EQ("int a            : 5;\n"
16376             "int one          : 1;\n"
16377             "// line comment\n"
16378             "int longbitfield : 6;",
16379             format("int a : 5;\n"
16380                    "int one : 1;\n"
16381                    "// line comment\n"
16382                    "int longbitfield : 6;",
16383                    Alignment));
16384 
16385   /* Test across comments and newlines */
16386   EXPECT_EQ("int a            : 5;\n"
16387             "/* block comment */\n"
16388             "\n"
16389             "int longbitfield : 6;",
16390             format("int a : 5;\n"
16391                    "/* block comment */\n"
16392                    "\n"
16393                    "int longbitfield : 6;",
16394                    Alignment));
16395   EXPECT_EQ("int a            : 5;\n"
16396             "int one          : 1;\n"
16397             "\n"
16398             "// line comment\n"
16399             "\n"
16400             "int longbitfield : 6;",
16401             format("int a : 5;\n"
16402                    "int one : 1;\n"
16403                    "\n"
16404                    "// line comment \n"
16405                    "\n"
16406                    "int longbitfield : 6;",
16407                    Alignment));
16408 }
16409 
16410 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16411   FormatStyle Alignment = getLLVMStyle();
16412   Alignment.AlignConsecutiveMacros.Enabled = true;
16413   Alignment.AlignConsecutiveAssignments.Enabled = true;
16414   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16415 
16416   Alignment.MaxEmptyLinesToKeep = 10;
16417   /* Test alignment across empty lines */
16418   EXPECT_EQ("int a = 5;\n"
16419             "\n"
16420             "int oneTwoThree = 123;",
16421             format("int a       = 5;\n"
16422                    "\n"
16423                    "int oneTwoThree= 123;",
16424                    Alignment));
16425   EXPECT_EQ("int a   = 5;\n"
16426             "int one = 1;\n"
16427             "\n"
16428             "int oneTwoThree = 123;",
16429             format("int a = 5;\n"
16430                    "int one = 1;\n"
16431                    "\n"
16432                    "int oneTwoThree = 123;",
16433                    Alignment));
16434 
16435   /* Test across comments */
16436   EXPECT_EQ("int a           = 5;\n"
16437             "/* block comment */\n"
16438             "int oneTwoThree = 123;",
16439             format("int a = 5;\n"
16440                    "/* block comment */\n"
16441                    "int oneTwoThree=123;",
16442                    Alignment));
16443 
16444   EXPECT_EQ("int a           = 5;\n"
16445             "// line comment\n"
16446             "int oneTwoThree = 123;",
16447             format("int a = 5;\n"
16448                    "// line comment\n"
16449                    "int oneTwoThree=123;",
16450                    Alignment));
16451 
16452   EXPECT_EQ("int a           = 5;\n"
16453             "/*\n"
16454             " * multi-line block comment\n"
16455             " */\n"
16456             "int oneTwoThree = 123;",
16457             format("int a = 5;\n"
16458                    "/*\n"
16459                    " * multi-line block comment\n"
16460                    " */\n"
16461                    "int oneTwoThree=123;",
16462                    Alignment));
16463 
16464   EXPECT_EQ("int a           = 5;\n"
16465             "//\n"
16466             "// multi-line line comment\n"
16467             "//\n"
16468             "int oneTwoThree = 123;",
16469             format("int a = 5;\n"
16470                    "//\n"
16471                    "// multi-line line comment\n"
16472                    "//\n"
16473                    "int oneTwoThree=123;",
16474                    Alignment));
16475 
16476   /* Test across comments and newlines */
16477   EXPECT_EQ("int a = 5;\n"
16478             "\n"
16479             "/* block comment */\n"
16480             "int oneTwoThree = 123;",
16481             format("int a = 5;\n"
16482                    "\n"
16483                    "/* block comment */\n"
16484                    "int oneTwoThree=123;",
16485                    Alignment));
16486 
16487   EXPECT_EQ("int a = 5;\n"
16488             "\n"
16489             "// line comment\n"
16490             "int oneTwoThree = 123;",
16491             format("int a = 5;\n"
16492                    "\n"
16493                    "// line comment\n"
16494                    "int oneTwoThree=123;",
16495                    Alignment));
16496 }
16497 
16498 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16499   FormatStyle Alignment = getLLVMStyle();
16500   Alignment.AlignConsecutiveMacros.Enabled = true;
16501   Alignment.AlignConsecutiveAssignments.Enabled = true;
16502   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16503   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16504   verifyFormat("int a           = 5;\n"
16505                "int oneTwoThree = 123;",
16506                Alignment);
16507   verifyFormat("int a           = method();\n"
16508                "int oneTwoThree = 133;",
16509                Alignment);
16510   verifyFormat("a &= 5;\n"
16511                "bcd *= 5;\n"
16512                "ghtyf += 5;\n"
16513                "dvfvdb -= 5;\n"
16514                "a /= 5;\n"
16515                "vdsvsv %= 5;\n"
16516                "sfdbddfbdfbb ^= 5;\n"
16517                "dvsdsv |= 5;\n"
16518                "int dsvvdvsdvvv = 123;",
16519                Alignment);
16520   verifyFormat("int i = 1, j = 10;\n"
16521                "something = 2000;",
16522                Alignment);
16523   verifyFormat("something = 2000;\n"
16524                "int i = 1, j = 10;\n",
16525                Alignment);
16526   verifyFormat("something = 2000;\n"
16527                "another   = 911;\n"
16528                "int i = 1, j = 10;\n"
16529                "oneMore = 1;\n"
16530                "i       = 2;",
16531                Alignment);
16532   verifyFormat("int a   = 5;\n"
16533                "int one = 1;\n"
16534                "method();\n"
16535                "int oneTwoThree = 123;\n"
16536                "int oneTwo      = 12;",
16537                Alignment);
16538   verifyFormat("int oneTwoThree = 123;\n"
16539                "int oneTwo      = 12;\n"
16540                "method();\n",
16541                Alignment);
16542   verifyFormat("int oneTwoThree = 123; // comment\n"
16543                "int oneTwo      = 12;  // comment",
16544                Alignment);
16545 
16546   // Bug 25167
16547   /* Uncomment when fixed
16548     verifyFormat("#if A\n"
16549                  "#else\n"
16550                  "int aaaaaaaa = 12;\n"
16551                  "#endif\n"
16552                  "#if B\n"
16553                  "#else\n"
16554                  "int a = 12;\n"
16555                  "#endif\n",
16556                  Alignment);
16557     verifyFormat("enum foo {\n"
16558                  "#if A\n"
16559                  "#else\n"
16560                  "  aaaaaaaa = 12;\n"
16561                  "#endif\n"
16562                  "#if B\n"
16563                  "#else\n"
16564                  "  a = 12;\n"
16565                  "#endif\n"
16566                  "};\n",
16567                  Alignment);
16568   */
16569 
16570   Alignment.MaxEmptyLinesToKeep = 10;
16571   /* Test alignment across empty lines */
16572   EXPECT_EQ("int a           = 5;\n"
16573             "\n"
16574             "int oneTwoThree = 123;",
16575             format("int a       = 5;\n"
16576                    "\n"
16577                    "int oneTwoThree= 123;",
16578                    Alignment));
16579   EXPECT_EQ("int a           = 5;\n"
16580             "int one         = 1;\n"
16581             "\n"
16582             "int oneTwoThree = 123;",
16583             format("int a = 5;\n"
16584                    "int one = 1;\n"
16585                    "\n"
16586                    "int oneTwoThree = 123;",
16587                    Alignment));
16588   EXPECT_EQ("int a           = 5;\n"
16589             "int one         = 1;\n"
16590             "\n"
16591             "int oneTwoThree = 123;\n"
16592             "int oneTwo      = 12;",
16593             format("int a = 5;\n"
16594                    "int one = 1;\n"
16595                    "\n"
16596                    "int oneTwoThree = 123;\n"
16597                    "int oneTwo = 12;",
16598                    Alignment));
16599 
16600   /* Test across comments */
16601   EXPECT_EQ("int a           = 5;\n"
16602             "/* block comment */\n"
16603             "int oneTwoThree = 123;",
16604             format("int a = 5;\n"
16605                    "/* block comment */\n"
16606                    "int oneTwoThree=123;",
16607                    Alignment));
16608 
16609   EXPECT_EQ("int a           = 5;\n"
16610             "// line comment\n"
16611             "int oneTwoThree = 123;",
16612             format("int a = 5;\n"
16613                    "// line comment\n"
16614                    "int oneTwoThree=123;",
16615                    Alignment));
16616 
16617   /* Test across comments and newlines */
16618   EXPECT_EQ("int a           = 5;\n"
16619             "\n"
16620             "/* block comment */\n"
16621             "int oneTwoThree = 123;",
16622             format("int a = 5;\n"
16623                    "\n"
16624                    "/* block comment */\n"
16625                    "int oneTwoThree=123;",
16626                    Alignment));
16627 
16628   EXPECT_EQ("int a           = 5;\n"
16629             "\n"
16630             "// line comment\n"
16631             "int oneTwoThree = 123;",
16632             format("int a = 5;\n"
16633                    "\n"
16634                    "// line comment\n"
16635                    "int oneTwoThree=123;",
16636                    Alignment));
16637 
16638   EXPECT_EQ("int a           = 5;\n"
16639             "//\n"
16640             "// multi-line line comment\n"
16641             "//\n"
16642             "int oneTwoThree = 123;",
16643             format("int a = 5;\n"
16644                    "//\n"
16645                    "// multi-line line comment\n"
16646                    "//\n"
16647                    "int oneTwoThree=123;",
16648                    Alignment));
16649 
16650   EXPECT_EQ("int a           = 5;\n"
16651             "/*\n"
16652             " *  multi-line block comment\n"
16653             " */\n"
16654             "int oneTwoThree = 123;",
16655             format("int a = 5;\n"
16656                    "/*\n"
16657                    " *  multi-line block comment\n"
16658                    " */\n"
16659                    "int oneTwoThree=123;",
16660                    Alignment));
16661 
16662   EXPECT_EQ("int a           = 5;\n"
16663             "\n"
16664             "/* block comment */\n"
16665             "\n"
16666             "\n"
16667             "\n"
16668             "int oneTwoThree = 123;",
16669             format("int a = 5;\n"
16670                    "\n"
16671                    "/* block comment */\n"
16672                    "\n"
16673                    "\n"
16674                    "\n"
16675                    "int oneTwoThree=123;",
16676                    Alignment));
16677 
16678   EXPECT_EQ("int a           = 5;\n"
16679             "\n"
16680             "// line comment\n"
16681             "\n"
16682             "\n"
16683             "\n"
16684             "int oneTwoThree = 123;",
16685             format("int a = 5;\n"
16686                    "\n"
16687                    "// line comment\n"
16688                    "\n"
16689                    "\n"
16690                    "\n"
16691                    "int oneTwoThree=123;",
16692                    Alignment));
16693 
16694   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16695   verifyFormat("#define A \\\n"
16696                "  int aaaa       = 12; \\\n"
16697                "  int b          = 23; \\\n"
16698                "  int ccc        = 234; \\\n"
16699                "  int dddddddddd = 2345;",
16700                Alignment);
16701   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16702   verifyFormat("#define A               \\\n"
16703                "  int aaaa       = 12;  \\\n"
16704                "  int b          = 23;  \\\n"
16705                "  int ccc        = 234; \\\n"
16706                "  int dddddddddd = 2345;",
16707                Alignment);
16708   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16709   verifyFormat("#define A                                                      "
16710                "                \\\n"
16711                "  int aaaa       = 12;                                         "
16712                "                \\\n"
16713                "  int b          = 23;                                         "
16714                "                \\\n"
16715                "  int ccc        = 234;                                        "
16716                "                \\\n"
16717                "  int dddddddddd = 2345;",
16718                Alignment);
16719   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16720                "k = 4, int l = 5,\n"
16721                "                  int m = 6) {\n"
16722                "  int j      = 10;\n"
16723                "  otherThing = 1;\n"
16724                "}",
16725                Alignment);
16726   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16727                "  int i   = 1;\n"
16728                "  int j   = 2;\n"
16729                "  int big = 10000;\n"
16730                "}",
16731                Alignment);
16732   verifyFormat("class C {\n"
16733                "public:\n"
16734                "  int i            = 1;\n"
16735                "  virtual void f() = 0;\n"
16736                "};",
16737                Alignment);
16738   verifyFormat("int i = 1;\n"
16739                "if (SomeType t = getSomething()) {\n"
16740                "}\n"
16741                "int j   = 2;\n"
16742                "int big = 10000;",
16743                Alignment);
16744   verifyFormat("int j = 7;\n"
16745                "for (int k = 0; k < N; ++k) {\n"
16746                "}\n"
16747                "int j   = 2;\n"
16748                "int big = 10000;\n"
16749                "}",
16750                Alignment);
16751   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16752   verifyFormat("int i = 1;\n"
16753                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16754                "    = someLooooooooooooooooongFunction();\n"
16755                "int j = 2;",
16756                Alignment);
16757   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16758   verifyFormat("int i = 1;\n"
16759                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16760                "    someLooooooooooooooooongFunction();\n"
16761                "int j = 2;",
16762                Alignment);
16763 
16764   verifyFormat("auto lambda = []() {\n"
16765                "  auto i = 0;\n"
16766                "  return 0;\n"
16767                "};\n"
16768                "int i  = 0;\n"
16769                "auto v = type{\n"
16770                "    i = 1,   //\n"
16771                "    (i = 2), //\n"
16772                "    i = 3    //\n"
16773                "};",
16774                Alignment);
16775 
16776   verifyFormat(
16777       "int i      = 1;\n"
16778       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16779       "                          loooooooooooooooooooooongParameterB);\n"
16780       "int j      = 2;",
16781       Alignment);
16782 
16783   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16784                "          typename B   = very_long_type_name_1,\n"
16785                "          typename T_2 = very_long_type_name_2>\n"
16786                "auto foo() {}\n",
16787                Alignment);
16788   verifyFormat("int a, b = 1;\n"
16789                "int c  = 2;\n"
16790                "int dd = 3;\n",
16791                Alignment);
16792   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16793                "float b[1][] = {{3.f}};\n",
16794                Alignment);
16795   verifyFormat("for (int i = 0; i < 1; i++)\n"
16796                "  int x = 1;\n",
16797                Alignment);
16798   verifyFormat("for (i = 0; i < 1; i++)\n"
16799                "  x = 1;\n"
16800                "y = 1;\n",
16801                Alignment);
16802 
16803   Alignment.ReflowComments = true;
16804   Alignment.ColumnLimit = 50;
16805   EXPECT_EQ("int x   = 0;\n"
16806             "int yy  = 1; /// specificlennospace\n"
16807             "int zzz = 2;\n",
16808             format("int x   = 0;\n"
16809                    "int yy  = 1; ///specificlennospace\n"
16810                    "int zzz = 2;\n",
16811                    Alignment));
16812 }
16813 
16814 TEST_F(FormatTest, AlignCompoundAssignments) {
16815   FormatStyle Alignment = getLLVMStyle();
16816   Alignment.AlignConsecutiveAssignments.Enabled = true;
16817   Alignment.AlignConsecutiveAssignments.AlignCompound = true;
16818   Alignment.AlignConsecutiveAssignments.PadOperators = false;
16819   verifyFormat("sfdbddfbdfbb    = 5;\n"
16820                "dvsdsv          = 5;\n"
16821                "int dsvvdvsdvvv = 123;",
16822                Alignment);
16823   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16824                "dvsdsv         |= 5;\n"
16825                "int dsvvdvsdvvv = 123;",
16826                Alignment);
16827   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
16828                "dvsdsv        <<= 5;\n"
16829                "int dsvvdvsdvvv = 123;",
16830                Alignment);
16831   // Test that `<=` is not treated as a compound assignment.
16832   verifyFormat("aa &= 5;\n"
16833                "b <= 10;\n"
16834                "c = 15;",
16835                Alignment);
16836   Alignment.AlignConsecutiveAssignments.PadOperators = true;
16837   verifyFormat("sfdbddfbdfbb    = 5;\n"
16838                "dvsdsv          = 5;\n"
16839                "int dsvvdvsdvvv = 123;",
16840                Alignment);
16841   verifyFormat("sfdbddfbdfbb    ^= 5;\n"
16842                "dvsdsv          |= 5;\n"
16843                "int dsvvdvsdvvv  = 123;",
16844                Alignment);
16845   verifyFormat("sfdbddfbdfbb     ^= 5;\n"
16846                "dvsdsv          <<= 5;\n"
16847                "int dsvvdvsdvvv   = 123;",
16848                Alignment);
16849   EXPECT_EQ("a   += 5;\n"
16850             "one  = 1;\n"
16851             "\n"
16852             "oneTwoThree = 123;\n",
16853             format("a += 5;\n"
16854                    "one = 1;\n"
16855                    "\n"
16856                    "oneTwoThree = 123;\n",
16857                    Alignment));
16858   EXPECT_EQ("a   += 5;\n"
16859             "one  = 1;\n"
16860             "//\n"
16861             "oneTwoThree = 123;\n",
16862             format("a += 5;\n"
16863                    "one = 1;\n"
16864                    "//\n"
16865                    "oneTwoThree = 123;\n",
16866                    Alignment));
16867   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16868   EXPECT_EQ("a           += 5;\n"
16869             "one          = 1;\n"
16870             "\n"
16871             "oneTwoThree  = 123;\n",
16872             format("a += 5;\n"
16873                    "one = 1;\n"
16874                    "\n"
16875                    "oneTwoThree = 123;\n",
16876                    Alignment));
16877   EXPECT_EQ("a   += 5;\n"
16878             "one  = 1;\n"
16879             "//\n"
16880             "oneTwoThree = 123;\n",
16881             format("a += 5;\n"
16882                    "one = 1;\n"
16883                    "//\n"
16884                    "oneTwoThree = 123;\n",
16885                    Alignment));
16886   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false;
16887   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16888   EXPECT_EQ("a   += 5;\n"
16889             "one  = 1;\n"
16890             "\n"
16891             "oneTwoThree = 123;\n",
16892             format("a += 5;\n"
16893                    "one = 1;\n"
16894                    "\n"
16895                    "oneTwoThree = 123;\n",
16896                    Alignment));
16897   EXPECT_EQ("a           += 5;\n"
16898             "one          = 1;\n"
16899             "//\n"
16900             "oneTwoThree  = 123;\n",
16901             format("a += 5;\n"
16902                    "one = 1;\n"
16903                    "//\n"
16904                    "oneTwoThree = 123;\n",
16905                    Alignment));
16906   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16907   EXPECT_EQ("a            += 5;\n"
16908             "one         >>= 1;\n"
16909             "\n"
16910             "oneTwoThree   = 123;\n",
16911             format("a += 5;\n"
16912                    "one >>= 1;\n"
16913                    "\n"
16914                    "oneTwoThree = 123;\n",
16915                    Alignment));
16916   EXPECT_EQ("a            += 5;\n"
16917             "one           = 1;\n"
16918             "//\n"
16919             "oneTwoThree <<= 123;\n",
16920             format("a += 5;\n"
16921                    "one = 1;\n"
16922                    "//\n"
16923                    "oneTwoThree <<= 123;\n",
16924                    Alignment));
16925 }
16926 
16927 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16928   FormatStyle Alignment = getLLVMStyle();
16929   Alignment.AlignConsecutiveMacros.Enabled = true;
16930   verifyFormat("int a = 5;\n"
16931                "int oneTwoThree = 123;",
16932                Alignment);
16933   verifyFormat("int a = 5;\n"
16934                "int oneTwoThree = 123;",
16935                Alignment);
16936 
16937   Alignment.AlignConsecutiveAssignments.Enabled = true;
16938   verifyFormat("int a           = 5;\n"
16939                "int oneTwoThree = 123;",
16940                Alignment);
16941   verifyFormat("int a           = method();\n"
16942                "int oneTwoThree = 133;",
16943                Alignment);
16944   verifyFormat("aa <= 5;\n"
16945                "a &= 5;\n"
16946                "bcd *= 5;\n"
16947                "ghtyf += 5;\n"
16948                "dvfvdb -= 5;\n"
16949                "a /= 5;\n"
16950                "vdsvsv %= 5;\n"
16951                "sfdbddfbdfbb ^= 5;\n"
16952                "dvsdsv |= 5;\n"
16953                "int dsvvdvsdvvv = 123;",
16954                Alignment);
16955   verifyFormat("int i = 1, j = 10;\n"
16956                "something = 2000;",
16957                Alignment);
16958   verifyFormat("something = 2000;\n"
16959                "int i = 1, j = 10;\n",
16960                Alignment);
16961   verifyFormat("something = 2000;\n"
16962                "another   = 911;\n"
16963                "int i = 1, j = 10;\n"
16964                "oneMore = 1;\n"
16965                "i       = 2;",
16966                Alignment);
16967   verifyFormat("int a   = 5;\n"
16968                "int one = 1;\n"
16969                "method();\n"
16970                "int oneTwoThree = 123;\n"
16971                "int oneTwo      = 12;",
16972                Alignment);
16973   verifyFormat("int oneTwoThree = 123;\n"
16974                "int oneTwo      = 12;\n"
16975                "method();\n",
16976                Alignment);
16977   verifyFormat("int oneTwoThree = 123; // comment\n"
16978                "int oneTwo      = 12;  // comment",
16979                Alignment);
16980   verifyFormat("int f()         = default;\n"
16981                "int &operator() = default;\n"
16982                "int &operator=() {",
16983                Alignment);
16984   verifyFormat("int f()         = delete;\n"
16985                "int &operator() = delete;\n"
16986                "int &operator=() {",
16987                Alignment);
16988   verifyFormat("int f()         = default; // comment\n"
16989                "int &operator() = default; // comment\n"
16990                "int &operator=() {",
16991                Alignment);
16992   verifyFormat("int f()         = default;\n"
16993                "int &operator() = default;\n"
16994                "int &operator==() {",
16995                Alignment);
16996   verifyFormat("int f()         = default;\n"
16997                "int &operator() = default;\n"
16998                "int &operator<=() {",
16999                Alignment);
17000   verifyFormat("int f()         = default;\n"
17001                "int &operator() = default;\n"
17002                "int &operator!=() {",
17003                Alignment);
17004   verifyFormat("int f()         = default;\n"
17005                "int &operator() = default;\n"
17006                "int &operator=();",
17007                Alignment);
17008   verifyFormat("int f()         = delete;\n"
17009                "int &operator() = delete;\n"
17010                "int &operator=();",
17011                Alignment);
17012   verifyFormat("/* long long padding */ int f() = default;\n"
17013                "int &operator()                 = default;\n"
17014                "int &operator/**/ =();",
17015                Alignment);
17016   // https://llvm.org/PR33697
17017   FormatStyle AlignmentWithPenalty = getLLVMStyle();
17018   AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true;
17019   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
17020   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
17021                "  void f() = delete;\n"
17022                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
17023                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
17024                "};\n",
17025                AlignmentWithPenalty);
17026 
17027   // Bug 25167
17028   /* Uncomment when fixed
17029     verifyFormat("#if A\n"
17030                  "#else\n"
17031                  "int aaaaaaaa = 12;\n"
17032                  "#endif\n"
17033                  "#if B\n"
17034                  "#else\n"
17035                  "int a = 12;\n"
17036                  "#endif\n",
17037                  Alignment);
17038     verifyFormat("enum foo {\n"
17039                  "#if A\n"
17040                  "#else\n"
17041                  "  aaaaaaaa = 12;\n"
17042                  "#endif\n"
17043                  "#if B\n"
17044                  "#else\n"
17045                  "  a = 12;\n"
17046                  "#endif\n"
17047                  "};\n",
17048                  Alignment);
17049   */
17050 
17051   EXPECT_EQ("int a = 5;\n"
17052             "\n"
17053             "int oneTwoThree = 123;",
17054             format("int a       = 5;\n"
17055                    "\n"
17056                    "int oneTwoThree= 123;",
17057                    Alignment));
17058   EXPECT_EQ("int a   = 5;\n"
17059             "int one = 1;\n"
17060             "\n"
17061             "int oneTwoThree = 123;",
17062             format("int a = 5;\n"
17063                    "int one = 1;\n"
17064                    "\n"
17065                    "int oneTwoThree = 123;",
17066                    Alignment));
17067   EXPECT_EQ("int a   = 5;\n"
17068             "int one = 1;\n"
17069             "\n"
17070             "int oneTwoThree = 123;\n"
17071             "int oneTwo      = 12;",
17072             format("int a = 5;\n"
17073                    "int one = 1;\n"
17074                    "\n"
17075                    "int oneTwoThree = 123;\n"
17076                    "int oneTwo = 12;",
17077                    Alignment));
17078   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17079   verifyFormat("#define A \\\n"
17080                "  int aaaa       = 12; \\\n"
17081                "  int b          = 23; \\\n"
17082                "  int ccc        = 234; \\\n"
17083                "  int dddddddddd = 2345;",
17084                Alignment);
17085   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17086   verifyFormat("#define A               \\\n"
17087                "  int aaaa       = 12;  \\\n"
17088                "  int b          = 23;  \\\n"
17089                "  int ccc        = 234; \\\n"
17090                "  int dddddddddd = 2345;",
17091                Alignment);
17092   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17093   verifyFormat("#define A                                                      "
17094                "                \\\n"
17095                "  int aaaa       = 12;                                         "
17096                "                \\\n"
17097                "  int b          = 23;                                         "
17098                "                \\\n"
17099                "  int ccc        = 234;                                        "
17100                "                \\\n"
17101                "  int dddddddddd = 2345;",
17102                Alignment);
17103   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17104                "k = 4, int l = 5,\n"
17105                "                  int m = 6) {\n"
17106                "  int j      = 10;\n"
17107                "  otherThing = 1;\n"
17108                "}",
17109                Alignment);
17110   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17111                "  int i   = 1;\n"
17112                "  int j   = 2;\n"
17113                "  int big = 10000;\n"
17114                "}",
17115                Alignment);
17116   verifyFormat("class C {\n"
17117                "public:\n"
17118                "  int i            = 1;\n"
17119                "  virtual void f() = 0;\n"
17120                "};",
17121                Alignment);
17122   verifyFormat("int i = 1;\n"
17123                "if (SomeType t = getSomething()) {\n"
17124                "}\n"
17125                "int j   = 2;\n"
17126                "int big = 10000;",
17127                Alignment);
17128   verifyFormat("int j = 7;\n"
17129                "for (int k = 0; k < N; ++k) {\n"
17130                "}\n"
17131                "int j   = 2;\n"
17132                "int big = 10000;\n"
17133                "}",
17134                Alignment);
17135   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17136   verifyFormat("int i = 1;\n"
17137                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17138                "    = someLooooooooooooooooongFunction();\n"
17139                "int j = 2;",
17140                Alignment);
17141   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17142   verifyFormat("int i = 1;\n"
17143                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17144                "    someLooooooooooooooooongFunction();\n"
17145                "int j = 2;",
17146                Alignment);
17147 
17148   verifyFormat("auto lambda = []() {\n"
17149                "  auto i = 0;\n"
17150                "  return 0;\n"
17151                "};\n"
17152                "int i  = 0;\n"
17153                "auto v = type{\n"
17154                "    i = 1,   //\n"
17155                "    (i = 2), //\n"
17156                "    i = 3    //\n"
17157                "};",
17158                Alignment);
17159 
17160   verifyFormat(
17161       "int i      = 1;\n"
17162       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17163       "                          loooooooooooooooooooooongParameterB);\n"
17164       "int j      = 2;",
17165       Alignment);
17166 
17167   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17168                "          typename B   = very_long_type_name_1,\n"
17169                "          typename T_2 = very_long_type_name_2>\n"
17170                "auto foo() {}\n",
17171                Alignment);
17172   verifyFormat("int a, b = 1;\n"
17173                "int c  = 2;\n"
17174                "int dd = 3;\n",
17175                Alignment);
17176   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17177                "float b[1][] = {{3.f}};\n",
17178                Alignment);
17179   verifyFormat("for (int i = 0; i < 1; i++)\n"
17180                "  int x = 1;\n",
17181                Alignment);
17182   verifyFormat("for (i = 0; i < 1; i++)\n"
17183                "  x = 1;\n"
17184                "y = 1;\n",
17185                Alignment);
17186 
17187   EXPECT_EQ(Alignment.ReflowComments, true);
17188   Alignment.ColumnLimit = 50;
17189   EXPECT_EQ("int x   = 0;\n"
17190             "int yy  = 1; /// specificlennospace\n"
17191             "int zzz = 2;\n",
17192             format("int x   = 0;\n"
17193                    "int yy  = 1; ///specificlennospace\n"
17194                    "int zzz = 2;\n",
17195                    Alignment));
17196 
17197   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17198                "auto b                     = [] {\n"
17199                "  f();\n"
17200                "  return;\n"
17201                "};",
17202                Alignment);
17203   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17204                "auto b                     = g([] {\n"
17205                "  f();\n"
17206                "  return;\n"
17207                "});",
17208                Alignment);
17209   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17210                "auto b                     = g(param, [] {\n"
17211                "  f();\n"
17212                "  return;\n"
17213                "});",
17214                Alignment);
17215   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17216                "auto b                     = [] {\n"
17217                "  if (condition) {\n"
17218                "    return;\n"
17219                "  }\n"
17220                "};",
17221                Alignment);
17222 
17223   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17224                "           ccc ? aaaaa : bbbbb,\n"
17225                "           dddddddddddddddddddddddddd);",
17226                Alignment);
17227   // FIXME: https://llvm.org/PR53497
17228   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
17229   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17230   //              "    ccc ? aaaaa : bbbbb,\n"
17231   //              "    dddddddddddddddddddddddddd);",
17232   //              Alignment);
17233 }
17234 
17235 TEST_F(FormatTest, AlignConsecutiveBitFields) {
17236   FormatStyle Alignment = getLLVMStyle();
17237   Alignment.AlignConsecutiveBitFields.Enabled = true;
17238   verifyFormat("int const a     : 5;\n"
17239                "int oneTwoThree : 23;",
17240                Alignment);
17241 
17242   // Initializers are allowed starting with c++2a
17243   verifyFormat("int const a     : 5 = 1;\n"
17244                "int oneTwoThree : 23 = 0;",
17245                Alignment);
17246 
17247   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17248   verifyFormat("int const a           : 5;\n"
17249                "int       oneTwoThree : 23;",
17250                Alignment);
17251 
17252   verifyFormat("int const a           : 5;  // comment\n"
17253                "int       oneTwoThree : 23; // comment",
17254                Alignment);
17255 
17256   verifyFormat("int const a           : 5 = 1;\n"
17257                "int       oneTwoThree : 23 = 0;",
17258                Alignment);
17259 
17260   Alignment.AlignConsecutiveAssignments.Enabled = true;
17261   verifyFormat("int const a           : 5  = 1;\n"
17262                "int       oneTwoThree : 23 = 0;",
17263                Alignment);
17264   verifyFormat("int const a           : 5  = {1};\n"
17265                "int       oneTwoThree : 23 = 0;",
17266                Alignment);
17267 
17268   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
17269   verifyFormat("int const a          :5;\n"
17270                "int       oneTwoThree:23;",
17271                Alignment);
17272 
17273   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
17274   verifyFormat("int const a           :5;\n"
17275                "int       oneTwoThree :23;",
17276                Alignment);
17277 
17278   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
17279   verifyFormat("int const a          : 5;\n"
17280                "int       oneTwoThree: 23;",
17281                Alignment);
17282 
17283   // Known limitations: ':' is only recognized as a bitfield colon when
17284   // followed by a number.
17285   /*
17286   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
17287                "int a           : 5;",
17288                Alignment);
17289   */
17290 }
17291 
17292 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
17293   FormatStyle Alignment = getLLVMStyle();
17294   Alignment.AlignConsecutiveMacros.Enabled = true;
17295   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17296   verifyFormat("float const a = 5;\n"
17297                "int oneTwoThree = 123;",
17298                Alignment);
17299   verifyFormat("int a = 5;\n"
17300                "float const oneTwoThree = 123;",
17301                Alignment);
17302 
17303   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17304   verifyFormat("float const a = 5;\n"
17305                "int         oneTwoThree = 123;",
17306                Alignment);
17307   verifyFormat("int         a = method();\n"
17308                "float const oneTwoThree = 133;",
17309                Alignment);
17310   verifyFormat("int i = 1, j = 10;\n"
17311                "something = 2000;",
17312                Alignment);
17313   verifyFormat("something = 2000;\n"
17314                "int i = 1, j = 10;\n",
17315                Alignment);
17316   verifyFormat("float      something = 2000;\n"
17317                "double     another = 911;\n"
17318                "int        i = 1, j = 10;\n"
17319                "const int *oneMore = 1;\n"
17320                "unsigned   i = 2;",
17321                Alignment);
17322   verifyFormat("float a = 5;\n"
17323                "int   one = 1;\n"
17324                "method();\n"
17325                "const double       oneTwoThree = 123;\n"
17326                "const unsigned int oneTwo = 12;",
17327                Alignment);
17328   verifyFormat("int      oneTwoThree{0}; // comment\n"
17329                "unsigned oneTwo;         // comment",
17330                Alignment);
17331   verifyFormat("unsigned int       *a;\n"
17332                "int                *b;\n"
17333                "unsigned int Const *c;\n"
17334                "unsigned int const *d;\n"
17335                "unsigned int Const &e;\n"
17336                "unsigned int const &f;",
17337                Alignment);
17338   verifyFormat("Const unsigned int *c;\n"
17339                "const unsigned int *d;\n"
17340                "Const unsigned int &e;\n"
17341                "const unsigned int &f;\n"
17342                "const unsigned      g;\n"
17343                "Const unsigned      h;",
17344                Alignment);
17345   EXPECT_EQ("float const a = 5;\n"
17346             "\n"
17347             "int oneTwoThree = 123;",
17348             format("float const   a = 5;\n"
17349                    "\n"
17350                    "int           oneTwoThree= 123;",
17351                    Alignment));
17352   EXPECT_EQ("float a = 5;\n"
17353             "int   one = 1;\n"
17354             "\n"
17355             "unsigned oneTwoThree = 123;",
17356             format("float    a = 5;\n"
17357                    "int      one = 1;\n"
17358                    "\n"
17359                    "unsigned oneTwoThree = 123;",
17360                    Alignment));
17361   EXPECT_EQ("float a = 5;\n"
17362             "int   one = 1;\n"
17363             "\n"
17364             "unsigned oneTwoThree = 123;\n"
17365             "int      oneTwo = 12;",
17366             format("float    a = 5;\n"
17367                    "int one = 1;\n"
17368                    "\n"
17369                    "unsigned oneTwoThree = 123;\n"
17370                    "int oneTwo = 12;",
17371                    Alignment));
17372   // Function prototype alignment
17373   verifyFormat("int    a();\n"
17374                "double b();",
17375                Alignment);
17376   verifyFormat("int    a(int x);\n"
17377                "double b();",
17378                Alignment);
17379   unsigned OldColumnLimit = Alignment.ColumnLimit;
17380   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17381   // otherwise the function parameters will be re-flowed onto a single line.
17382   Alignment.ColumnLimit = 0;
17383   EXPECT_EQ("int    a(int   x,\n"
17384             "         float y);\n"
17385             "double b(int    x,\n"
17386             "         double y);",
17387             format("int a(int x,\n"
17388                    " float y);\n"
17389                    "double b(int x,\n"
17390                    " double y);",
17391                    Alignment));
17392   // This ensures that function parameters of function declarations are
17393   // correctly indented when their owning functions are indented.
17394   // The failure case here is for 'double y' to not be indented enough.
17395   EXPECT_EQ("double a(int x);\n"
17396             "int    b(int    y,\n"
17397             "         double z);",
17398             format("double a(int x);\n"
17399                    "int b(int y,\n"
17400                    " double z);",
17401                    Alignment));
17402   // Set ColumnLimit low so that we induce wrapping immediately after
17403   // the function name and opening paren.
17404   Alignment.ColumnLimit = 13;
17405   verifyFormat("int function(\n"
17406                "    int  x,\n"
17407                "    bool y);",
17408                Alignment);
17409   Alignment.ColumnLimit = OldColumnLimit;
17410   // Ensure function pointers don't screw up recursive alignment
17411   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17412                "double b();",
17413                Alignment);
17414   Alignment.AlignConsecutiveAssignments.Enabled = true;
17415   // Ensure recursive alignment is broken by function braces, so that the
17416   // "a = 1" does not align with subsequent assignments inside the function
17417   // body.
17418   verifyFormat("int func(int a = 1) {\n"
17419                "  int b  = 2;\n"
17420                "  int cc = 3;\n"
17421                "}",
17422                Alignment);
17423   verifyFormat("float      something = 2000;\n"
17424                "double     another   = 911;\n"
17425                "int        i = 1, j = 10;\n"
17426                "const int *oneMore = 1;\n"
17427                "unsigned   i       = 2;",
17428                Alignment);
17429   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17430                "unsigned oneTwo      = 0;   // comment",
17431                Alignment);
17432   // Make sure that scope is correctly tracked, in the absence of braces
17433   verifyFormat("for (int i = 0; i < n; i++)\n"
17434                "  j = i;\n"
17435                "double x = 1;\n",
17436                Alignment);
17437   verifyFormat("if (int i = 0)\n"
17438                "  j = i;\n"
17439                "double x = 1;\n",
17440                Alignment);
17441   // Ensure operator[] and operator() are comprehended
17442   verifyFormat("struct test {\n"
17443                "  long long int foo();\n"
17444                "  int           operator[](int a);\n"
17445                "  double        bar();\n"
17446                "};\n",
17447                Alignment);
17448   verifyFormat("struct test {\n"
17449                "  long long int foo();\n"
17450                "  int           operator()(int a);\n"
17451                "  double        bar();\n"
17452                "};\n",
17453                Alignment);
17454   // http://llvm.org/PR52914
17455   verifyFormat("char *a[]     = {\"a\", // comment\n"
17456                "                 \"bb\"};\n"
17457                "int   bbbbbbb = 0;",
17458                Alignment);
17459 
17460   // PAS_Right
17461   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17462             "  int const i   = 1;\n"
17463             "  int      *j   = 2;\n"
17464             "  int       big = 10000;\n"
17465             "\n"
17466             "  unsigned oneTwoThree = 123;\n"
17467             "  int      oneTwo      = 12;\n"
17468             "  method();\n"
17469             "  float k  = 2;\n"
17470             "  int   ll = 10000;\n"
17471             "}",
17472             format("void SomeFunction(int parameter= 0) {\n"
17473                    " int const  i= 1;\n"
17474                    "  int *j=2;\n"
17475                    " int big  =  10000;\n"
17476                    "\n"
17477                    "unsigned oneTwoThree  =123;\n"
17478                    "int oneTwo = 12;\n"
17479                    "  method();\n"
17480                    "float k= 2;\n"
17481                    "int ll=10000;\n"
17482                    "}",
17483                    Alignment));
17484   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17485             "  int const i   = 1;\n"
17486             "  int     **j   = 2, ***k;\n"
17487             "  int      &k   = i;\n"
17488             "  int     &&l   = i + j;\n"
17489             "  int       big = 10000;\n"
17490             "\n"
17491             "  unsigned oneTwoThree = 123;\n"
17492             "  int      oneTwo      = 12;\n"
17493             "  method();\n"
17494             "  float k  = 2;\n"
17495             "  int   ll = 10000;\n"
17496             "}",
17497             format("void SomeFunction(int parameter= 0) {\n"
17498                    " int const  i= 1;\n"
17499                    "  int **j=2,***k;\n"
17500                    "int &k=i;\n"
17501                    "int &&l=i+j;\n"
17502                    " int big  =  10000;\n"
17503                    "\n"
17504                    "unsigned oneTwoThree  =123;\n"
17505                    "int oneTwo = 12;\n"
17506                    "  method();\n"
17507                    "float k= 2;\n"
17508                    "int ll=10000;\n"
17509                    "}",
17510                    Alignment));
17511   // variables are aligned at their name, pointers are at the right most
17512   // position
17513   verifyFormat("int   *a;\n"
17514                "int  **b;\n"
17515                "int ***c;\n"
17516                "int    foobar;\n",
17517                Alignment);
17518 
17519   // PAS_Left
17520   FormatStyle AlignmentLeft = Alignment;
17521   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17522   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17523             "  int const i   = 1;\n"
17524             "  int*      j   = 2;\n"
17525             "  int       big = 10000;\n"
17526             "\n"
17527             "  unsigned oneTwoThree = 123;\n"
17528             "  int      oneTwo      = 12;\n"
17529             "  method();\n"
17530             "  float k  = 2;\n"
17531             "  int   ll = 10000;\n"
17532             "}",
17533             format("void SomeFunction(int parameter= 0) {\n"
17534                    " int const  i= 1;\n"
17535                    "  int *j=2;\n"
17536                    " int big  =  10000;\n"
17537                    "\n"
17538                    "unsigned oneTwoThree  =123;\n"
17539                    "int oneTwo = 12;\n"
17540                    "  method();\n"
17541                    "float k= 2;\n"
17542                    "int ll=10000;\n"
17543                    "}",
17544                    AlignmentLeft));
17545   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17546             "  int const i   = 1;\n"
17547             "  int**     j   = 2;\n"
17548             "  int&      k   = i;\n"
17549             "  int&&     l   = i + j;\n"
17550             "  int       big = 10000;\n"
17551             "\n"
17552             "  unsigned oneTwoThree = 123;\n"
17553             "  int      oneTwo      = 12;\n"
17554             "  method();\n"
17555             "  float k  = 2;\n"
17556             "  int   ll = 10000;\n"
17557             "}",
17558             format("void SomeFunction(int parameter= 0) {\n"
17559                    " int const  i= 1;\n"
17560                    "  int **j=2;\n"
17561                    "int &k=i;\n"
17562                    "int &&l=i+j;\n"
17563                    " int big  =  10000;\n"
17564                    "\n"
17565                    "unsigned oneTwoThree  =123;\n"
17566                    "int oneTwo = 12;\n"
17567                    "  method();\n"
17568                    "float k= 2;\n"
17569                    "int ll=10000;\n"
17570                    "}",
17571                    AlignmentLeft));
17572   // variables are aligned at their name, pointers are at the left most position
17573   verifyFormat("int*   a;\n"
17574                "int**  b;\n"
17575                "int*** c;\n"
17576                "int    foobar;\n",
17577                AlignmentLeft);
17578 
17579   // PAS_Middle
17580   FormatStyle AlignmentMiddle = Alignment;
17581   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17582   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17583             "  int const i   = 1;\n"
17584             "  int *     j   = 2;\n"
17585             "  int       big = 10000;\n"
17586             "\n"
17587             "  unsigned oneTwoThree = 123;\n"
17588             "  int      oneTwo      = 12;\n"
17589             "  method();\n"
17590             "  float k  = 2;\n"
17591             "  int   ll = 10000;\n"
17592             "}",
17593             format("void SomeFunction(int parameter= 0) {\n"
17594                    " int const  i= 1;\n"
17595                    "  int *j=2;\n"
17596                    " int big  =  10000;\n"
17597                    "\n"
17598                    "unsigned oneTwoThree  =123;\n"
17599                    "int oneTwo = 12;\n"
17600                    "  method();\n"
17601                    "float k= 2;\n"
17602                    "int ll=10000;\n"
17603                    "}",
17604                    AlignmentMiddle));
17605   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17606             "  int const i   = 1;\n"
17607             "  int **    j   = 2, ***k;\n"
17608             "  int &     k   = i;\n"
17609             "  int &&    l   = i + j;\n"
17610             "  int       big = 10000;\n"
17611             "\n"
17612             "  unsigned oneTwoThree = 123;\n"
17613             "  int      oneTwo      = 12;\n"
17614             "  method();\n"
17615             "  float k  = 2;\n"
17616             "  int   ll = 10000;\n"
17617             "}",
17618             format("void SomeFunction(int parameter= 0) {\n"
17619                    " int const  i= 1;\n"
17620                    "  int **j=2,***k;\n"
17621                    "int &k=i;\n"
17622                    "int &&l=i+j;\n"
17623                    " int big  =  10000;\n"
17624                    "\n"
17625                    "unsigned oneTwoThree  =123;\n"
17626                    "int oneTwo = 12;\n"
17627                    "  method();\n"
17628                    "float k= 2;\n"
17629                    "int ll=10000;\n"
17630                    "}",
17631                    AlignmentMiddle));
17632   // variables are aligned at their name, pointers are in the middle
17633   verifyFormat("int *   a;\n"
17634                "int *   b;\n"
17635                "int *** c;\n"
17636                "int     foobar;\n",
17637                AlignmentMiddle);
17638 
17639   Alignment.AlignConsecutiveAssignments.Enabled = false;
17640   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17641   verifyFormat("#define A \\\n"
17642                "  int       aaaa = 12; \\\n"
17643                "  float     b = 23; \\\n"
17644                "  const int ccc = 234; \\\n"
17645                "  unsigned  dddddddddd = 2345;",
17646                Alignment);
17647   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17648   verifyFormat("#define A              \\\n"
17649                "  int       aaaa = 12; \\\n"
17650                "  float     b = 23;    \\\n"
17651                "  const int ccc = 234; \\\n"
17652                "  unsigned  dddddddddd = 2345;",
17653                Alignment);
17654   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17655   Alignment.ColumnLimit = 30;
17656   verifyFormat("#define A                    \\\n"
17657                "  int       aaaa = 12;       \\\n"
17658                "  float     b = 23;          \\\n"
17659                "  const int ccc = 234;       \\\n"
17660                "  int       dddddddddd = 2345;",
17661                Alignment);
17662   Alignment.ColumnLimit = 80;
17663   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17664                "k = 4, int l = 5,\n"
17665                "                  int m = 6) {\n"
17666                "  const int j = 10;\n"
17667                "  otherThing = 1;\n"
17668                "}",
17669                Alignment);
17670   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17671                "  int const i = 1;\n"
17672                "  int      *j = 2;\n"
17673                "  int       big = 10000;\n"
17674                "}",
17675                Alignment);
17676   verifyFormat("class C {\n"
17677                "public:\n"
17678                "  int          i = 1;\n"
17679                "  virtual void f() = 0;\n"
17680                "};",
17681                Alignment);
17682   verifyFormat("float i = 1;\n"
17683                "if (SomeType t = getSomething()) {\n"
17684                "}\n"
17685                "const unsigned j = 2;\n"
17686                "int            big = 10000;",
17687                Alignment);
17688   verifyFormat("float j = 7;\n"
17689                "for (int k = 0; k < N; ++k) {\n"
17690                "}\n"
17691                "unsigned j = 2;\n"
17692                "int      big = 10000;\n"
17693                "}",
17694                Alignment);
17695   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17696   verifyFormat("float              i = 1;\n"
17697                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17698                "    = someLooooooooooooooooongFunction();\n"
17699                "int j = 2;",
17700                Alignment);
17701   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17702   verifyFormat("int                i = 1;\n"
17703                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17704                "    someLooooooooooooooooongFunction();\n"
17705                "int j = 2;",
17706                Alignment);
17707 
17708   Alignment.AlignConsecutiveAssignments.Enabled = true;
17709   verifyFormat("auto lambda = []() {\n"
17710                "  auto  ii = 0;\n"
17711                "  float j  = 0;\n"
17712                "  return 0;\n"
17713                "};\n"
17714                "int   i  = 0;\n"
17715                "float i2 = 0;\n"
17716                "auto  v  = type{\n"
17717                "    i = 1,   //\n"
17718                "    (i = 2), //\n"
17719                "    i = 3    //\n"
17720                "};",
17721                Alignment);
17722   Alignment.AlignConsecutiveAssignments.Enabled = false;
17723 
17724   verifyFormat(
17725       "int      i = 1;\n"
17726       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17727       "                          loooooooooooooooooooooongParameterB);\n"
17728       "int      j = 2;",
17729       Alignment);
17730 
17731   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17732   // We expect declarations and assignments to align, as long as it doesn't
17733   // exceed the column limit, starting a new alignment sequence whenever it
17734   // happens.
17735   Alignment.AlignConsecutiveAssignments.Enabled = true;
17736   Alignment.ColumnLimit = 30;
17737   verifyFormat("float    ii              = 1;\n"
17738                "unsigned j               = 2;\n"
17739                "int someVerylongVariable = 1;\n"
17740                "AnotherLongType  ll = 123456;\n"
17741                "VeryVeryLongType k  = 2;\n"
17742                "int              myvar = 1;",
17743                Alignment);
17744   Alignment.ColumnLimit = 80;
17745   Alignment.AlignConsecutiveAssignments.Enabled = false;
17746 
17747   verifyFormat(
17748       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17749       "          typename LongType, typename B>\n"
17750       "auto foo() {}\n",
17751       Alignment);
17752   verifyFormat("float a, b = 1;\n"
17753                "int   c = 2;\n"
17754                "int   dd = 3;\n",
17755                Alignment);
17756   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17757                "float b[1][] = {{3.f}};\n",
17758                Alignment);
17759   Alignment.AlignConsecutiveAssignments.Enabled = true;
17760   verifyFormat("float a, b = 1;\n"
17761                "int   c  = 2;\n"
17762                "int   dd = 3;\n",
17763                Alignment);
17764   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17765                "float b[1][] = {{3.f}};\n",
17766                Alignment);
17767   Alignment.AlignConsecutiveAssignments.Enabled = false;
17768 
17769   Alignment.ColumnLimit = 30;
17770   Alignment.BinPackParameters = false;
17771   verifyFormat("void foo(float     a,\n"
17772                "         float     b,\n"
17773                "         int       c,\n"
17774                "         uint32_t *d) {\n"
17775                "  int   *e = 0;\n"
17776                "  float  f = 0;\n"
17777                "  double g = 0;\n"
17778                "}\n"
17779                "void bar(ino_t     a,\n"
17780                "         int       b,\n"
17781                "         uint32_t *c,\n"
17782                "         bool      d) {}\n",
17783                Alignment);
17784   Alignment.BinPackParameters = true;
17785   Alignment.ColumnLimit = 80;
17786 
17787   // Bug 33507
17788   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17789   verifyFormat(
17790       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
17791       "  static const Version verVs2017;\n"
17792       "  return true;\n"
17793       "});\n",
17794       Alignment);
17795   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17796 
17797   // See llvm.org/PR35641
17798   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17799   verifyFormat("int func() { //\n"
17800                "  int      b;\n"
17801                "  unsigned c;\n"
17802                "}",
17803                Alignment);
17804 
17805   // See PR37175
17806   FormatStyle Style = getMozillaStyle();
17807   Style.AlignConsecutiveDeclarations.Enabled = true;
17808   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17809             "foo(int a);",
17810             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17811 
17812   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17813   verifyFormat("unsigned int*       a;\n"
17814                "int*                b;\n"
17815                "unsigned int Const* c;\n"
17816                "unsigned int const* d;\n"
17817                "unsigned int Const& e;\n"
17818                "unsigned int const& f;",
17819                Alignment);
17820   verifyFormat("Const unsigned int* c;\n"
17821                "const unsigned int* d;\n"
17822                "Const unsigned int& e;\n"
17823                "const unsigned int& f;\n"
17824                "const unsigned      g;\n"
17825                "Const unsigned      h;",
17826                Alignment);
17827 
17828   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17829   verifyFormat("unsigned int *       a;\n"
17830                "int *                b;\n"
17831                "unsigned int Const * c;\n"
17832                "unsigned int const * d;\n"
17833                "unsigned int Const & e;\n"
17834                "unsigned int const & f;",
17835                Alignment);
17836   verifyFormat("Const unsigned int * c;\n"
17837                "const unsigned int * d;\n"
17838                "Const unsigned int & e;\n"
17839                "const unsigned int & f;\n"
17840                "const unsigned       g;\n"
17841                "Const unsigned       h;",
17842                Alignment);
17843 
17844   // See PR46529
17845   FormatStyle BracedAlign = getLLVMStyle();
17846   BracedAlign.AlignConsecutiveDeclarations.Enabled = true;
17847   verifyFormat("const auto result{[]() {\n"
17848                "  const auto something = 1;\n"
17849                "  return 2;\n"
17850                "}};",
17851                BracedAlign);
17852   verifyFormat("int foo{[]() {\n"
17853                "  int bar{0};\n"
17854                "  return 0;\n"
17855                "}()};",
17856                BracedAlign);
17857   BracedAlign.Cpp11BracedListStyle = false;
17858   verifyFormat("const auto result{ []() {\n"
17859                "  const auto something = 1;\n"
17860                "  return 2;\n"
17861                "} };",
17862                BracedAlign);
17863   verifyFormat("int foo{ []() {\n"
17864                "  int bar{ 0 };\n"
17865                "  return 0;\n"
17866                "}() };",
17867                BracedAlign);
17868 }
17869 
17870 TEST_F(FormatTest, AlignWithLineBreaks) {
17871   auto Style = getLLVMStyleWithColumns(120);
17872 
17873   EXPECT_EQ(Style.AlignConsecutiveAssignments,
17874             FormatStyle::AlignConsecutiveStyle(
17875                 {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
17876                  /*AcrossComments=*/false, /*AlignCompound=*/false,
17877                  /*PadOperators=*/true}));
17878   EXPECT_EQ(Style.AlignConsecutiveDeclarations,
17879             FormatStyle::AlignConsecutiveStyle({}));
17880   verifyFormat("void foo() {\n"
17881                "  int myVar = 5;\n"
17882                "  double x = 3.14;\n"
17883                "  auto str = \"Hello \"\n"
17884                "             \"World\";\n"
17885                "  auto s = \"Hello \"\n"
17886                "           \"Again\";\n"
17887                "}",
17888                Style);
17889 
17890   // clang-format off
17891   verifyFormat("void foo() {\n"
17892                "  const int capacityBefore = Entries.capacity();\n"
17893                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17894                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17895                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17896                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17897                "}",
17898                Style);
17899   // clang-format on
17900 
17901   Style.AlignConsecutiveAssignments.Enabled = true;
17902   verifyFormat("void foo() {\n"
17903                "  int myVar = 5;\n"
17904                "  double x  = 3.14;\n"
17905                "  auto str  = \"Hello \"\n"
17906                "              \"World\";\n"
17907                "  auto s    = \"Hello \"\n"
17908                "              \"Again\";\n"
17909                "}",
17910                Style);
17911 
17912   // clang-format off
17913   verifyFormat("void foo() {\n"
17914                "  const int capacityBefore = Entries.capacity();\n"
17915                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17916                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17917                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17918                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17919                "}",
17920                Style);
17921   // clang-format on
17922 
17923   Style.AlignConsecutiveAssignments.Enabled = false;
17924   Style.AlignConsecutiveDeclarations.Enabled = true;
17925   verifyFormat("void foo() {\n"
17926                "  int    myVar = 5;\n"
17927                "  double x = 3.14;\n"
17928                "  auto   str = \"Hello \"\n"
17929                "               \"World\";\n"
17930                "  auto   s = \"Hello \"\n"
17931                "             \"Again\";\n"
17932                "}",
17933                Style);
17934 
17935   // clang-format off
17936   verifyFormat("void foo() {\n"
17937                "  const int  capacityBefore = Entries.capacity();\n"
17938                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17939                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17940                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17941                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17942                "}",
17943                Style);
17944   // clang-format on
17945 
17946   Style.AlignConsecutiveAssignments.Enabled = true;
17947   Style.AlignConsecutiveDeclarations.Enabled = true;
17948 
17949   verifyFormat("void foo() {\n"
17950                "  int    myVar = 5;\n"
17951                "  double x     = 3.14;\n"
17952                "  auto   str   = \"Hello \"\n"
17953                "                 \"World\";\n"
17954                "  auto   s     = \"Hello \"\n"
17955                "                 \"Again\";\n"
17956                "}",
17957                Style);
17958 
17959   // clang-format off
17960   verifyFormat("void foo() {\n"
17961                "  const int  capacityBefore = Entries.capacity();\n"
17962                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17963                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17964                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17965                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17966                "}",
17967                Style);
17968   // clang-format on
17969 
17970   Style = getLLVMStyleWithColumns(120);
17971   Style.AlignConsecutiveAssignments.Enabled = true;
17972   Style.ContinuationIndentWidth = 4;
17973   Style.IndentWidth = 4;
17974 
17975   // clang-format off
17976   verifyFormat("void SomeFunc() {\n"
17977                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17978                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17979                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17980                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17981                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17982                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17983                "}",
17984                Style);
17985   // clang-format on
17986 
17987   Style.BinPackArguments = false;
17988 
17989   // clang-format off
17990   verifyFormat("void SomeFunc() {\n"
17991                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
17992                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17993                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
17994                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17995                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
17996                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17997                "}",
17998                Style);
17999   // clang-format on
18000 }
18001 
18002 TEST_F(FormatTest, AlignWithInitializerPeriods) {
18003   auto Style = getLLVMStyleWithColumns(60);
18004 
18005   verifyFormat("void foo1(void) {\n"
18006                "  BYTE p[1] = 1;\n"
18007                "  A B = {.one_foooooooooooooooo = 2,\n"
18008                "         .two_fooooooooooooo = 3,\n"
18009                "         .three_fooooooooooooo = 4};\n"
18010                "  BYTE payload = 2;\n"
18011                "}",
18012                Style);
18013 
18014   Style.AlignConsecutiveAssignments.Enabled = true;
18015   Style.AlignConsecutiveDeclarations.Enabled = false;
18016   verifyFormat("void foo2(void) {\n"
18017                "  BYTE p[1]    = 1;\n"
18018                "  A B          = {.one_foooooooooooooooo = 2,\n"
18019                "                  .two_fooooooooooooo    = 3,\n"
18020                "                  .three_fooooooooooooo  = 4};\n"
18021                "  BYTE payload = 2;\n"
18022                "}",
18023                Style);
18024 
18025   Style.AlignConsecutiveAssignments.Enabled = false;
18026   Style.AlignConsecutiveDeclarations.Enabled = true;
18027   verifyFormat("void foo3(void) {\n"
18028                "  BYTE p[1] = 1;\n"
18029                "  A    B = {.one_foooooooooooooooo = 2,\n"
18030                "            .two_fooooooooooooo = 3,\n"
18031                "            .three_fooooooooooooo = 4};\n"
18032                "  BYTE payload = 2;\n"
18033                "}",
18034                Style);
18035 
18036   Style.AlignConsecutiveAssignments.Enabled = true;
18037   Style.AlignConsecutiveDeclarations.Enabled = true;
18038   verifyFormat("void foo4(void) {\n"
18039                "  BYTE p[1]    = 1;\n"
18040                "  A    B       = {.one_foooooooooooooooo = 2,\n"
18041                "                  .two_fooooooooooooo    = 3,\n"
18042                "                  .three_fooooooooooooo  = 4};\n"
18043                "  BYTE payload = 2;\n"
18044                "}",
18045                Style);
18046 }
18047 
18048 TEST_F(FormatTest, LinuxBraceBreaking) {
18049   FormatStyle LinuxBraceStyle = getLLVMStyle();
18050   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
18051   verifyFormat("namespace a\n"
18052                "{\n"
18053                "class A\n"
18054                "{\n"
18055                "  void f()\n"
18056                "  {\n"
18057                "    if (true) {\n"
18058                "      a();\n"
18059                "      b();\n"
18060                "    } else {\n"
18061                "      a();\n"
18062                "    }\n"
18063                "  }\n"
18064                "  void g() { return; }\n"
18065                "};\n"
18066                "struct B {\n"
18067                "  int x;\n"
18068                "};\n"
18069                "} // namespace a\n",
18070                LinuxBraceStyle);
18071   verifyFormat("enum X {\n"
18072                "  Y = 0,\n"
18073                "}\n",
18074                LinuxBraceStyle);
18075   verifyFormat("struct S {\n"
18076                "  int Type;\n"
18077                "  union {\n"
18078                "    int x;\n"
18079                "    double y;\n"
18080                "  } Value;\n"
18081                "  class C\n"
18082                "  {\n"
18083                "    MyFavoriteType Value;\n"
18084                "  } Class;\n"
18085                "}\n",
18086                LinuxBraceStyle);
18087 }
18088 
18089 TEST_F(FormatTest, MozillaBraceBreaking) {
18090   FormatStyle MozillaBraceStyle = getLLVMStyle();
18091   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
18092   MozillaBraceStyle.FixNamespaceComments = false;
18093   verifyFormat("namespace a {\n"
18094                "class A\n"
18095                "{\n"
18096                "  void f()\n"
18097                "  {\n"
18098                "    if (true) {\n"
18099                "      a();\n"
18100                "      b();\n"
18101                "    }\n"
18102                "  }\n"
18103                "  void g() { return; }\n"
18104                "};\n"
18105                "enum E\n"
18106                "{\n"
18107                "  A,\n"
18108                "  // foo\n"
18109                "  B,\n"
18110                "  C\n"
18111                "};\n"
18112                "struct B\n"
18113                "{\n"
18114                "  int x;\n"
18115                "};\n"
18116                "}\n",
18117                MozillaBraceStyle);
18118   verifyFormat("struct S\n"
18119                "{\n"
18120                "  int Type;\n"
18121                "  union\n"
18122                "  {\n"
18123                "    int x;\n"
18124                "    double y;\n"
18125                "  } Value;\n"
18126                "  class C\n"
18127                "  {\n"
18128                "    MyFavoriteType Value;\n"
18129                "  } Class;\n"
18130                "}\n",
18131                MozillaBraceStyle);
18132 }
18133 
18134 TEST_F(FormatTest, StroustrupBraceBreaking) {
18135   FormatStyle StroustrupBraceStyle = getLLVMStyle();
18136   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18137   verifyFormat("namespace a {\n"
18138                "class A {\n"
18139                "  void f()\n"
18140                "  {\n"
18141                "    if (true) {\n"
18142                "      a();\n"
18143                "      b();\n"
18144                "    }\n"
18145                "  }\n"
18146                "  void g() { return; }\n"
18147                "};\n"
18148                "struct B {\n"
18149                "  int x;\n"
18150                "};\n"
18151                "} // namespace a\n",
18152                StroustrupBraceStyle);
18153 
18154   verifyFormat("void foo()\n"
18155                "{\n"
18156                "  if (a) {\n"
18157                "    a();\n"
18158                "  }\n"
18159                "  else {\n"
18160                "    b();\n"
18161                "  }\n"
18162                "}\n",
18163                StroustrupBraceStyle);
18164 
18165   verifyFormat("#ifdef _DEBUG\n"
18166                "int foo(int i = 0)\n"
18167                "#else\n"
18168                "int foo(int i = 5)\n"
18169                "#endif\n"
18170                "{\n"
18171                "  return i;\n"
18172                "}",
18173                StroustrupBraceStyle);
18174 
18175   verifyFormat("void foo() {}\n"
18176                "void bar()\n"
18177                "#ifdef _DEBUG\n"
18178                "{\n"
18179                "  foo();\n"
18180                "}\n"
18181                "#else\n"
18182                "{\n"
18183                "}\n"
18184                "#endif",
18185                StroustrupBraceStyle);
18186 
18187   verifyFormat("void foobar() { int i = 5; }\n"
18188                "#ifdef _DEBUG\n"
18189                "void bar() {}\n"
18190                "#else\n"
18191                "void bar() { foobar(); }\n"
18192                "#endif",
18193                StroustrupBraceStyle);
18194 }
18195 
18196 TEST_F(FormatTest, AllmanBraceBreaking) {
18197   FormatStyle AllmanBraceStyle = getLLVMStyle();
18198   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
18199 
18200   EXPECT_EQ("namespace a\n"
18201             "{\n"
18202             "void f();\n"
18203             "void g();\n"
18204             "} // namespace a\n",
18205             format("namespace a\n"
18206                    "{\n"
18207                    "void f();\n"
18208                    "void g();\n"
18209                    "}\n",
18210                    AllmanBraceStyle));
18211 
18212   verifyFormat("namespace a\n"
18213                "{\n"
18214                "class A\n"
18215                "{\n"
18216                "  void f()\n"
18217                "  {\n"
18218                "    if (true)\n"
18219                "    {\n"
18220                "      a();\n"
18221                "      b();\n"
18222                "    }\n"
18223                "  }\n"
18224                "  void g() { return; }\n"
18225                "};\n"
18226                "struct B\n"
18227                "{\n"
18228                "  int x;\n"
18229                "};\n"
18230                "union C\n"
18231                "{\n"
18232                "};\n"
18233                "} // namespace a",
18234                AllmanBraceStyle);
18235 
18236   verifyFormat("void f()\n"
18237                "{\n"
18238                "  if (true)\n"
18239                "  {\n"
18240                "    a();\n"
18241                "  }\n"
18242                "  else if (false)\n"
18243                "  {\n"
18244                "    b();\n"
18245                "  }\n"
18246                "  else\n"
18247                "  {\n"
18248                "    c();\n"
18249                "  }\n"
18250                "}\n",
18251                AllmanBraceStyle);
18252 
18253   verifyFormat("void f()\n"
18254                "{\n"
18255                "  for (int i = 0; i < 10; ++i)\n"
18256                "  {\n"
18257                "    a();\n"
18258                "  }\n"
18259                "  while (false)\n"
18260                "  {\n"
18261                "    b();\n"
18262                "  }\n"
18263                "  do\n"
18264                "  {\n"
18265                "    c();\n"
18266                "  } while (false)\n"
18267                "}\n",
18268                AllmanBraceStyle);
18269 
18270   verifyFormat("void f(int a)\n"
18271                "{\n"
18272                "  switch (a)\n"
18273                "  {\n"
18274                "  case 0:\n"
18275                "    break;\n"
18276                "  case 1:\n"
18277                "  {\n"
18278                "    break;\n"
18279                "  }\n"
18280                "  case 2:\n"
18281                "  {\n"
18282                "  }\n"
18283                "  break;\n"
18284                "  default:\n"
18285                "    break;\n"
18286                "  }\n"
18287                "}\n",
18288                AllmanBraceStyle);
18289 
18290   verifyFormat("enum X\n"
18291                "{\n"
18292                "  Y = 0,\n"
18293                "}\n",
18294                AllmanBraceStyle);
18295   verifyFormat("enum X\n"
18296                "{\n"
18297                "  Y = 0\n"
18298                "}\n",
18299                AllmanBraceStyle);
18300 
18301   verifyFormat("@interface BSApplicationController ()\n"
18302                "{\n"
18303                "@private\n"
18304                "  id _extraIvar;\n"
18305                "}\n"
18306                "@end\n",
18307                AllmanBraceStyle);
18308 
18309   verifyFormat("#ifdef _DEBUG\n"
18310                "int foo(int i = 0)\n"
18311                "#else\n"
18312                "int foo(int i = 5)\n"
18313                "#endif\n"
18314                "{\n"
18315                "  return i;\n"
18316                "}",
18317                AllmanBraceStyle);
18318 
18319   verifyFormat("void foo() {}\n"
18320                "void bar()\n"
18321                "#ifdef _DEBUG\n"
18322                "{\n"
18323                "  foo();\n"
18324                "}\n"
18325                "#else\n"
18326                "{\n"
18327                "}\n"
18328                "#endif",
18329                AllmanBraceStyle);
18330 
18331   verifyFormat("void foobar() { int i = 5; }\n"
18332                "#ifdef _DEBUG\n"
18333                "void bar() {}\n"
18334                "#else\n"
18335                "void bar() { foobar(); }\n"
18336                "#endif",
18337                AllmanBraceStyle);
18338 
18339   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18340             FormatStyle::SLS_All);
18341 
18342   verifyFormat("[](int i) { return i + 2; };\n"
18343                "[](int i, int j)\n"
18344                "{\n"
18345                "  auto x = i + j;\n"
18346                "  auto y = i * j;\n"
18347                "  return x ^ y;\n"
18348                "};\n"
18349                "void foo()\n"
18350                "{\n"
18351                "  auto shortLambda = [](int i) { return i + 2; };\n"
18352                "  auto longLambda = [](int i, int j)\n"
18353                "  {\n"
18354                "    auto x = i + j;\n"
18355                "    auto y = i * j;\n"
18356                "    return x ^ y;\n"
18357                "  };\n"
18358                "}",
18359                AllmanBraceStyle);
18360 
18361   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18362 
18363   verifyFormat("[](int i)\n"
18364                "{\n"
18365                "  return i + 2;\n"
18366                "};\n"
18367                "[](int i, int j)\n"
18368                "{\n"
18369                "  auto x = i + j;\n"
18370                "  auto y = i * j;\n"
18371                "  return x ^ y;\n"
18372                "};\n"
18373                "void foo()\n"
18374                "{\n"
18375                "  auto shortLambda = [](int i)\n"
18376                "  {\n"
18377                "    return i + 2;\n"
18378                "  };\n"
18379                "  auto longLambda = [](int i, int j)\n"
18380                "  {\n"
18381                "    auto x = i + j;\n"
18382                "    auto y = i * j;\n"
18383                "    return x ^ y;\n"
18384                "  };\n"
18385                "}",
18386                AllmanBraceStyle);
18387 
18388   // Reset
18389   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18390 
18391   // This shouldn't affect ObjC blocks..
18392   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18393                "  // ...\n"
18394                "  int i;\n"
18395                "}];",
18396                AllmanBraceStyle);
18397   verifyFormat("void (^block)(void) = ^{\n"
18398                "  // ...\n"
18399                "  int i;\n"
18400                "};",
18401                AllmanBraceStyle);
18402   // .. or dict literals.
18403   verifyFormat("void f()\n"
18404                "{\n"
18405                "  // ...\n"
18406                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18407                "}",
18408                AllmanBraceStyle);
18409   verifyFormat("void f()\n"
18410                "{\n"
18411                "  // ...\n"
18412                "  [object someMethod:@{a : @\"b\"}];\n"
18413                "}",
18414                AllmanBraceStyle);
18415   verifyFormat("int f()\n"
18416                "{ // comment\n"
18417                "  return 42;\n"
18418                "}",
18419                AllmanBraceStyle);
18420 
18421   AllmanBraceStyle.ColumnLimit = 19;
18422   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18423   AllmanBraceStyle.ColumnLimit = 18;
18424   verifyFormat("void f()\n"
18425                "{\n"
18426                "  int i;\n"
18427                "}",
18428                AllmanBraceStyle);
18429   AllmanBraceStyle.ColumnLimit = 80;
18430 
18431   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18432   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18433       FormatStyle::SIS_WithoutElse;
18434   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18435   verifyFormat("void f(bool b)\n"
18436                "{\n"
18437                "  if (b)\n"
18438                "  {\n"
18439                "    return;\n"
18440                "  }\n"
18441                "}\n",
18442                BreakBeforeBraceShortIfs);
18443   verifyFormat("void f(bool b)\n"
18444                "{\n"
18445                "  if constexpr (b)\n"
18446                "  {\n"
18447                "    return;\n"
18448                "  }\n"
18449                "}\n",
18450                BreakBeforeBraceShortIfs);
18451   verifyFormat("void f(bool b)\n"
18452                "{\n"
18453                "  if CONSTEXPR (b)\n"
18454                "  {\n"
18455                "    return;\n"
18456                "  }\n"
18457                "}\n",
18458                BreakBeforeBraceShortIfs);
18459   verifyFormat("void f(bool b)\n"
18460                "{\n"
18461                "  if (b) return;\n"
18462                "}\n",
18463                BreakBeforeBraceShortIfs);
18464   verifyFormat("void f(bool b)\n"
18465                "{\n"
18466                "  if constexpr (b) return;\n"
18467                "}\n",
18468                BreakBeforeBraceShortIfs);
18469   verifyFormat("void f(bool b)\n"
18470                "{\n"
18471                "  if CONSTEXPR (b) return;\n"
18472                "}\n",
18473                BreakBeforeBraceShortIfs);
18474   verifyFormat("void f(bool b)\n"
18475                "{\n"
18476                "  while (b)\n"
18477                "  {\n"
18478                "    return;\n"
18479                "  }\n"
18480                "}\n",
18481                BreakBeforeBraceShortIfs);
18482 }
18483 
18484 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18485   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18486   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18487 
18488   // Make a few changes to the style for testing purposes
18489   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18490       FormatStyle::SFS_Empty;
18491   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18492 
18493   // FIXME: this test case can't decide whether there should be a blank line
18494   // after the ~D() line or not. It adds one if one doesn't exist in the test
18495   // and it removes the line if one exists.
18496   /*
18497   verifyFormat("class A;\n"
18498                "namespace B\n"
18499                "  {\n"
18500                "class C;\n"
18501                "// Comment\n"
18502                "class D\n"
18503                "  {\n"
18504                "public:\n"
18505                "  D();\n"
18506                "  ~D() {}\n"
18507                "private:\n"
18508                "  enum E\n"
18509                "    {\n"
18510                "    F\n"
18511                "    }\n"
18512                "  };\n"
18513                "  } // namespace B\n",
18514                WhitesmithsBraceStyle);
18515   */
18516 
18517   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18518   verifyFormat("namespace a\n"
18519                "  {\n"
18520                "class A\n"
18521                "  {\n"
18522                "  void f()\n"
18523                "    {\n"
18524                "    if (true)\n"
18525                "      {\n"
18526                "      a();\n"
18527                "      b();\n"
18528                "      }\n"
18529                "    }\n"
18530                "  void g()\n"
18531                "    {\n"
18532                "    return;\n"
18533                "    }\n"
18534                "  };\n"
18535                "struct B\n"
18536                "  {\n"
18537                "  int x;\n"
18538                "  };\n"
18539                "  } // namespace a",
18540                WhitesmithsBraceStyle);
18541 
18542   verifyFormat("namespace a\n"
18543                "  {\n"
18544                "namespace b\n"
18545                "  {\n"
18546                "class A\n"
18547                "  {\n"
18548                "  void f()\n"
18549                "    {\n"
18550                "    if (true)\n"
18551                "      {\n"
18552                "      a();\n"
18553                "      b();\n"
18554                "      }\n"
18555                "    }\n"
18556                "  void g()\n"
18557                "    {\n"
18558                "    return;\n"
18559                "    }\n"
18560                "  };\n"
18561                "struct B\n"
18562                "  {\n"
18563                "  int x;\n"
18564                "  };\n"
18565                "  } // namespace b\n"
18566                "  } // namespace a",
18567                WhitesmithsBraceStyle);
18568 
18569   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18570   verifyFormat("namespace a\n"
18571                "  {\n"
18572                "namespace b\n"
18573                "  {\n"
18574                "  class A\n"
18575                "    {\n"
18576                "    void f()\n"
18577                "      {\n"
18578                "      if (true)\n"
18579                "        {\n"
18580                "        a();\n"
18581                "        b();\n"
18582                "        }\n"
18583                "      }\n"
18584                "    void g()\n"
18585                "      {\n"
18586                "      return;\n"
18587                "      }\n"
18588                "    };\n"
18589                "  struct B\n"
18590                "    {\n"
18591                "    int x;\n"
18592                "    };\n"
18593                "  } // namespace b\n"
18594                "  } // namespace a",
18595                WhitesmithsBraceStyle);
18596 
18597   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18598   verifyFormat("namespace a\n"
18599                "  {\n"
18600                "  namespace b\n"
18601                "    {\n"
18602                "    class A\n"
18603                "      {\n"
18604                "      void f()\n"
18605                "        {\n"
18606                "        if (true)\n"
18607                "          {\n"
18608                "          a();\n"
18609                "          b();\n"
18610                "          }\n"
18611                "        }\n"
18612                "      void g()\n"
18613                "        {\n"
18614                "        return;\n"
18615                "        }\n"
18616                "      };\n"
18617                "    struct B\n"
18618                "      {\n"
18619                "      int x;\n"
18620                "      };\n"
18621                "    } // namespace b\n"
18622                "  }   // namespace a",
18623                WhitesmithsBraceStyle);
18624 
18625   verifyFormat("void f()\n"
18626                "  {\n"
18627                "  if (true)\n"
18628                "    {\n"
18629                "    a();\n"
18630                "    }\n"
18631                "  else if (false)\n"
18632                "    {\n"
18633                "    b();\n"
18634                "    }\n"
18635                "  else\n"
18636                "    {\n"
18637                "    c();\n"
18638                "    }\n"
18639                "  }\n",
18640                WhitesmithsBraceStyle);
18641 
18642   verifyFormat("void f()\n"
18643                "  {\n"
18644                "  for (int i = 0; i < 10; ++i)\n"
18645                "    {\n"
18646                "    a();\n"
18647                "    }\n"
18648                "  while (false)\n"
18649                "    {\n"
18650                "    b();\n"
18651                "    }\n"
18652                "  do\n"
18653                "    {\n"
18654                "    c();\n"
18655                "    } while (false)\n"
18656                "  }\n",
18657                WhitesmithsBraceStyle);
18658 
18659   WhitesmithsBraceStyle.IndentCaseLabels = true;
18660   verifyFormat("void switchTest1(int a)\n"
18661                "  {\n"
18662                "  switch (a)\n"
18663                "    {\n"
18664                "    case 2:\n"
18665                "      {\n"
18666                "      }\n"
18667                "      break;\n"
18668                "    }\n"
18669                "  }\n",
18670                WhitesmithsBraceStyle);
18671 
18672   verifyFormat("void switchTest2(int a)\n"
18673                "  {\n"
18674                "  switch (a)\n"
18675                "    {\n"
18676                "    case 0:\n"
18677                "      break;\n"
18678                "    case 1:\n"
18679                "      {\n"
18680                "      break;\n"
18681                "      }\n"
18682                "    case 2:\n"
18683                "      {\n"
18684                "      }\n"
18685                "      break;\n"
18686                "    default:\n"
18687                "      break;\n"
18688                "    }\n"
18689                "  }\n",
18690                WhitesmithsBraceStyle);
18691 
18692   verifyFormat("void switchTest3(int a)\n"
18693                "  {\n"
18694                "  switch (a)\n"
18695                "    {\n"
18696                "    case 0:\n"
18697                "      {\n"
18698                "      foo(x);\n"
18699                "      }\n"
18700                "      break;\n"
18701                "    default:\n"
18702                "      {\n"
18703                "      foo(1);\n"
18704                "      }\n"
18705                "      break;\n"
18706                "    }\n"
18707                "  }\n",
18708                WhitesmithsBraceStyle);
18709 
18710   WhitesmithsBraceStyle.IndentCaseLabels = false;
18711 
18712   verifyFormat("void switchTest4(int a)\n"
18713                "  {\n"
18714                "  switch (a)\n"
18715                "    {\n"
18716                "  case 2:\n"
18717                "    {\n"
18718                "    }\n"
18719                "    break;\n"
18720                "    }\n"
18721                "  }\n",
18722                WhitesmithsBraceStyle);
18723 
18724   verifyFormat("void switchTest5(int a)\n"
18725                "  {\n"
18726                "  switch (a)\n"
18727                "    {\n"
18728                "  case 0:\n"
18729                "    break;\n"
18730                "  case 1:\n"
18731                "    {\n"
18732                "    foo();\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 switchTest6(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   verifyFormat("enum X\n"
18764                "  {\n"
18765                "  Y = 0, // testing\n"
18766                "  }\n",
18767                WhitesmithsBraceStyle);
18768 
18769   verifyFormat("enum X\n"
18770                "  {\n"
18771                "  Y = 0\n"
18772                "  }\n",
18773                WhitesmithsBraceStyle);
18774   verifyFormat("enum X\n"
18775                "  {\n"
18776                "  Y = 0,\n"
18777                "  Z = 1\n"
18778                "  };\n",
18779                WhitesmithsBraceStyle);
18780 
18781   verifyFormat("@interface BSApplicationController ()\n"
18782                "  {\n"
18783                "@private\n"
18784                "  id _extraIvar;\n"
18785                "  }\n"
18786                "@end\n",
18787                WhitesmithsBraceStyle);
18788 
18789   verifyFormat("#ifdef _DEBUG\n"
18790                "int foo(int i = 0)\n"
18791                "#else\n"
18792                "int foo(int i = 5)\n"
18793                "#endif\n"
18794                "  {\n"
18795                "  return i;\n"
18796                "  }",
18797                WhitesmithsBraceStyle);
18798 
18799   verifyFormat("void foo() {}\n"
18800                "void bar()\n"
18801                "#ifdef _DEBUG\n"
18802                "  {\n"
18803                "  foo();\n"
18804                "  }\n"
18805                "#else\n"
18806                "  {\n"
18807                "  }\n"
18808                "#endif",
18809                WhitesmithsBraceStyle);
18810 
18811   verifyFormat("void foobar()\n"
18812                "  {\n"
18813                "  int i = 5;\n"
18814                "  }\n"
18815                "#ifdef _DEBUG\n"
18816                "void bar()\n"
18817                "  {\n"
18818                "  }\n"
18819                "#else\n"
18820                "void bar()\n"
18821                "  {\n"
18822                "  foobar();\n"
18823                "  }\n"
18824                "#endif",
18825                WhitesmithsBraceStyle);
18826 
18827   // This shouldn't affect ObjC blocks..
18828   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18829                "  // ...\n"
18830                "  int i;\n"
18831                "}];",
18832                WhitesmithsBraceStyle);
18833   verifyFormat("void (^block)(void) = ^{\n"
18834                "  // ...\n"
18835                "  int i;\n"
18836                "};",
18837                WhitesmithsBraceStyle);
18838   // .. or dict literals.
18839   verifyFormat("void f()\n"
18840                "  {\n"
18841                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18842                "  }",
18843                WhitesmithsBraceStyle);
18844 
18845   verifyFormat("int f()\n"
18846                "  { // comment\n"
18847                "  return 42;\n"
18848                "  }",
18849                WhitesmithsBraceStyle);
18850 
18851   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18852   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18853       FormatStyle::SIS_OnlyFirstIf;
18854   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18855   verifyFormat("void f(bool b)\n"
18856                "  {\n"
18857                "  if (b)\n"
18858                "    {\n"
18859                "    return;\n"
18860                "    }\n"
18861                "  }\n",
18862                BreakBeforeBraceShortIfs);
18863   verifyFormat("void f(bool b)\n"
18864                "  {\n"
18865                "  if (b) return;\n"
18866                "  }\n",
18867                BreakBeforeBraceShortIfs);
18868   verifyFormat("void f(bool b)\n"
18869                "  {\n"
18870                "  while (b)\n"
18871                "    {\n"
18872                "    return;\n"
18873                "    }\n"
18874                "  }\n",
18875                BreakBeforeBraceShortIfs);
18876 }
18877 
18878 TEST_F(FormatTest, GNUBraceBreaking) {
18879   FormatStyle GNUBraceStyle = getLLVMStyle();
18880   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
18881   verifyFormat("namespace a\n"
18882                "{\n"
18883                "class A\n"
18884                "{\n"
18885                "  void f()\n"
18886                "  {\n"
18887                "    int a;\n"
18888                "    {\n"
18889                "      int b;\n"
18890                "    }\n"
18891                "    if (true)\n"
18892                "      {\n"
18893                "        a();\n"
18894                "        b();\n"
18895                "      }\n"
18896                "  }\n"
18897                "  void g() { return; }\n"
18898                "}\n"
18899                "} // namespace a",
18900                GNUBraceStyle);
18901 
18902   verifyFormat("void f()\n"
18903                "{\n"
18904                "  if (true)\n"
18905                "    {\n"
18906                "      a();\n"
18907                "    }\n"
18908                "  else if (false)\n"
18909                "    {\n"
18910                "      b();\n"
18911                "    }\n"
18912                "  else\n"
18913                "    {\n"
18914                "      c();\n"
18915                "    }\n"
18916                "}\n",
18917                GNUBraceStyle);
18918 
18919   verifyFormat("void f()\n"
18920                "{\n"
18921                "  for (int i = 0; i < 10; ++i)\n"
18922                "    {\n"
18923                "      a();\n"
18924                "    }\n"
18925                "  while (false)\n"
18926                "    {\n"
18927                "      b();\n"
18928                "    }\n"
18929                "  do\n"
18930                "    {\n"
18931                "      c();\n"
18932                "    }\n"
18933                "  while (false);\n"
18934                "}\n",
18935                GNUBraceStyle);
18936 
18937   verifyFormat("void f(int a)\n"
18938                "{\n"
18939                "  switch (a)\n"
18940                "    {\n"
18941                "    case 0:\n"
18942                "      break;\n"
18943                "    case 1:\n"
18944                "      {\n"
18945                "        break;\n"
18946                "      }\n"
18947                "    case 2:\n"
18948                "      {\n"
18949                "      }\n"
18950                "      break;\n"
18951                "    default:\n"
18952                "      break;\n"
18953                "    }\n"
18954                "}\n",
18955                GNUBraceStyle);
18956 
18957   verifyFormat("enum X\n"
18958                "{\n"
18959                "  Y = 0,\n"
18960                "}\n",
18961                GNUBraceStyle);
18962 
18963   verifyFormat("@interface BSApplicationController ()\n"
18964                "{\n"
18965                "@private\n"
18966                "  id _extraIvar;\n"
18967                "}\n"
18968                "@end\n",
18969                GNUBraceStyle);
18970 
18971   verifyFormat("#ifdef _DEBUG\n"
18972                "int foo(int i = 0)\n"
18973                "#else\n"
18974                "int foo(int i = 5)\n"
18975                "#endif\n"
18976                "{\n"
18977                "  return i;\n"
18978                "}",
18979                GNUBraceStyle);
18980 
18981   verifyFormat("void foo() {}\n"
18982                "void bar()\n"
18983                "#ifdef _DEBUG\n"
18984                "{\n"
18985                "  foo();\n"
18986                "}\n"
18987                "#else\n"
18988                "{\n"
18989                "}\n"
18990                "#endif",
18991                GNUBraceStyle);
18992 
18993   verifyFormat("void foobar() { int i = 5; }\n"
18994                "#ifdef _DEBUG\n"
18995                "void bar() {}\n"
18996                "#else\n"
18997                "void bar() { foobar(); }\n"
18998                "#endif",
18999                GNUBraceStyle);
19000 }
19001 
19002 TEST_F(FormatTest, WebKitBraceBreaking) {
19003   FormatStyle WebKitBraceStyle = getLLVMStyle();
19004   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
19005   WebKitBraceStyle.FixNamespaceComments = false;
19006   verifyFormat("namespace a {\n"
19007                "class A {\n"
19008                "  void f()\n"
19009                "  {\n"
19010                "    if (true) {\n"
19011                "      a();\n"
19012                "      b();\n"
19013                "    }\n"
19014                "  }\n"
19015                "  void g() { return; }\n"
19016                "};\n"
19017                "enum E {\n"
19018                "  A,\n"
19019                "  // foo\n"
19020                "  B,\n"
19021                "  C\n"
19022                "};\n"
19023                "struct B {\n"
19024                "  int x;\n"
19025                "};\n"
19026                "}\n",
19027                WebKitBraceStyle);
19028   verifyFormat("struct S {\n"
19029                "  int Type;\n"
19030                "  union {\n"
19031                "    int x;\n"
19032                "    double y;\n"
19033                "  } Value;\n"
19034                "  class C {\n"
19035                "    MyFavoriteType Value;\n"
19036                "  } Class;\n"
19037                "};\n",
19038                WebKitBraceStyle);
19039 }
19040 
19041 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
19042   verifyFormat("void f() {\n"
19043                "  try {\n"
19044                "  } catch (const Exception &e) {\n"
19045                "  }\n"
19046                "}\n",
19047                getLLVMStyle());
19048 }
19049 
19050 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
19051   auto Style = getLLVMStyle();
19052   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19053   Style.AlignConsecutiveAssignments.Enabled = true;
19054   Style.AlignConsecutiveDeclarations.Enabled = true;
19055   verifyFormat("struct test demo[] = {\n"
19056                "    {56,    23, \"hello\"},\n"
19057                "    {-1, 93463, \"world\"},\n"
19058                "    { 7,     5,    \"!!\"}\n"
19059                "};\n",
19060                Style);
19061 
19062   verifyFormat("struct test demo[] = {\n"
19063                "    {56,    23, \"hello\"}, // first line\n"
19064                "    {-1, 93463, \"world\"}, // second line\n"
19065                "    { 7,     5,    \"!!\"}  // third line\n"
19066                "};\n",
19067                Style);
19068 
19069   verifyFormat("struct test demo[4] = {\n"
19070                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19071                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19072                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19073                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19074                "};\n",
19075                Style);
19076 
19077   verifyFormat("struct test demo[3] = {\n"
19078                "    {56,    23, \"hello\"},\n"
19079                "    {-1, 93463, \"world\"},\n"
19080                "    { 7,     5,    \"!!\"}\n"
19081                "};\n",
19082                Style);
19083 
19084   verifyFormat("struct test demo[3] = {\n"
19085                "    {int{56},    23, \"hello\"},\n"
19086                "    {int{-1}, 93463, \"world\"},\n"
19087                "    { int{7},     5,    \"!!\"}\n"
19088                "};\n",
19089                Style);
19090 
19091   verifyFormat("struct test demo[] = {\n"
19092                "    {56,    23, \"hello\"},\n"
19093                "    {-1, 93463, \"world\"},\n"
19094                "    { 7,     5,    \"!!\"},\n"
19095                "};\n",
19096                Style);
19097 
19098   verifyFormat("test demo[] = {\n"
19099                "    {56,    23, \"hello\"},\n"
19100                "    {-1, 93463, \"world\"},\n"
19101                "    { 7,     5,    \"!!\"},\n"
19102                "};\n",
19103                Style);
19104 
19105   verifyFormat("demo = std::array<struct test, 3>{\n"
19106                "    test{56,    23, \"hello\"},\n"
19107                "    test{-1, 93463, \"world\"},\n"
19108                "    test{ 7,     5,    \"!!\"},\n"
19109                "};\n",
19110                Style);
19111 
19112   verifyFormat("test demo[] = {\n"
19113                "    {56,    23, \"hello\"},\n"
19114                "#if X\n"
19115                "    {-1, 93463, \"world\"},\n"
19116                "#endif\n"
19117                "    { 7,     5,    \"!!\"}\n"
19118                "};\n",
19119                Style);
19120 
19121   verifyFormat(
19122       "test demo[] = {\n"
19123       "    { 7,    23,\n"
19124       "     \"hello world i am a very long line that really, in any\"\n"
19125       "     \"just world, ought to be split over multiple lines\"},\n"
19126       "    {-1, 93463,                                  \"world\"},\n"
19127       "    {56,     5,                                     \"!!\"}\n"
19128       "};\n",
19129       Style);
19130 
19131   verifyFormat("return GradForUnaryCwise(g, {\n"
19132                "                                {{\"sign\"}, \"Sign\",  "
19133                "  {\"x\", \"dy\"}},\n"
19134                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
19135                ", \"sign\"}},\n"
19136                "});\n",
19137                Style);
19138 
19139   Style.ColumnLimit = 0;
19140   EXPECT_EQ(
19141       "test demo[] = {\n"
19142       "    {56,    23, \"hello world i am a very long line that really, "
19143       "in any just world, ought to be split over multiple lines\"},\n"
19144       "    {-1, 93463,                                                  "
19145       "                                                 \"world\"},\n"
19146       "    { 7,     5,                                                  "
19147       "                                                    \"!!\"},\n"
19148       "};",
19149       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19150              "that really, in any just world, ought to be split over multiple "
19151              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19152              Style));
19153 
19154   Style.ColumnLimit = 80;
19155   verifyFormat("test demo[] = {\n"
19156                "    {56,    23, /* a comment */ \"hello\"},\n"
19157                "    {-1, 93463,                 \"world\"},\n"
19158                "    { 7,     5,                    \"!!\"}\n"
19159                "};\n",
19160                Style);
19161 
19162   verifyFormat("test demo[] = {\n"
19163                "    {56,    23,                    \"hello\"},\n"
19164                "    {-1, 93463, \"world\" /* comment here */},\n"
19165                "    { 7,     5,                       \"!!\"}\n"
19166                "};\n",
19167                Style);
19168 
19169   verifyFormat("test demo[] = {\n"
19170                "    {56, /* a comment */ 23, \"hello\"},\n"
19171                "    {-1,              93463, \"world\"},\n"
19172                "    { 7,                  5,    \"!!\"}\n"
19173                "};\n",
19174                Style);
19175 
19176   Style.ColumnLimit = 20;
19177   EXPECT_EQ(
19178       "demo = std::array<\n"
19179       "    struct test, 3>{\n"
19180       "    test{\n"
19181       "         56,    23,\n"
19182       "         \"hello \"\n"
19183       "         \"world i \"\n"
19184       "         \"am a very \"\n"
19185       "         \"long line \"\n"
19186       "         \"that \"\n"
19187       "         \"really, \"\n"
19188       "         \"in any \"\n"
19189       "         \"just \"\n"
19190       "         \"world, \"\n"
19191       "         \"ought to \"\n"
19192       "         \"be split \"\n"
19193       "         \"over \"\n"
19194       "         \"multiple \"\n"
19195       "         \"lines\"},\n"
19196       "    test{-1, 93463,\n"
19197       "         \"world\"},\n"
19198       "    test{ 7,     5,\n"
19199       "         \"!!\"   },\n"
19200       "};",
19201       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19202              "i am a very long line that really, in any just world, ought "
19203              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19204              "test{7, 5, \"!!\"},};",
19205              Style));
19206   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19207   Style = getLLVMStyleWithColumns(50);
19208   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19209   verifyFormat("static A x = {\n"
19210                "    {{init1, init2, init3, init4},\n"
19211                "     {init1, init2, init3, init4}}\n"
19212                "};",
19213                Style);
19214   // TODO: Fix the indentations below when this option is fully functional.
19215   verifyFormat("int a[][] = {\n"
19216                "    {\n"
19217                "     {0, 2}, //\n"
19218                " {1, 2}  //\n"
19219                "    }\n"
19220                "};",
19221                Style);
19222   Style.ColumnLimit = 100;
19223   EXPECT_EQ(
19224       "test demo[] = {\n"
19225       "    {56,    23,\n"
19226       "     \"hello world i am a very long line that really, in any just world"
19227       ", ought to be split over \"\n"
19228       "     \"multiple lines\"  },\n"
19229       "    {-1, 93463, \"world\"},\n"
19230       "    { 7,     5,    \"!!\"},\n"
19231       "};",
19232       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19233              "that really, in any just world, ought to be split over multiple "
19234              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19235              Style));
19236 
19237   Style = getLLVMStyleWithColumns(50);
19238   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19239   verifyFormat("struct test demo[] = {\n"
19240                "    {56,    23, \"hello\"},\n"
19241                "    {-1, 93463, \"world\"},\n"
19242                "    { 7,     5,    \"!!\"}\n"
19243                "};\n"
19244                "static A x = {\n"
19245                "    {{init1, init2, init3, init4},\n"
19246                "     {init1, init2, init3, init4}}\n"
19247                "};",
19248                Style);
19249   Style.ColumnLimit = 100;
19250   Style.AlignConsecutiveAssignments.AcrossComments = true;
19251   Style.AlignConsecutiveDeclarations.AcrossComments = true;
19252   verifyFormat("struct test demo[] = {\n"
19253                "    {56,    23, \"hello\"},\n"
19254                "    {-1, 93463, \"world\"},\n"
19255                "    { 7,     5,    \"!!\"}\n"
19256                "};\n"
19257                "struct test demo[4] = {\n"
19258                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19259                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19260                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19261                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19262                "};\n",
19263                Style);
19264   EXPECT_EQ(
19265       "test demo[] = {\n"
19266       "    {56,\n"
19267       "     \"hello world i am a very long line that really, in any just world"
19268       ", ought to be split over \"\n"
19269       "     \"multiple lines\",    23},\n"
19270       "    {-1,      \"world\", 93463},\n"
19271       "    { 7,         \"!!\",     5},\n"
19272       "};",
19273       format("test demo[] = {{56, \"hello world i am a very long line "
19274              "that really, in any just world, ought to be split over multiple "
19275              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
19276              Style));
19277 }
19278 
19279 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
19280   auto Style = getLLVMStyle();
19281   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19282   /* FIXME: This case gets misformatted.
19283   verifyFormat("auto foo = Items{\n"
19284                "    Section{0, bar(), },\n"
19285                "    Section{1, boo()  }\n"
19286                "};\n",
19287                Style);
19288   */
19289   verifyFormat("auto foo = Items{\n"
19290                "    Section{\n"
19291                "            0, bar(),\n"
19292                "            }\n"
19293                "};\n",
19294                Style);
19295   verifyFormat("struct test demo[] = {\n"
19296                "    {56, 23,    \"hello\"},\n"
19297                "    {-1, 93463, \"world\"},\n"
19298                "    {7,  5,     \"!!\"   }\n"
19299                "};\n",
19300                Style);
19301   verifyFormat("struct test demo[] = {\n"
19302                "    {56, 23,    \"hello\"}, // first line\n"
19303                "    {-1, 93463, \"world\"}, // second line\n"
19304                "    {7,  5,     \"!!\"   }  // third line\n"
19305                "};\n",
19306                Style);
19307   verifyFormat("struct test demo[4] = {\n"
19308                "    {56,  23,    21, \"oh\"      }, // first line\n"
19309                "    {-1,  93463, 22, \"my\"      }, // second line\n"
19310                "    {7,   5,     1,  \"goodness\"}  // third line\n"
19311                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
19312                "};\n",
19313                Style);
19314   verifyFormat("struct test demo[3] = {\n"
19315                "    {56, 23,    \"hello\"},\n"
19316                "    {-1, 93463, \"world\"},\n"
19317                "    {7,  5,     \"!!\"   }\n"
19318                "};\n",
19319                Style);
19320 
19321   verifyFormat("struct test demo[3] = {\n"
19322                "    {int{56}, 23,    \"hello\"},\n"
19323                "    {int{-1}, 93463, \"world\"},\n"
19324                "    {int{7},  5,     \"!!\"   }\n"
19325                "};\n",
19326                Style);
19327   verifyFormat("struct test demo[] = {\n"
19328                "    {56, 23,    \"hello\"},\n"
19329                "    {-1, 93463, \"world\"},\n"
19330                "    {7,  5,     \"!!\"   },\n"
19331                "};\n",
19332                Style);
19333   verifyFormat("test demo[] = {\n"
19334                "    {56, 23,    \"hello\"},\n"
19335                "    {-1, 93463, \"world\"},\n"
19336                "    {7,  5,     \"!!\"   },\n"
19337                "};\n",
19338                Style);
19339   verifyFormat("demo = std::array<struct test, 3>{\n"
19340                "    test{56, 23,    \"hello\"},\n"
19341                "    test{-1, 93463, \"world\"},\n"
19342                "    test{7,  5,     \"!!\"   },\n"
19343                "};\n",
19344                Style);
19345   verifyFormat("test demo[] = {\n"
19346                "    {56, 23,    \"hello\"},\n"
19347                "#if X\n"
19348                "    {-1, 93463, \"world\"},\n"
19349                "#endif\n"
19350                "    {7,  5,     \"!!\"   }\n"
19351                "};\n",
19352                Style);
19353   verifyFormat(
19354       "test demo[] = {\n"
19355       "    {7,  23,\n"
19356       "     \"hello world i am a very long line that really, in any\"\n"
19357       "     \"just world, ought to be split over multiple lines\"},\n"
19358       "    {-1, 93463, \"world\"                                 },\n"
19359       "    {56, 5,     \"!!\"                                    }\n"
19360       "};\n",
19361       Style);
19362 
19363   verifyFormat("return GradForUnaryCwise(g, {\n"
19364                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19365                "\"dy\"}   },\n"
19366                "                                {{\"dx\"},   \"Mul\",  "
19367                "{\"dy\", \"sign\"}},\n"
19368                "});\n",
19369                Style);
19370 
19371   Style.ColumnLimit = 0;
19372   EXPECT_EQ(
19373       "test demo[] = {\n"
19374       "    {56, 23,    \"hello world i am a very long line that really, in any "
19375       "just world, ought to be split over multiple lines\"},\n"
19376       "    {-1, 93463, \"world\"                                               "
19377       "                                                   },\n"
19378       "    {7,  5,     \"!!\"                                                  "
19379       "                                                   },\n"
19380       "};",
19381       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19382              "that really, in any just world, ought to be split over multiple "
19383              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19384              Style));
19385 
19386   Style.ColumnLimit = 80;
19387   verifyFormat("test demo[] = {\n"
19388                "    {56, 23,    /* a comment */ \"hello\"},\n"
19389                "    {-1, 93463, \"world\"                },\n"
19390                "    {7,  5,     \"!!\"                   }\n"
19391                "};\n",
19392                Style);
19393 
19394   verifyFormat("test demo[] = {\n"
19395                "    {56, 23,    \"hello\"                   },\n"
19396                "    {-1, 93463, \"world\" /* comment here */},\n"
19397                "    {7,  5,     \"!!\"                      }\n"
19398                "};\n",
19399                Style);
19400 
19401   verifyFormat("test demo[] = {\n"
19402                "    {56, /* a comment */ 23, \"hello\"},\n"
19403                "    {-1, 93463,              \"world\"},\n"
19404                "    {7,  5,                  \"!!\"   }\n"
19405                "};\n",
19406                Style);
19407 
19408   Style.ColumnLimit = 20;
19409   EXPECT_EQ(
19410       "demo = std::array<\n"
19411       "    struct test, 3>{\n"
19412       "    test{\n"
19413       "         56, 23,\n"
19414       "         \"hello \"\n"
19415       "         \"world i \"\n"
19416       "         \"am a very \"\n"
19417       "         \"long line \"\n"
19418       "         \"that \"\n"
19419       "         \"really, \"\n"
19420       "         \"in any \"\n"
19421       "         \"just \"\n"
19422       "         \"world, \"\n"
19423       "         \"ought to \"\n"
19424       "         \"be split \"\n"
19425       "         \"over \"\n"
19426       "         \"multiple \"\n"
19427       "         \"lines\"},\n"
19428       "    test{-1, 93463,\n"
19429       "         \"world\"},\n"
19430       "    test{7,  5,\n"
19431       "         \"!!\"   },\n"
19432       "};",
19433       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19434              "i am a very long line that really, in any just world, ought "
19435              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19436              "test{7, 5, \"!!\"},};",
19437              Style));
19438 
19439   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19440   Style = getLLVMStyleWithColumns(50);
19441   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19442   verifyFormat("static A x = {\n"
19443                "    {{init1, init2, init3, init4},\n"
19444                "     {init1, init2, init3, init4}}\n"
19445                "};",
19446                Style);
19447   Style.ColumnLimit = 100;
19448   EXPECT_EQ(
19449       "test demo[] = {\n"
19450       "    {56, 23,\n"
19451       "     \"hello world i am a very long line that really, in any just world"
19452       ", ought to be split over \"\n"
19453       "     \"multiple lines\"  },\n"
19454       "    {-1, 93463, \"world\"},\n"
19455       "    {7,  5,     \"!!\"   },\n"
19456       "};",
19457       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19458              "that really, in any just world, ought to be split over multiple "
19459              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19460              Style));
19461 }
19462 
19463 TEST_F(FormatTest, UnderstandsPragmas) {
19464   verifyFormat("#pragma omp reduction(| : var)");
19465   verifyFormat("#pragma omp reduction(+ : var)");
19466 
19467   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19468             "(including parentheses).",
19469             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19470                    "(including parentheses)."));
19471 }
19472 
19473 TEST_F(FormatTest, UnderstandPragmaOption) {
19474   verifyFormat("#pragma option -C -A");
19475 
19476   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19477 }
19478 
19479 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19480   FormatStyle Style = getLLVMStyleWithColumns(20);
19481 
19482   // See PR41213
19483   EXPECT_EQ("/*\n"
19484             " *\t9012345\n"
19485             " * /8901\n"
19486             " */",
19487             format("/*\n"
19488                    " *\t9012345 /8901\n"
19489                    " */",
19490                    Style));
19491   EXPECT_EQ("/*\n"
19492             " *345678\n"
19493             " *\t/8901\n"
19494             " */",
19495             format("/*\n"
19496                    " *345678\t/8901\n"
19497                    " */",
19498                    Style));
19499 
19500   verifyFormat("int a; // the\n"
19501                "       // comment",
19502                Style);
19503   EXPECT_EQ("int a; /* first line\n"
19504             "        * second\n"
19505             "        * line third\n"
19506             "        * line\n"
19507             "        */",
19508             format("int a; /* first line\n"
19509                    "        * second\n"
19510                    "        * line third\n"
19511                    "        * line\n"
19512                    "        */",
19513                    Style));
19514   EXPECT_EQ("int a; // first line\n"
19515             "       // second\n"
19516             "       // line third\n"
19517             "       // line",
19518             format("int a; // first line\n"
19519                    "       // second line\n"
19520                    "       // third line",
19521                    Style));
19522 
19523   Style.PenaltyExcessCharacter = 90;
19524   verifyFormat("int a; // the comment", Style);
19525   EXPECT_EQ("int a; // the comment\n"
19526             "       // aaa",
19527             format("int a; // the comment aaa", Style));
19528   EXPECT_EQ("int a; /* first line\n"
19529             "        * second line\n"
19530             "        * third line\n"
19531             "        */",
19532             format("int a; /* first line\n"
19533                    "        * second line\n"
19534                    "        * third line\n"
19535                    "        */",
19536                    Style));
19537   EXPECT_EQ("int a; // first line\n"
19538             "       // second line\n"
19539             "       // third line",
19540             format("int a; // first line\n"
19541                    "       // second line\n"
19542                    "       // third line",
19543                    Style));
19544   // FIXME: Investigate why this is not getting the same layout as the test
19545   // above.
19546   EXPECT_EQ("int a; /* first line\n"
19547             "        * second line\n"
19548             "        * third line\n"
19549             "        */",
19550             format("int a; /* first line second line third line"
19551                    "\n*/",
19552                    Style));
19553 
19554   EXPECT_EQ("// foo bar baz bazfoo\n"
19555             "// foo bar foo bar\n",
19556             format("// foo bar baz bazfoo\n"
19557                    "// foo bar foo           bar\n",
19558                    Style));
19559   EXPECT_EQ("// foo bar baz bazfoo\n"
19560             "// foo bar foo bar\n",
19561             format("// foo bar baz      bazfoo\n"
19562                    "// foo            bar foo bar\n",
19563                    Style));
19564 
19565   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19566   // next one.
19567   EXPECT_EQ("// foo bar baz bazfoo\n"
19568             "// bar foo bar\n",
19569             format("// foo bar baz      bazfoo bar\n"
19570                    "// foo            bar\n",
19571                    Style));
19572 
19573   EXPECT_EQ("// foo bar baz bazfoo\n"
19574             "// foo bar baz bazfoo\n"
19575             "// bar foo bar\n",
19576             format("// foo bar baz      bazfoo\n"
19577                    "// foo bar baz      bazfoo bar\n"
19578                    "// foo bar\n",
19579                    Style));
19580 
19581   EXPECT_EQ("// foo bar baz bazfoo\n"
19582             "// foo bar baz bazfoo\n"
19583             "// bar foo bar\n",
19584             format("// foo bar baz      bazfoo\n"
19585                    "// foo bar baz      bazfoo bar\n"
19586                    "// foo           bar\n",
19587                    Style));
19588 
19589   // Make sure we do not keep protruding characters if strict mode reflow is
19590   // cheaper than keeping protruding characters.
19591   Style.ColumnLimit = 21;
19592   EXPECT_EQ(
19593       "// foo foo foo foo\n"
19594       "// foo foo foo foo\n"
19595       "// foo foo foo foo\n",
19596       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19597 
19598   EXPECT_EQ("int a = /* long block\n"
19599             "           comment */\n"
19600             "    42;",
19601             format("int a = /* long block comment */ 42;", Style));
19602 }
19603 
19604 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19605   FormatStyle Style = getLLVMStyle();
19606   Style.ColumnLimit = 8;
19607   Style.PenaltyExcessCharacter = 15;
19608   verifyFormat("int foo(\n"
19609                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19610                Style);
19611   Style.PenaltyBreakOpenParenthesis = 200;
19612   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19613             format("int foo(\n"
19614                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19615                    Style));
19616 }
19617 
19618 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19619   FormatStyle Style = getLLVMStyle();
19620   Style.ColumnLimit = 5;
19621   Style.PenaltyExcessCharacter = 150;
19622   verifyFormat("foo((\n"
19623                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19624 
19625                Style);
19626   Style.PenaltyBreakOpenParenthesis = 100000;
19627   EXPECT_EQ("foo((int)\n"
19628             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19629             format("foo((\n"
19630                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19631                    Style));
19632 }
19633 
19634 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19635   FormatStyle Style = getLLVMStyle();
19636   Style.ColumnLimit = 4;
19637   Style.PenaltyExcessCharacter = 100;
19638   verifyFormat("for (\n"
19639                "    int iiiiiiiiiiiiiiiii =\n"
19640                "        0;\n"
19641                "    iiiiiiiiiiiiiiiii <\n"
19642                "    2;\n"
19643                "    iiiiiiiiiiiiiiiii++) {\n"
19644                "}",
19645 
19646                Style);
19647   Style.PenaltyBreakOpenParenthesis = 1250;
19648   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19649             "         0;\n"
19650             "     iiiiiiiiiiiiiiiii <\n"
19651             "     2;\n"
19652             "     iiiiiiiiiiiiiiiii++) {\n"
19653             "}",
19654             format("for (\n"
19655                    "    int iiiiiiiiiiiiiiiii =\n"
19656                    "        0;\n"
19657                    "    iiiiiiiiiiiiiiiii <\n"
19658                    "    2;\n"
19659                    "    iiiiiiiiiiiiiiiii++) {\n"
19660                    "}",
19661                    Style));
19662 }
19663 
19664 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19665   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19666   EXPECT_EQ(Styles[0], Styles[i])                                              \
19667       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19668 
19669 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19670   SmallVector<FormatStyle, 3> Styles;
19671   Styles.resize(3);
19672 
19673   Styles[0] = getLLVMStyle();
19674   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19675   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19676   EXPECT_ALL_STYLES_EQUAL(Styles);
19677 
19678   Styles[0] = getGoogleStyle();
19679   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19680   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19681   EXPECT_ALL_STYLES_EQUAL(Styles);
19682 
19683   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19684   EXPECT_TRUE(
19685       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19686   EXPECT_TRUE(
19687       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19688   EXPECT_ALL_STYLES_EQUAL(Styles);
19689 
19690   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19691   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19692   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19693   EXPECT_ALL_STYLES_EQUAL(Styles);
19694 
19695   Styles[0] = getMozillaStyle();
19696   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19697   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19698   EXPECT_ALL_STYLES_EQUAL(Styles);
19699 
19700   Styles[0] = getWebKitStyle();
19701   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19702   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19703   EXPECT_ALL_STYLES_EQUAL(Styles);
19704 
19705   Styles[0] = getGNUStyle();
19706   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19707   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19708   EXPECT_ALL_STYLES_EQUAL(Styles);
19709 
19710   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19711 }
19712 
19713 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19714   SmallVector<FormatStyle, 8> Styles;
19715   Styles.resize(2);
19716 
19717   Styles[0] = getGoogleStyle();
19718   Styles[1] = getLLVMStyle();
19719   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19720   EXPECT_ALL_STYLES_EQUAL(Styles);
19721 
19722   Styles.resize(5);
19723   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19724   Styles[1] = getLLVMStyle();
19725   Styles[1].Language = FormatStyle::LK_JavaScript;
19726   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19727 
19728   Styles[2] = getLLVMStyle();
19729   Styles[2].Language = FormatStyle::LK_JavaScript;
19730   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19731                                   "BasedOnStyle: Google",
19732                                   &Styles[2])
19733                    .value());
19734 
19735   Styles[3] = getLLVMStyle();
19736   Styles[3].Language = FormatStyle::LK_JavaScript;
19737   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19738                                   "Language: JavaScript",
19739                                   &Styles[3])
19740                    .value());
19741 
19742   Styles[4] = getLLVMStyle();
19743   Styles[4].Language = FormatStyle::LK_JavaScript;
19744   EXPECT_EQ(0, parseConfiguration("---\n"
19745                                   "BasedOnStyle: LLVM\n"
19746                                   "IndentWidth: 123\n"
19747                                   "---\n"
19748                                   "BasedOnStyle: Google\n"
19749                                   "Language: JavaScript",
19750                                   &Styles[4])
19751                    .value());
19752   EXPECT_ALL_STYLES_EQUAL(Styles);
19753 }
19754 
19755 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
19756   Style.FIELD = false;                                                         \
19757   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
19758   EXPECT_TRUE(Style.FIELD);                                                    \
19759   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
19760   EXPECT_FALSE(Style.FIELD);
19761 
19762 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
19763 
19764 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
19765   Style.STRUCT.FIELD = false;                                                  \
19766   EXPECT_EQ(0,                                                                 \
19767             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
19768                 .value());                                                     \
19769   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
19770   EXPECT_EQ(0,                                                                 \
19771             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
19772                 .value());                                                     \
19773   EXPECT_FALSE(Style.STRUCT.FIELD);
19774 
19775 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
19776   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
19777 
19778 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
19779   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
19780   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
19781   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
19782 
19783 TEST_F(FormatTest, ParsesConfigurationBools) {
19784   FormatStyle Style = {};
19785   Style.Language = FormatStyle::LK_Cpp;
19786   CHECK_PARSE_BOOL(AlignTrailingComments);
19787   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
19788   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
19789   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
19790   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
19791   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
19792   CHECK_PARSE_BOOL(BinPackArguments);
19793   CHECK_PARSE_BOOL(BinPackParameters);
19794   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
19795   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
19796   CHECK_PARSE_BOOL(BreakStringLiterals);
19797   CHECK_PARSE_BOOL(CompactNamespaces);
19798   CHECK_PARSE_BOOL(DeriveLineEnding);
19799   CHECK_PARSE_BOOL(DerivePointerAlignment);
19800   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
19801   CHECK_PARSE_BOOL(DisableFormat);
19802   CHECK_PARSE_BOOL(IndentAccessModifiers);
19803   CHECK_PARSE_BOOL(IndentCaseLabels);
19804   CHECK_PARSE_BOOL(IndentCaseBlocks);
19805   CHECK_PARSE_BOOL(IndentGotoLabels);
19806   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
19807   CHECK_PARSE_BOOL(IndentRequiresClause);
19808   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
19809   CHECK_PARSE_BOOL(InsertBraces);
19810   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
19811   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
19812   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
19813   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
19814   CHECK_PARSE_BOOL(ReflowComments);
19815   CHECK_PARSE_BOOL(RemoveBracesLLVM);
19816   CHECK_PARSE_BOOL(SortUsingDeclarations);
19817   CHECK_PARSE_BOOL(SpacesInParentheses);
19818   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
19819   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
19820   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
19821   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
19822   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
19823   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19824   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19825   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19826   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19827   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19828   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19829   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19830   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19831   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19832   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19833   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19834   CHECK_PARSE_BOOL(UseCRLF);
19835 
19836   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19837   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19838   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19839   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19840   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19841   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19842   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19843   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19844   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19845   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19846   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19847   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19848   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19849   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19850   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19851   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19852   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19853   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19854   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19855   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19856                           AfterFunctionDeclarationName);
19857   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19858                           AfterFunctionDefinitionName);
19859   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19860   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19861   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19862 }
19863 
19864 #undef CHECK_PARSE_BOOL
19865 
19866 TEST_F(FormatTest, ParsesConfiguration) {
19867   FormatStyle Style = {};
19868   Style.Language = FormatStyle::LK_Cpp;
19869   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19870   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19871               ConstructorInitializerIndentWidth, 1234u);
19872   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19873   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19874   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19875   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19876   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19877               PenaltyBreakBeforeFirstCallParameter, 1234u);
19878   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
19879               PenaltyBreakTemplateDeclaration, 1234u);
19880   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
19881               1234u);
19882   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
19883   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
19884               PenaltyReturnTypeOnItsOwnLine, 1234u);
19885   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
19886               SpacesBeforeTrailingComments, 1234u);
19887   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
19888   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
19889   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
19890 
19891   Style.QualifierAlignment = FormatStyle::QAS_Right;
19892   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
19893               FormatStyle::QAS_Leave);
19894   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
19895               FormatStyle::QAS_Right);
19896   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
19897               FormatStyle::QAS_Left);
19898   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
19899               FormatStyle::QAS_Custom);
19900 
19901   Style.QualifierOrder.clear();
19902   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
19903               std::vector<std::string>({"const", "volatile", "type"}));
19904   Style.QualifierOrder.clear();
19905   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
19906               std::vector<std::string>({"const", "type"}));
19907   Style.QualifierOrder.clear();
19908   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
19909               std::vector<std::string>({"volatile", "type"}));
19910 
19911 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
19912   do {                                                                         \
19913     Style.FIELD.Enabled = true;                                                \
19914     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
19915                 FormatStyle::AlignConsecutiveStyle(                            \
19916                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19917                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19918                      /*PadOperators=*/true}));                                 \
19919     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
19920                 FormatStyle::AlignConsecutiveStyle(                            \
19921                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19922                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19923                      /*PadOperators=*/true}));                                 \
19924     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
19925                 FormatStyle::AlignConsecutiveStyle(                            \
19926                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19927                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19928                      /*PadOperators=*/true}));                                 \
19929     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
19930                 FormatStyle::AlignConsecutiveStyle(                            \
19931                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
19932                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
19933                      /*PadOperators=*/true}));                                 \
19934     /* For backwards compability, false / true should still parse */           \
19935     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
19936                 FormatStyle::AlignConsecutiveStyle(                            \
19937                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
19938                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19939                      /*PadOperators=*/true}));                                 \
19940     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
19941                 FormatStyle::AlignConsecutiveStyle(                            \
19942                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
19943                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
19944                      /*PadOperators=*/true}));                                 \
19945                                                                                \
19946     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
19947     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
19948     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
19949     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
19950     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
19951   } while (false)
19952 
19953   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
19954   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
19955   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
19956   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
19957 
19958 #undef CHECK_ALIGN_CONSECUTIVE
19959 
19960   Style.PointerAlignment = FormatStyle::PAS_Middle;
19961   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
19962               FormatStyle::PAS_Left);
19963   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
19964               FormatStyle::PAS_Right);
19965   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
19966               FormatStyle::PAS_Middle);
19967   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
19968   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
19969               FormatStyle::RAS_Pointer);
19970   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
19971               FormatStyle::RAS_Left);
19972   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
19973               FormatStyle::RAS_Right);
19974   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
19975               FormatStyle::RAS_Middle);
19976   // For backward compatibility:
19977   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
19978               FormatStyle::PAS_Left);
19979   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
19980               FormatStyle::PAS_Right);
19981   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
19982               FormatStyle::PAS_Middle);
19983 
19984   Style.Standard = FormatStyle::LS_Auto;
19985   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
19986   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
19987   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
19988   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
19989   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
19990   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
19991   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
19992   // Legacy aliases:
19993   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
19994   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
19995   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
19996   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
19997 
19998   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
19999   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
20000               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
20001   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
20002               FormatStyle::BOS_None);
20003   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
20004               FormatStyle::BOS_All);
20005   // For backward compatibility:
20006   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
20007               FormatStyle::BOS_None);
20008   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
20009               FormatStyle::BOS_All);
20010 
20011   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20012   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
20013               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20014   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
20015               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
20016   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
20017               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
20018   // For backward compatibility:
20019   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
20020               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20021 
20022   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
20023   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
20024               FormatStyle::BILS_AfterComma);
20025   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
20026               FormatStyle::BILS_BeforeComma);
20027   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
20028               FormatStyle::BILS_AfterColon);
20029   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
20030               FormatStyle::BILS_BeforeColon);
20031   // For backward compatibility:
20032   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
20033               FormatStyle::BILS_BeforeComma);
20034 
20035   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20036   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
20037               FormatStyle::PCIS_Never);
20038   CHECK_PARSE("PackConstructorInitializers: BinPack",
20039               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20040   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
20041               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20042   CHECK_PARSE("PackConstructorInitializers: NextLine",
20043               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20044   // For backward compatibility:
20045   CHECK_PARSE("BasedOnStyle: Google\n"
20046               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20047               "AllowAllConstructorInitializersOnNextLine: false",
20048               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20049   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20050   CHECK_PARSE("BasedOnStyle: Google\n"
20051               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
20052               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20053   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20054               "AllowAllConstructorInitializersOnNextLine: true",
20055               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20056   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20057   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20058               "AllowAllConstructorInitializersOnNextLine: false",
20059               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20060 
20061   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
20062   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
20063               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
20064   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
20065               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
20066   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
20067               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
20068   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
20069               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
20070 
20071   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20072   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
20073               FormatStyle::BAS_Align);
20074   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
20075               FormatStyle::BAS_DontAlign);
20076   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
20077               FormatStyle::BAS_AlwaysBreak);
20078   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
20079               FormatStyle::BAS_BlockIndent);
20080   // For backward compatibility:
20081   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
20082               FormatStyle::BAS_DontAlign);
20083   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
20084               FormatStyle::BAS_Align);
20085 
20086   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
20087   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
20088               FormatStyle::ENAS_DontAlign);
20089   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
20090               FormatStyle::ENAS_Left);
20091   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
20092               FormatStyle::ENAS_Right);
20093   // For backward compatibility:
20094   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
20095               FormatStyle::ENAS_Left);
20096   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
20097               FormatStyle::ENAS_Right);
20098 
20099   Style.AlignOperands = FormatStyle::OAS_Align;
20100   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
20101               FormatStyle::OAS_DontAlign);
20102   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
20103   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
20104               FormatStyle::OAS_AlignAfterOperator);
20105   // For backward compatibility:
20106   CHECK_PARSE("AlignOperands: false", AlignOperands,
20107               FormatStyle::OAS_DontAlign);
20108   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
20109 
20110   Style.UseTab = FormatStyle::UT_ForIndentation;
20111   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
20112   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
20113   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
20114   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
20115               FormatStyle::UT_ForContinuationAndIndentation);
20116   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
20117               FormatStyle::UT_AlignWithSpaces);
20118   // For backward compatibility:
20119   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
20120   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
20121 
20122   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
20123   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
20124               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20125   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
20126               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
20127   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
20128               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20129   // For backward compatibility:
20130   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
20131               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20132   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
20133               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20134 
20135   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
20136   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
20137               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20138   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
20139               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
20140   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
20141               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
20142   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
20143               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20144   // For backward compatibility:
20145   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
20146               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20147   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
20148               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20149 
20150   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
20151   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
20152               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
20153   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
20154               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
20155   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
20156               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
20157   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
20158               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
20159 
20160   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20161   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
20162               FormatStyle::SBPO_Never);
20163   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
20164               FormatStyle::SBPO_Always);
20165   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
20166               FormatStyle::SBPO_ControlStatements);
20167   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
20168               SpaceBeforeParens,
20169               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20170   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
20171               FormatStyle::SBPO_NonEmptyParentheses);
20172   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
20173               FormatStyle::SBPO_Custom);
20174   // For backward compatibility:
20175   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
20176               FormatStyle::SBPO_Never);
20177   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
20178               FormatStyle::SBPO_ControlStatements);
20179   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
20180               SpaceBeforeParens,
20181               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20182 
20183   Style.ColumnLimit = 123;
20184   FormatStyle BaseStyle = getLLVMStyle();
20185   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
20186   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
20187 
20188   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
20189   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
20190               FormatStyle::BS_Attach);
20191   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
20192               FormatStyle::BS_Linux);
20193   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
20194               FormatStyle::BS_Mozilla);
20195   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
20196               FormatStyle::BS_Stroustrup);
20197   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
20198               FormatStyle::BS_Allman);
20199   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
20200               FormatStyle::BS_Whitesmiths);
20201   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
20202   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
20203               FormatStyle::BS_WebKit);
20204   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
20205               FormatStyle::BS_Custom);
20206 
20207   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
20208   CHECK_PARSE("BraceWrapping:\n"
20209               "  AfterControlStatement: MultiLine",
20210               BraceWrapping.AfterControlStatement,
20211               FormatStyle::BWACS_MultiLine);
20212   CHECK_PARSE("BraceWrapping:\n"
20213               "  AfterControlStatement: Always",
20214               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20215   CHECK_PARSE("BraceWrapping:\n"
20216               "  AfterControlStatement: Never",
20217               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20218   // For backward compatibility:
20219   CHECK_PARSE("BraceWrapping:\n"
20220               "  AfterControlStatement: true",
20221               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20222   CHECK_PARSE("BraceWrapping:\n"
20223               "  AfterControlStatement: false",
20224               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20225 
20226   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
20227   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
20228               FormatStyle::RTBS_None);
20229   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
20230               FormatStyle::RTBS_All);
20231   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
20232               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
20233   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
20234               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
20235   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
20236               AlwaysBreakAfterReturnType,
20237               FormatStyle::RTBS_TopLevelDefinitions);
20238 
20239   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20240   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
20241               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
20242   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
20243               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20244   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
20245               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20246   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
20247               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20248   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
20249               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20250 
20251   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
20252   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
20253               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
20254   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
20255               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
20256   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
20257               AlwaysBreakAfterDefinitionReturnType,
20258               FormatStyle::DRTBS_TopLevel);
20259 
20260   Style.NamespaceIndentation = FormatStyle::NI_All;
20261   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
20262               FormatStyle::NI_None);
20263   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
20264               FormatStyle::NI_Inner);
20265   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
20266               FormatStyle::NI_All);
20267 
20268   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
20269   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
20270               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20271   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
20272               AllowShortIfStatementsOnASingleLine,
20273               FormatStyle::SIS_WithoutElse);
20274   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
20275               AllowShortIfStatementsOnASingleLine,
20276               FormatStyle::SIS_OnlyFirstIf);
20277   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
20278               AllowShortIfStatementsOnASingleLine,
20279               FormatStyle::SIS_AllIfsAndElse);
20280   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
20281               AllowShortIfStatementsOnASingleLine,
20282               FormatStyle::SIS_OnlyFirstIf);
20283   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
20284               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20285   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
20286               AllowShortIfStatementsOnASingleLine,
20287               FormatStyle::SIS_WithoutElse);
20288 
20289   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
20290   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
20291               FormatStyle::IEBS_AfterExternBlock);
20292   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
20293               FormatStyle::IEBS_Indent);
20294   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
20295               FormatStyle::IEBS_NoIndent);
20296   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
20297               FormatStyle::IEBS_Indent);
20298   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20299               FormatStyle::IEBS_NoIndent);
20300 
20301   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20302   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20303               FormatStyle::BFCS_Both);
20304   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20305               FormatStyle::BFCS_None);
20306   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20307               FormatStyle::BFCS_Before);
20308   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20309               FormatStyle::BFCS_After);
20310 
20311   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20312   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20313               FormatStyle::SJSIO_After);
20314   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20315               FormatStyle::SJSIO_Before);
20316 
20317   // FIXME: This is required because parsing a configuration simply overwrites
20318   // the first N elements of the list instead of resetting it.
20319   Style.ForEachMacros.clear();
20320   std::vector<std::string> BoostForeach;
20321   BoostForeach.push_back("BOOST_FOREACH");
20322   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20323   std::vector<std::string> BoostAndQForeach;
20324   BoostAndQForeach.push_back("BOOST_FOREACH");
20325   BoostAndQForeach.push_back("Q_FOREACH");
20326   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20327               BoostAndQForeach);
20328 
20329   Style.IfMacros.clear();
20330   std::vector<std::string> CustomIfs;
20331   CustomIfs.push_back("MYIF");
20332   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20333 
20334   Style.AttributeMacros.clear();
20335   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20336               std::vector<std::string>{"__capability"});
20337   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20338               std::vector<std::string>({"attr1", "attr2"}));
20339 
20340   Style.StatementAttributeLikeMacros.clear();
20341   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20342               StatementAttributeLikeMacros,
20343               std::vector<std::string>({"emit", "Q_EMIT"}));
20344 
20345   Style.StatementMacros.clear();
20346   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20347               std::vector<std::string>{"QUNUSED"});
20348   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20349               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20350 
20351   Style.NamespaceMacros.clear();
20352   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20353               std::vector<std::string>{"TESTSUITE"});
20354   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20355               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20356 
20357   Style.WhitespaceSensitiveMacros.clear();
20358   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20359               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20360   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20361               WhitespaceSensitiveMacros,
20362               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20363   Style.WhitespaceSensitiveMacros.clear();
20364   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20365               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20366   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20367               WhitespaceSensitiveMacros,
20368               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20369 
20370   Style.IncludeStyle.IncludeCategories.clear();
20371   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20372       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20373   CHECK_PARSE("IncludeCategories:\n"
20374               "  - Regex: abc/.*\n"
20375               "    Priority: 2\n"
20376               "  - Regex: .*\n"
20377               "    Priority: 1\n"
20378               "    CaseSensitive: true\n",
20379               IncludeStyle.IncludeCategories, ExpectedCategories);
20380   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20381               "abc$");
20382   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20383               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20384 
20385   Style.SortIncludes = FormatStyle::SI_Never;
20386   CHECK_PARSE("SortIncludes: true", SortIncludes,
20387               FormatStyle::SI_CaseSensitive);
20388   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20389   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20390               FormatStyle::SI_CaseInsensitive);
20391   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20392               FormatStyle::SI_CaseSensitive);
20393   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20394 
20395   Style.RawStringFormats.clear();
20396   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20397       {
20398           FormatStyle::LK_TextProto,
20399           {"pb", "proto"},
20400           {"PARSE_TEXT_PROTO"},
20401           /*CanonicalDelimiter=*/"",
20402           "llvm",
20403       },
20404       {
20405           FormatStyle::LK_Cpp,
20406           {"cc", "cpp"},
20407           {"C_CODEBLOCK", "CPPEVAL"},
20408           /*CanonicalDelimiter=*/"cc",
20409           /*BasedOnStyle=*/"",
20410       },
20411   };
20412 
20413   CHECK_PARSE("RawStringFormats:\n"
20414               "  - Language: TextProto\n"
20415               "    Delimiters:\n"
20416               "      - 'pb'\n"
20417               "      - 'proto'\n"
20418               "    EnclosingFunctions:\n"
20419               "      - 'PARSE_TEXT_PROTO'\n"
20420               "    BasedOnStyle: llvm\n"
20421               "  - Language: Cpp\n"
20422               "    Delimiters:\n"
20423               "      - 'cc'\n"
20424               "      - 'cpp'\n"
20425               "    EnclosingFunctions:\n"
20426               "      - 'C_CODEBLOCK'\n"
20427               "      - 'CPPEVAL'\n"
20428               "    CanonicalDelimiter: 'cc'",
20429               RawStringFormats, ExpectedRawStringFormats);
20430 
20431   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20432               "  Minimum: 0\n"
20433               "  Maximum: 0",
20434               SpacesInLineCommentPrefix.Minimum, 0u);
20435   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20436   Style.SpacesInLineCommentPrefix.Minimum = 1;
20437   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20438               "  Minimum: 2",
20439               SpacesInLineCommentPrefix.Minimum, 0u);
20440   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20441               "  Maximum: -1",
20442               SpacesInLineCommentPrefix.Maximum, -1u);
20443   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20444               "  Minimum: 2",
20445               SpacesInLineCommentPrefix.Minimum, 2u);
20446   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20447               "  Maximum: 1",
20448               SpacesInLineCommentPrefix.Maximum, 1u);
20449   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20450 
20451   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20452   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20453   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20454               FormatStyle::SIAS_Always);
20455   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20456   // For backward compatibility:
20457   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20458   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20459 
20460   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20461               FormatStyle::RCPS_WithPreceding);
20462   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20463               FormatStyle::RCPS_WithFollowing);
20464   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20465               FormatStyle::RCPS_SingleLine);
20466   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20467               FormatStyle::RCPS_OwnLine);
20468 
20469   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20470               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20471   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20472               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20473   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20474               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20475   // For backward compatibility:
20476   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20477               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20478   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20479               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20480 }
20481 
20482 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20483   FormatStyle Style = {};
20484   Style.Language = FormatStyle::LK_Cpp;
20485   CHECK_PARSE("Language: Cpp\n"
20486               "IndentWidth: 12",
20487               IndentWidth, 12u);
20488   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20489                                "IndentWidth: 34",
20490                                &Style),
20491             ParseError::Unsuitable);
20492   FormatStyle BinPackedTCS = {};
20493   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20494   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20495                                "InsertTrailingCommas: Wrapped",
20496                                &BinPackedTCS),
20497             ParseError::BinPackTrailingCommaConflict);
20498   EXPECT_EQ(12u, Style.IndentWidth);
20499   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20500   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20501 
20502   Style.Language = FormatStyle::LK_JavaScript;
20503   CHECK_PARSE("Language: JavaScript\n"
20504               "IndentWidth: 12",
20505               IndentWidth, 12u);
20506   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20507   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20508                                "IndentWidth: 34",
20509                                &Style),
20510             ParseError::Unsuitable);
20511   EXPECT_EQ(23u, Style.IndentWidth);
20512   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20513   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20514 
20515   CHECK_PARSE("BasedOnStyle: LLVM\n"
20516               "IndentWidth: 67",
20517               IndentWidth, 67u);
20518 
20519   CHECK_PARSE("---\n"
20520               "Language: JavaScript\n"
20521               "IndentWidth: 12\n"
20522               "---\n"
20523               "Language: Cpp\n"
20524               "IndentWidth: 34\n"
20525               "...\n",
20526               IndentWidth, 12u);
20527 
20528   Style.Language = FormatStyle::LK_Cpp;
20529   CHECK_PARSE("---\n"
20530               "Language: JavaScript\n"
20531               "IndentWidth: 12\n"
20532               "---\n"
20533               "Language: Cpp\n"
20534               "IndentWidth: 34\n"
20535               "...\n",
20536               IndentWidth, 34u);
20537   CHECK_PARSE("---\n"
20538               "IndentWidth: 78\n"
20539               "---\n"
20540               "Language: JavaScript\n"
20541               "IndentWidth: 56\n"
20542               "...\n",
20543               IndentWidth, 78u);
20544 
20545   Style.ColumnLimit = 123;
20546   Style.IndentWidth = 234;
20547   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20548   Style.TabWidth = 345;
20549   EXPECT_FALSE(parseConfiguration("---\n"
20550                                   "IndentWidth: 456\n"
20551                                   "BreakBeforeBraces: Allman\n"
20552                                   "---\n"
20553                                   "Language: JavaScript\n"
20554                                   "IndentWidth: 111\n"
20555                                   "TabWidth: 111\n"
20556                                   "---\n"
20557                                   "Language: Cpp\n"
20558                                   "BreakBeforeBraces: Stroustrup\n"
20559                                   "TabWidth: 789\n"
20560                                   "...\n",
20561                                   &Style));
20562   EXPECT_EQ(123u, Style.ColumnLimit);
20563   EXPECT_EQ(456u, Style.IndentWidth);
20564   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20565   EXPECT_EQ(789u, Style.TabWidth);
20566 
20567   EXPECT_EQ(parseConfiguration("---\n"
20568                                "Language: JavaScript\n"
20569                                "IndentWidth: 56\n"
20570                                "---\n"
20571                                "IndentWidth: 78\n"
20572                                "...\n",
20573                                &Style),
20574             ParseError::Error);
20575   EXPECT_EQ(parseConfiguration("---\n"
20576                                "Language: JavaScript\n"
20577                                "IndentWidth: 56\n"
20578                                "---\n"
20579                                "Language: JavaScript\n"
20580                                "IndentWidth: 78\n"
20581                                "...\n",
20582                                &Style),
20583             ParseError::Error);
20584 
20585   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20586 }
20587 
20588 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20589   FormatStyle Style = {};
20590   Style.Language = FormatStyle::LK_JavaScript;
20591   Style.BreakBeforeTernaryOperators = true;
20592   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20593   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20594 
20595   Style.BreakBeforeTernaryOperators = true;
20596   EXPECT_EQ(0, parseConfiguration("---\n"
20597                                   "BasedOnStyle: Google\n"
20598                                   "---\n"
20599                                   "Language: JavaScript\n"
20600                                   "IndentWidth: 76\n"
20601                                   "...\n",
20602                                   &Style)
20603                    .value());
20604   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20605   EXPECT_EQ(76u, Style.IndentWidth);
20606   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20607 }
20608 
20609 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20610   FormatStyle Style = getLLVMStyle();
20611   std::string YAML = configurationAsText(Style);
20612   FormatStyle ParsedStyle = {};
20613   ParsedStyle.Language = FormatStyle::LK_Cpp;
20614   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20615   EXPECT_EQ(Style, ParsedStyle);
20616 }
20617 
20618 TEST_F(FormatTest, WorksFor8bitEncodings) {
20619   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20620             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20621             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20622             "\"\xef\xee\xf0\xf3...\"",
20623             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20624                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20625                    "\xef\xee\xf0\xf3...\"",
20626                    getLLVMStyleWithColumns(12)));
20627 }
20628 
20629 TEST_F(FormatTest, HandlesUTF8BOM) {
20630   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20631   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20632             format("\xef\xbb\xbf#include <iostream>"));
20633   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20634             format("\xef\xbb\xbf\n#include <iostream>"));
20635 }
20636 
20637 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20638 #if !defined(_MSC_VER)
20639 
20640 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20641   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20642                getLLVMStyleWithColumns(35));
20643   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20644                getLLVMStyleWithColumns(31));
20645   verifyFormat("// Однажды в студёную зимнюю пору...",
20646                getLLVMStyleWithColumns(36));
20647   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20648   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20649                getLLVMStyleWithColumns(39));
20650   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20651                getLLVMStyleWithColumns(35));
20652 }
20653 
20654 TEST_F(FormatTest, SplitsUTF8Strings) {
20655   // Non-printable characters' width is currently considered to be the length in
20656   // bytes in UTF8. The characters can be displayed in very different manner
20657   // (zero-width, single width with a substitution glyph, expanded to their code
20658   // (e.g. "<8d>"), so there's no single correct way to handle them.
20659   EXPECT_EQ("\"aaaaÄ\"\n"
20660             "\"\xc2\x8d\";",
20661             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20662   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20663             "\"\xc2\x8d\";",
20664             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20665   EXPECT_EQ("\"Однажды, в \"\n"
20666             "\"студёную \"\n"
20667             "\"зимнюю \"\n"
20668             "\"пору,\"",
20669             format("\"Однажды, в студёную зимнюю пору,\"",
20670                    getLLVMStyleWithColumns(13)));
20671   EXPECT_EQ(
20672       "\"一 二 三 \"\n"
20673       "\"四 五六 \"\n"
20674       "\"七 八 九 \"\n"
20675       "\"十\"",
20676       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20677   EXPECT_EQ("\"一\t\"\n"
20678             "\"二 \t\"\n"
20679             "\"三 四 \"\n"
20680             "\"五\t\"\n"
20681             "\"六 \t\"\n"
20682             "\"七 \"\n"
20683             "\"八九十\tqq\"",
20684             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20685                    getLLVMStyleWithColumns(11)));
20686 
20687   // UTF8 character in an escape sequence.
20688   EXPECT_EQ("\"aaaaaa\"\n"
20689             "\"\\\xC2\x8D\"",
20690             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20691 }
20692 
20693 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20694   EXPECT_EQ("const char *sssss =\n"
20695             "    \"一二三四五六七八\\\n"
20696             " 九 十\";",
20697             format("const char *sssss = \"一二三四五六七八\\\n"
20698                    " 九 十\";",
20699                    getLLVMStyleWithColumns(30)));
20700 }
20701 
20702 TEST_F(FormatTest, SplitsUTF8LineComments) {
20703   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20704             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20705   EXPECT_EQ("// Я из лесу\n"
20706             "// вышел; был\n"
20707             "// сильный\n"
20708             "// мороз.",
20709             format("// Я из лесу вышел; был сильный мороз.",
20710                    getLLVMStyleWithColumns(13)));
20711   EXPECT_EQ("// 一二三\n"
20712             "// 四五六七\n"
20713             "// 八  九\n"
20714             "// 十",
20715             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20716 }
20717 
20718 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20719   EXPECT_EQ("/* Гляжу,\n"
20720             " * поднимается\n"
20721             " * медленно в\n"
20722             " * гору\n"
20723             " * Лошадка,\n"
20724             " * везущая\n"
20725             " * хворосту\n"
20726             " * воз. */",
20727             format("/* Гляжу, поднимается медленно в гору\n"
20728                    " * Лошадка, везущая хворосту воз. */",
20729                    getLLVMStyleWithColumns(13)));
20730   EXPECT_EQ(
20731       "/* 一二三\n"
20732       " * 四五六七\n"
20733       " * 八  九\n"
20734       " * 十  */",
20735       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20736   EXPECT_EQ("/* �������� ��������\n"
20737             " * ��������\n"
20738             " * ������-�� */",
20739             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20740 }
20741 
20742 #endif // _MSC_VER
20743 
20744 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
20745   FormatStyle Style = getLLVMStyle();
20746 
20747   Style.ConstructorInitializerIndentWidth = 4;
20748   verifyFormat(
20749       "SomeClass::Constructor()\n"
20750       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20751       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20752       Style);
20753 
20754   Style.ConstructorInitializerIndentWidth = 2;
20755   verifyFormat(
20756       "SomeClass::Constructor()\n"
20757       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20758       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20759       Style);
20760 
20761   Style.ConstructorInitializerIndentWidth = 0;
20762   verifyFormat(
20763       "SomeClass::Constructor()\n"
20764       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20765       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20766       Style);
20767   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20768   verifyFormat(
20769       "SomeLongTemplateVariableName<\n"
20770       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
20771       Style);
20772   verifyFormat("bool smaller = 1 < "
20773                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
20774                "                       "
20775                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
20776                Style);
20777 
20778   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
20779   verifyFormat("SomeClass::Constructor() :\n"
20780                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
20781                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
20782                Style);
20783 }
20784 
20785 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
20786   FormatStyle Style = getLLVMStyle();
20787   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20788   Style.ConstructorInitializerIndentWidth = 4;
20789   verifyFormat("SomeClass::Constructor()\n"
20790                "    : a(a)\n"
20791                "    , b(b)\n"
20792                "    , c(c) {}",
20793                Style);
20794   verifyFormat("SomeClass::Constructor()\n"
20795                "    : a(a) {}",
20796                Style);
20797 
20798   Style.ColumnLimit = 0;
20799   verifyFormat("SomeClass::Constructor()\n"
20800                "    : a(a) {}",
20801                Style);
20802   verifyFormat("SomeClass::Constructor() noexcept\n"
20803                "    : a(a) {}",
20804                Style);
20805   verifyFormat("SomeClass::Constructor()\n"
20806                "    : a(a)\n"
20807                "    , b(b)\n"
20808                "    , c(c) {}",
20809                Style);
20810   verifyFormat("SomeClass::Constructor()\n"
20811                "    : a(a) {\n"
20812                "  foo();\n"
20813                "  bar();\n"
20814                "}",
20815                Style);
20816 
20817   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20818   verifyFormat("SomeClass::Constructor()\n"
20819                "    : a(a)\n"
20820                "    , b(b)\n"
20821                "    , c(c) {\n}",
20822                Style);
20823   verifyFormat("SomeClass::Constructor()\n"
20824                "    : a(a) {\n}",
20825                Style);
20826 
20827   Style.ColumnLimit = 80;
20828   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
20829   Style.ConstructorInitializerIndentWidth = 2;
20830   verifyFormat("SomeClass::Constructor()\n"
20831                "  : a(a)\n"
20832                "  , b(b)\n"
20833                "  , c(c) {}",
20834                Style);
20835 
20836   Style.ConstructorInitializerIndentWidth = 0;
20837   verifyFormat("SomeClass::Constructor()\n"
20838                ": a(a)\n"
20839                ", b(b)\n"
20840                ", c(c) {}",
20841                Style);
20842 
20843   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20844   Style.ConstructorInitializerIndentWidth = 4;
20845   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20846   verifyFormat(
20847       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20848       Style);
20849   verifyFormat(
20850       "SomeClass::Constructor()\n"
20851       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20852       Style);
20853   Style.ConstructorInitializerIndentWidth = 4;
20854   Style.ColumnLimit = 60;
20855   verifyFormat("SomeClass::Constructor()\n"
20856                "    : aaaaaaaa(aaaaaaaa)\n"
20857                "    , aaaaaaaa(aaaaaaaa)\n"
20858                "    , aaaaaaaa(aaaaaaaa) {}",
20859                Style);
20860 }
20861 
20862 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20863   FormatStyle Style = getLLVMStyle();
20864   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20865   Style.ConstructorInitializerIndentWidth = 4;
20866   verifyFormat("SomeClass::Constructor()\n"
20867                "    : a{a}\n"
20868                "    , b{b} {}",
20869                Style);
20870   verifyFormat("SomeClass::Constructor()\n"
20871                "    : a{a}\n"
20872                "#if CONDITION\n"
20873                "    , b{b}\n"
20874                "#endif\n"
20875                "{\n}",
20876                Style);
20877   Style.ConstructorInitializerIndentWidth = 2;
20878   verifyFormat("SomeClass::Constructor()\n"
20879                "#if CONDITION\n"
20880                "  : a{a}\n"
20881                "#endif\n"
20882                "  , b{b}\n"
20883                "  , c{c} {\n}",
20884                Style);
20885   Style.ConstructorInitializerIndentWidth = 0;
20886   verifyFormat("SomeClass::Constructor()\n"
20887                ": a{a}\n"
20888                "#ifdef CONDITION\n"
20889                ", b{b}\n"
20890                "#else\n"
20891                ", c{c}\n"
20892                "#endif\n"
20893                ", d{d} {\n}",
20894                Style);
20895   Style.ConstructorInitializerIndentWidth = 4;
20896   verifyFormat("SomeClass::Constructor()\n"
20897                "    : a{a}\n"
20898                "#if WINDOWS\n"
20899                "#if DEBUG\n"
20900                "    , b{0}\n"
20901                "#else\n"
20902                "    , b{1}\n"
20903                "#endif\n"
20904                "#else\n"
20905                "#if DEBUG\n"
20906                "    , b{2}\n"
20907                "#else\n"
20908                "    , b{3}\n"
20909                "#endif\n"
20910                "#endif\n"
20911                "{\n}",
20912                Style);
20913   verifyFormat("SomeClass::Constructor()\n"
20914                "    : a{a}\n"
20915                "#if WINDOWS\n"
20916                "    , b{0}\n"
20917                "#if DEBUG\n"
20918                "    , c{0}\n"
20919                "#else\n"
20920                "    , c{1}\n"
20921                "#endif\n"
20922                "#else\n"
20923                "#if DEBUG\n"
20924                "    , c{2}\n"
20925                "#else\n"
20926                "    , c{3}\n"
20927                "#endif\n"
20928                "    , b{1}\n"
20929                "#endif\n"
20930                "{\n}",
20931                Style);
20932 }
20933 
20934 TEST_F(FormatTest, Destructors) {
20935   verifyFormat("void F(int &i) { i.~int(); }");
20936   verifyFormat("void F(int &i) { i->~int(); }");
20937 }
20938 
20939 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20940   FormatStyle Style = getWebKitStyle();
20941 
20942   // Don't indent in outer namespaces.
20943   verifyFormat("namespace outer {\n"
20944                "int i;\n"
20945                "namespace inner {\n"
20946                "    int i;\n"
20947                "} // namespace inner\n"
20948                "} // namespace outer\n"
20949                "namespace other_outer {\n"
20950                "int i;\n"
20951                "}",
20952                Style);
20953 
20954   // Don't indent case labels.
20955   verifyFormat("switch (variable) {\n"
20956                "case 1:\n"
20957                "case 2:\n"
20958                "    doSomething();\n"
20959                "    break;\n"
20960                "default:\n"
20961                "    ++variable;\n"
20962                "}",
20963                Style);
20964 
20965   // Wrap before binary operators.
20966   EXPECT_EQ("void f()\n"
20967             "{\n"
20968             "    if (aaaaaaaaaaaaaaaa\n"
20969             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
20970             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20971             "        return;\n"
20972             "}",
20973             format("void f() {\n"
20974                    "if (aaaaaaaaaaaaaaaa\n"
20975                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
20976                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20977                    "return;\n"
20978                    "}",
20979                    Style));
20980 
20981   // Allow functions on a single line.
20982   verifyFormat("void f() { return; }", Style);
20983 
20984   // Allow empty blocks on a single line and insert a space in empty blocks.
20985   EXPECT_EQ("void f() { }", format("void f() {}", Style));
20986   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
20987   // However, don't merge non-empty short loops.
20988   EXPECT_EQ("while (true) {\n"
20989             "    continue;\n"
20990             "}",
20991             format("while (true) { continue; }", Style));
20992 
20993   // Constructor initializers are formatted one per line with the "," on the
20994   // new line.
20995   verifyFormat("Constructor()\n"
20996                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
20997                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
20998                "          aaaaaaaaaaaaaa)\n"
20999                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
21000                "{\n"
21001                "}",
21002                Style);
21003   verifyFormat("SomeClass::Constructor()\n"
21004                "    : a(a)\n"
21005                "{\n"
21006                "}",
21007                Style);
21008   EXPECT_EQ("SomeClass::Constructor()\n"
21009             "    : a(a)\n"
21010             "{\n"
21011             "}",
21012             format("SomeClass::Constructor():a(a){}", Style));
21013   verifyFormat("SomeClass::Constructor()\n"
21014                "    : a(a)\n"
21015                "    , b(b)\n"
21016                "    , c(c)\n"
21017                "{\n"
21018                "}",
21019                Style);
21020   verifyFormat("SomeClass::Constructor()\n"
21021                "    : a(a)\n"
21022                "{\n"
21023                "    foo();\n"
21024                "    bar();\n"
21025                "}",
21026                Style);
21027 
21028   // Access specifiers should be aligned left.
21029   verifyFormat("class C {\n"
21030                "public:\n"
21031                "    int i;\n"
21032                "};",
21033                Style);
21034 
21035   // Do not align comments.
21036   verifyFormat("int a; // Do not\n"
21037                "double b; // align comments.",
21038                Style);
21039 
21040   // Do not align operands.
21041   EXPECT_EQ("ASSERT(aaaa\n"
21042             "    || bbbb);",
21043             format("ASSERT ( aaaa\n||bbbb);", Style));
21044 
21045   // Accept input's line breaks.
21046   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
21047             "    || bbbbbbbbbbbbbbb) {\n"
21048             "    i++;\n"
21049             "}",
21050             format("if (aaaaaaaaaaaaaaa\n"
21051                    "|| bbbbbbbbbbbbbbb) { i++; }",
21052                    Style));
21053   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
21054             "    i++;\n"
21055             "}",
21056             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
21057 
21058   // Don't automatically break all macro definitions (llvm.org/PR17842).
21059   verifyFormat("#define aNumber 10", Style);
21060   // However, generally keep the line breaks that the user authored.
21061   EXPECT_EQ("#define aNumber \\\n"
21062             "    10",
21063             format("#define aNumber \\\n"
21064                    " 10",
21065                    Style));
21066 
21067   // Keep empty and one-element array literals on a single line.
21068   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
21069             "                                  copyItems:YES];",
21070             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
21071                    "copyItems:YES];",
21072                    Style));
21073   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
21074             "                                  copyItems:YES];",
21075             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
21076                    "             copyItems:YES];",
21077                    Style));
21078   // FIXME: This does not seem right, there should be more indentation before
21079   // the array literal's entries. Nested blocks have the same problem.
21080   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21081             "    @\"a\",\n"
21082             "    @\"a\"\n"
21083             "]\n"
21084             "                                  copyItems:YES];",
21085             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21086                    "     @\"a\",\n"
21087                    "     @\"a\"\n"
21088                    "     ]\n"
21089                    "       copyItems:YES];",
21090                    Style));
21091   EXPECT_EQ(
21092       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21093       "                                  copyItems:YES];",
21094       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21095              "   copyItems:YES];",
21096              Style));
21097 
21098   verifyFormat("[self.a b:c c:d];", Style);
21099   EXPECT_EQ("[self.a b:c\n"
21100             "        c:d];",
21101             format("[self.a b:c\n"
21102                    "c:d];",
21103                    Style));
21104 }
21105 
21106 TEST_F(FormatTest, FormatsLambdas) {
21107   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
21108   verifyFormat(
21109       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
21110   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
21111   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
21112   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
21113   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
21114   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
21115   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
21116   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
21117   verifyFormat("int x = f(*+[] {});");
21118   verifyFormat("void f() {\n"
21119                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
21120                "}\n");
21121   verifyFormat("void f() {\n"
21122                "  other(x.begin(), //\n"
21123                "        x.end(),   //\n"
21124                "        [&](int, int) { return 1; });\n"
21125                "}\n");
21126   verifyFormat("void f() {\n"
21127                "  other.other.other.other.other(\n"
21128                "      x.begin(), x.end(),\n"
21129                "      [something, rather](int, int, int, int, int, int, int) { "
21130                "return 1; });\n"
21131                "}\n");
21132   verifyFormat(
21133       "void f() {\n"
21134       "  other.other.other.other.other(\n"
21135       "      x.begin(), x.end(),\n"
21136       "      [something, rather](int, int, int, int, int, int, int) {\n"
21137       "        //\n"
21138       "      });\n"
21139       "}\n");
21140   verifyFormat("SomeFunction([]() { // A cool function...\n"
21141                "  return 43;\n"
21142                "});");
21143   EXPECT_EQ("SomeFunction([]() {\n"
21144             "#define A a\n"
21145             "  return 43;\n"
21146             "});",
21147             format("SomeFunction([](){\n"
21148                    "#define A a\n"
21149                    "return 43;\n"
21150                    "});"));
21151   verifyFormat("void f() {\n"
21152                "  SomeFunction([](decltype(x), A *a) {});\n"
21153                "  SomeFunction([](typeof(x), A *a) {});\n"
21154                "  SomeFunction([](_Atomic(x), A *a) {});\n"
21155                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
21156                "}");
21157   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21158                "    [](const aaaaaaaaaa &a) { return a; });");
21159   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
21160                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
21161                "});");
21162   verifyFormat("Constructor()\n"
21163                "    : Field([] { // comment\n"
21164                "        int i;\n"
21165                "      }) {}");
21166   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
21167                "  return some_parameter.size();\n"
21168                "};");
21169   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
21170                "    [](const string &s) { return s; };");
21171   verifyFormat("int i = aaaaaa ? 1 //\n"
21172                "               : [] {\n"
21173                "                   return 2; //\n"
21174                "                 }();");
21175   verifyFormat("llvm::errs() << \"number of twos is \"\n"
21176                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
21177                "                  return x == 2; // force break\n"
21178                "                });");
21179   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21180                "    [=](int iiiiiiiiiiii) {\n"
21181                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
21182                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
21183                "    });",
21184                getLLVMStyleWithColumns(60));
21185 
21186   verifyFormat("SomeFunction({[&] {\n"
21187                "                // comment\n"
21188                "              },\n"
21189                "              [&] {\n"
21190                "                // comment\n"
21191                "              }});");
21192   verifyFormat("SomeFunction({[&] {\n"
21193                "  // comment\n"
21194                "}});");
21195   verifyFormat(
21196       "virtual aaaaaaaaaaaaaaaa(\n"
21197       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
21198       "    aaaaa aaaaaaaaa);");
21199 
21200   // Lambdas with return types.
21201   verifyFormat("int c = []() -> int { return 2; }();\n");
21202   verifyFormat("int c = []() -> int * { return 2; }();\n");
21203   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
21204   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
21205   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
21206   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
21207   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
21208   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
21209   verifyFormat("[a, a]() -> a<1> {};");
21210   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
21211   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
21212   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
21213   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
21214   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
21215   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
21216   verifyFormat("[]() -> foo<!5> { return {}; };");
21217   verifyFormat("[]() -> foo<~5> { return {}; };");
21218   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
21219   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
21220   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
21221   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
21222   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
21223   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
21224   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
21225   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
21226   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
21227   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
21228   verifyFormat("namespace bar {\n"
21229                "// broken:\n"
21230                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
21231                "} // namespace bar");
21232   verifyFormat("namespace bar {\n"
21233                "// broken:\n"
21234                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
21235                "} // namespace bar");
21236   verifyFormat("namespace bar {\n"
21237                "// broken:\n"
21238                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
21239                "} // namespace bar");
21240   verifyFormat("namespace bar {\n"
21241                "// broken:\n"
21242                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
21243                "} // namespace bar");
21244   verifyFormat("namespace bar {\n"
21245                "// broken:\n"
21246                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
21247                "} // namespace bar");
21248   verifyFormat("namespace bar {\n"
21249                "// broken:\n"
21250                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
21251                "} // namespace bar");
21252   verifyFormat("namespace bar {\n"
21253                "// broken:\n"
21254                "auto foo{[]() -> foo<!5> { return {}; }};\n"
21255                "} // namespace bar");
21256   verifyFormat("namespace bar {\n"
21257                "// broken:\n"
21258                "auto foo{[]() -> foo<~5> { return {}; }};\n"
21259                "} // namespace bar");
21260   verifyFormat("namespace bar {\n"
21261                "// broken:\n"
21262                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
21263                "} // namespace bar");
21264   verifyFormat("namespace bar {\n"
21265                "// broken:\n"
21266                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
21267                "} // namespace bar");
21268   verifyFormat("namespace bar {\n"
21269                "// broken:\n"
21270                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
21271                "} // namespace bar");
21272   verifyFormat("namespace bar {\n"
21273                "// broken:\n"
21274                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
21275                "} // namespace bar");
21276   verifyFormat("namespace bar {\n"
21277                "// broken:\n"
21278                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
21279                "} // namespace bar");
21280   verifyFormat("namespace bar {\n"
21281                "// broken:\n"
21282                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
21283                "} // namespace bar");
21284   verifyFormat("namespace bar {\n"
21285                "// broken:\n"
21286                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
21287                "} // namespace bar");
21288   verifyFormat("namespace bar {\n"
21289                "// broken:\n"
21290                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
21291                "} // namespace bar");
21292   verifyFormat("namespace bar {\n"
21293                "// broken:\n"
21294                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
21295                "} // namespace bar");
21296   verifyFormat("namespace bar {\n"
21297                "// broken:\n"
21298                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21299                "} // namespace bar");
21300   verifyFormat("[]() -> a<1> {};");
21301   verifyFormat("[]() -> a<1> { ; };");
21302   verifyFormat("[]() -> a<1> { ; }();");
21303   verifyFormat("[a, a]() -> a<true> {};");
21304   verifyFormat("[]() -> a<true> {};");
21305   verifyFormat("[]() -> a<true> { ; };");
21306   verifyFormat("[]() -> a<true> { ; }();");
21307   verifyFormat("[a, a]() -> a<false> {};");
21308   verifyFormat("[]() -> a<false> {};");
21309   verifyFormat("[]() -> a<false> { ; };");
21310   verifyFormat("[]() -> a<false> { ; }();");
21311   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21312   verifyFormat("namespace bar {\n"
21313                "auto foo{[]() -> foo<false> { ; }};\n"
21314                "} // namespace bar");
21315   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21316                "                   int j) -> int {\n"
21317                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21318                "};");
21319   verifyFormat(
21320       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21321       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21322       "      return aaaaaaaaaaaaaaaaa;\n"
21323       "    });",
21324       getLLVMStyleWithColumns(70));
21325   verifyFormat("[]() //\n"
21326                "    -> int {\n"
21327                "  return 1; //\n"
21328                "};");
21329   verifyFormat("[]() -> Void<T...> {};");
21330   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21331   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21332   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21333   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21334   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21335   verifyFormat("return int{[x = x]() { return x; }()};");
21336 
21337   // Lambdas with explicit template argument lists.
21338   verifyFormat(
21339       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21340   verifyFormat("auto L = []<class T>(T) {\n"
21341                "  {\n"
21342                "    f();\n"
21343                "    g();\n"
21344                "  }\n"
21345                "};\n");
21346   verifyFormat("auto L = []<class... T>(T...) {\n"
21347                "  {\n"
21348                "    f();\n"
21349                "    g();\n"
21350                "  }\n"
21351                "};\n");
21352   verifyFormat("auto L = []<typename... T>(T...) {\n"
21353                "  {\n"
21354                "    f();\n"
21355                "    g();\n"
21356                "  }\n"
21357                "};\n");
21358   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21359                "  {\n"
21360                "    f();\n"
21361                "    g();\n"
21362                "  }\n"
21363                "};\n");
21364   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21365                "  {\n"
21366                "    f();\n"
21367                "    g();\n"
21368                "  }\n"
21369                "};\n");
21370 
21371   // Multiple lambdas in the same parentheses change indentation rules. These
21372   // lambdas are forced to start on new lines.
21373   verifyFormat("SomeFunction(\n"
21374                "    []() {\n"
21375                "      //\n"
21376                "    },\n"
21377                "    []() {\n"
21378                "      //\n"
21379                "    });");
21380 
21381   // A lambda passed as arg0 is always pushed to the next line.
21382   verifyFormat("SomeFunction(\n"
21383                "    [this] {\n"
21384                "      //\n"
21385                "    },\n"
21386                "    1);\n");
21387 
21388   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21389   // the arg0 case above.
21390   auto Style = getGoogleStyle();
21391   Style.BinPackArguments = false;
21392   verifyFormat("SomeFunction(\n"
21393                "    a,\n"
21394                "    [this] {\n"
21395                "      //\n"
21396                "    },\n"
21397                "    b);\n",
21398                Style);
21399   verifyFormat("SomeFunction(\n"
21400                "    a,\n"
21401                "    [this] {\n"
21402                "      //\n"
21403                "    },\n"
21404                "    b);\n");
21405 
21406   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21407   // the BinPackArguments value (as long as the code is wide enough).
21408   verifyFormat(
21409       "something->SomeFunction(\n"
21410       "    a,\n"
21411       "    [this] {\n"
21412       "      "
21413       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21414       "    },\n"
21415       "    b);\n");
21416 
21417   // A multi-line lambda is pulled up as long as the introducer fits on the
21418   // previous line and there are no further args.
21419   verifyFormat("function(1, [this, that] {\n"
21420                "  //\n"
21421                "});\n");
21422   verifyFormat("function([this, that] {\n"
21423                "  //\n"
21424                "});\n");
21425   // FIXME: this format is not ideal and we should consider forcing the first
21426   // arg onto its own line.
21427   verifyFormat("function(a, b, c, //\n"
21428                "         d, [this, that] {\n"
21429                "           //\n"
21430                "         });\n");
21431 
21432   // Multiple lambdas are treated correctly even when there is a short arg0.
21433   verifyFormat("SomeFunction(\n"
21434                "    1,\n"
21435                "    [this] {\n"
21436                "      //\n"
21437                "    },\n"
21438                "    [this] {\n"
21439                "      //\n"
21440                "    },\n"
21441                "    1);\n");
21442 
21443   // More complex introducers.
21444   verifyFormat("return [i, args...] {};");
21445 
21446   // Not lambdas.
21447   verifyFormat("constexpr char hello[]{\"hello\"};");
21448   verifyFormat("double &operator[](int i) { return 0; }\n"
21449                "int i;");
21450   verifyFormat("std::unique_ptr<int[]> foo() {}");
21451   verifyFormat("int i = a[a][a]->f();");
21452   verifyFormat("int i = (*b)[a]->f();");
21453 
21454   // Other corner cases.
21455   verifyFormat("void f() {\n"
21456                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21457                "  );\n"
21458                "}");
21459 
21460   // Lambdas created through weird macros.
21461   verifyFormat("void f() {\n"
21462                "  MACRO((const AA &a) { return 1; });\n"
21463                "  MACRO((AA &a) { return 1; });\n"
21464                "}");
21465 
21466   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21467                "      doo_dah();\n"
21468                "      doo_dah();\n"
21469                "    })) {\n"
21470                "}");
21471   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21472                "                doo_dah();\n"
21473                "                doo_dah();\n"
21474                "              })) {\n"
21475                "}");
21476   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21477                "                doo_dah();\n"
21478                "                doo_dah();\n"
21479                "              })) {\n"
21480                "}");
21481   verifyFormat("auto lambda = []() {\n"
21482                "  int a = 2\n"
21483                "#if A\n"
21484                "          + 2\n"
21485                "#endif\n"
21486                "      ;\n"
21487                "};");
21488 
21489   // Lambdas with complex multiline introducers.
21490   verifyFormat(
21491       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21492       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21493       "        -> ::std::unordered_set<\n"
21494       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21495       "      //\n"
21496       "    });");
21497 
21498   FormatStyle DoNotMerge = getLLVMStyle();
21499   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21500   verifyFormat("auto c = []() {\n"
21501                "  return b;\n"
21502                "};",
21503                "auto c = []() { return b; };", DoNotMerge);
21504   verifyFormat("auto c = []() {\n"
21505                "};",
21506                " auto c = []() {};", DoNotMerge);
21507 
21508   FormatStyle MergeEmptyOnly = getLLVMStyle();
21509   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21510   verifyFormat("auto c = []() {\n"
21511                "  return b;\n"
21512                "};",
21513                "auto c = []() {\n"
21514                "  return b;\n"
21515                " };",
21516                MergeEmptyOnly);
21517   verifyFormat("auto c = []() {};",
21518                "auto c = []() {\n"
21519                "};",
21520                MergeEmptyOnly);
21521 
21522   FormatStyle MergeInline = getLLVMStyle();
21523   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21524   verifyFormat("auto c = []() {\n"
21525                "  return b;\n"
21526                "};",
21527                "auto c = []() { return b; };", MergeInline);
21528   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21529                MergeInline);
21530   verifyFormat("function([]() { return b; }, a)",
21531                "function([]() { return b; }, a)", MergeInline);
21532   verifyFormat("function(a, []() { return b; })",
21533                "function(a, []() { return b; })", MergeInline);
21534 
21535   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21536   // AllowShortLambdasOnASingleLine
21537   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21538   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21539   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21540   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21541       FormatStyle::ShortLambdaStyle::SLS_None;
21542   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21543                "    []()\n"
21544                "    {\n"
21545                "      return 17;\n"
21546                "    });",
21547                LLVMWithBeforeLambdaBody);
21548   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21549                "    []()\n"
21550                "    {\n"
21551                "    });",
21552                LLVMWithBeforeLambdaBody);
21553   verifyFormat("auto fct_SLS_None = []()\n"
21554                "{\n"
21555                "  return 17;\n"
21556                "};",
21557                LLVMWithBeforeLambdaBody);
21558   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21559                "    []()\n"
21560                "    {\n"
21561                "      return Call(\n"
21562                "          []()\n"
21563                "          {\n"
21564                "            return 17;\n"
21565                "          });\n"
21566                "    });",
21567                LLVMWithBeforeLambdaBody);
21568   verifyFormat("void Fct() {\n"
21569                "  return {[]()\n"
21570                "          {\n"
21571                "            return 17;\n"
21572                "          }};\n"
21573                "}",
21574                LLVMWithBeforeLambdaBody);
21575 
21576   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21577       FormatStyle::ShortLambdaStyle::SLS_Empty;
21578   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21579                "    []()\n"
21580                "    {\n"
21581                "      return 17;\n"
21582                "    });",
21583                LLVMWithBeforeLambdaBody);
21584   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21585                LLVMWithBeforeLambdaBody);
21586   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21587                "ongFunctionName_SLS_Empty(\n"
21588                "    []() {});",
21589                LLVMWithBeforeLambdaBody);
21590   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21591                "                                []()\n"
21592                "                                {\n"
21593                "                                  return 17;\n"
21594                "                                });",
21595                LLVMWithBeforeLambdaBody);
21596   verifyFormat("auto fct_SLS_Empty = []()\n"
21597                "{\n"
21598                "  return 17;\n"
21599                "};",
21600                LLVMWithBeforeLambdaBody);
21601   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21602                "    []()\n"
21603                "    {\n"
21604                "      return Call([]() {});\n"
21605                "    });",
21606                LLVMWithBeforeLambdaBody);
21607   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21608                "                           []()\n"
21609                "                           {\n"
21610                "                             return Call([]() {});\n"
21611                "                           });",
21612                LLVMWithBeforeLambdaBody);
21613   verifyFormat(
21614       "FctWithLongLineInLambda_SLS_Empty(\n"
21615       "    []()\n"
21616       "    {\n"
21617       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21618       "                               AndShouldNotBeConsiderAsInline,\n"
21619       "                               LambdaBodyMustBeBreak);\n"
21620       "    });",
21621       LLVMWithBeforeLambdaBody);
21622 
21623   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21624       FormatStyle::ShortLambdaStyle::SLS_Inline;
21625   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21626                LLVMWithBeforeLambdaBody);
21627   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21628                LLVMWithBeforeLambdaBody);
21629   verifyFormat("auto fct_SLS_Inline = []()\n"
21630                "{\n"
21631                "  return 17;\n"
21632                "};",
21633                LLVMWithBeforeLambdaBody);
21634   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21635                "17; }); });",
21636                LLVMWithBeforeLambdaBody);
21637   verifyFormat(
21638       "FctWithLongLineInLambda_SLS_Inline(\n"
21639       "    []()\n"
21640       "    {\n"
21641       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21642       "                               AndShouldNotBeConsiderAsInline,\n"
21643       "                               LambdaBodyMustBeBreak);\n"
21644       "    });",
21645       LLVMWithBeforeLambdaBody);
21646   verifyFormat("FctWithMultipleParams_SLS_Inline("
21647                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21648                "                                 []() { return 17; });",
21649                LLVMWithBeforeLambdaBody);
21650   verifyFormat(
21651       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21652       LLVMWithBeforeLambdaBody);
21653 
21654   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21655       FormatStyle::ShortLambdaStyle::SLS_All;
21656   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21657                LLVMWithBeforeLambdaBody);
21658   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21659                LLVMWithBeforeLambdaBody);
21660   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21661                LLVMWithBeforeLambdaBody);
21662   verifyFormat("FctWithOneParam_SLS_All(\n"
21663                "    []()\n"
21664                "    {\n"
21665                "      // A cool function...\n"
21666                "      return 43;\n"
21667                "    });",
21668                LLVMWithBeforeLambdaBody);
21669   verifyFormat("FctWithMultipleParams_SLS_All("
21670                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21671                "                              []() { return 17; });",
21672                LLVMWithBeforeLambdaBody);
21673   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21674                LLVMWithBeforeLambdaBody);
21675   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21676                LLVMWithBeforeLambdaBody);
21677   verifyFormat(
21678       "FctWithLongLineInLambda_SLS_All(\n"
21679       "    []()\n"
21680       "    {\n"
21681       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21682       "                               AndShouldNotBeConsiderAsInline,\n"
21683       "                               LambdaBodyMustBeBreak);\n"
21684       "    });",
21685       LLVMWithBeforeLambdaBody);
21686   verifyFormat(
21687       "auto fct_SLS_All = []()\n"
21688       "{\n"
21689       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21690       "                           AndShouldNotBeConsiderAsInline,\n"
21691       "                           LambdaBodyMustBeBreak);\n"
21692       "};",
21693       LLVMWithBeforeLambdaBody);
21694   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21695   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21696                LLVMWithBeforeLambdaBody);
21697   verifyFormat(
21698       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21699       "                                FirstParam,\n"
21700       "                                SecondParam,\n"
21701       "                                ThirdParam,\n"
21702       "                                FourthParam);",
21703       LLVMWithBeforeLambdaBody);
21704   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21705                "    []() { return "
21706                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21707                "    FirstParam,\n"
21708                "    SecondParam,\n"
21709                "    ThirdParam,\n"
21710                "    FourthParam);",
21711                LLVMWithBeforeLambdaBody);
21712   verifyFormat(
21713       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21714       "                                SecondParam,\n"
21715       "                                ThirdParam,\n"
21716       "                                FourthParam,\n"
21717       "                                []() { return SomeValueNotSoLong; });",
21718       LLVMWithBeforeLambdaBody);
21719   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21720                "    []()\n"
21721                "    {\n"
21722                "      return "
21723                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21724                "eConsiderAsInline;\n"
21725                "    });",
21726                LLVMWithBeforeLambdaBody);
21727   verifyFormat(
21728       "FctWithLongLineInLambda_SLS_All(\n"
21729       "    []()\n"
21730       "    {\n"
21731       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21732       "                               AndShouldNotBeConsiderAsInline,\n"
21733       "                               LambdaBodyMustBeBreak);\n"
21734       "    });",
21735       LLVMWithBeforeLambdaBody);
21736   verifyFormat("FctWithTwoParams_SLS_All(\n"
21737                "    []()\n"
21738                "    {\n"
21739                "      // A cool function...\n"
21740                "      return 43;\n"
21741                "    },\n"
21742                "    87);",
21743                LLVMWithBeforeLambdaBody);
21744   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
21745                LLVMWithBeforeLambdaBody);
21746   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
21747                LLVMWithBeforeLambdaBody);
21748   verifyFormat(
21749       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
21750       LLVMWithBeforeLambdaBody);
21751   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
21752                "}); }, x);",
21753                LLVMWithBeforeLambdaBody);
21754   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21755                "    []()\n"
21756                "    {\n"
21757                "      // A cool function...\n"
21758                "      return Call([]() { return 17; });\n"
21759                "    });",
21760                LLVMWithBeforeLambdaBody);
21761   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21762                "    []()\n"
21763                "    {\n"
21764                "      return Call(\n"
21765                "          []()\n"
21766                "          {\n"
21767                "            // A cool function...\n"
21768                "            return 17;\n"
21769                "          });\n"
21770                "    });",
21771                LLVMWithBeforeLambdaBody);
21772 
21773   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21774       FormatStyle::ShortLambdaStyle::SLS_None;
21775 
21776   verifyFormat("auto select = [this]() -> const Library::Object *\n"
21777                "{\n"
21778                "  return MyAssignment::SelectFromList(this);\n"
21779                "};\n",
21780                LLVMWithBeforeLambdaBody);
21781 
21782   verifyFormat("auto select = [this]() -> const Library::Object &\n"
21783                "{\n"
21784                "  return MyAssignment::SelectFromList(this);\n"
21785                "};\n",
21786                LLVMWithBeforeLambdaBody);
21787 
21788   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
21789                "{\n"
21790                "  return MyAssignment::SelectFromList(this);\n"
21791                "};\n",
21792                LLVMWithBeforeLambdaBody);
21793 
21794   verifyFormat("namespace test {\n"
21795                "class Test {\n"
21796                "public:\n"
21797                "  Test() = default;\n"
21798                "};\n"
21799                "} // namespace test",
21800                LLVMWithBeforeLambdaBody);
21801 
21802   // Lambdas with different indentation styles.
21803   Style = getLLVMStyleWithColumns(100);
21804   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21805             "  return promise.then(\n"
21806             "      [this, &someVariable, someObject = "
21807             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21808             "        return someObject.startAsyncAction().then(\n"
21809             "            [this, &someVariable](AsyncActionResult result) "
21810             "mutable { result.processMore(); });\n"
21811             "      });\n"
21812             "}\n",
21813             format("SomeResult doSomething(SomeObject promise) {\n"
21814                    "  return promise.then([this, &someVariable, someObject = "
21815                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21816                    "    return someObject.startAsyncAction().then([this, "
21817                    "&someVariable](AsyncActionResult result) mutable {\n"
21818                    "      result.processMore();\n"
21819                    "    });\n"
21820                    "  });\n"
21821                    "}\n",
21822                    Style));
21823   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21824   verifyFormat("test() {\n"
21825                "  ([]() -> {\n"
21826                "    int b = 32;\n"
21827                "    return 3;\n"
21828                "  }).foo();\n"
21829                "}",
21830                Style);
21831   verifyFormat("test() {\n"
21832                "  []() -> {\n"
21833                "    int b = 32;\n"
21834                "    return 3;\n"
21835                "  }\n"
21836                "}",
21837                Style);
21838   verifyFormat("std::sort(v.begin(), v.end(),\n"
21839                "          [](const auto &someLongArgumentName, const auto "
21840                "&someOtherLongArgumentName) {\n"
21841                "  return someLongArgumentName.someMemberVariable < "
21842                "someOtherLongArgumentName.someMemberVariable;\n"
21843                "});",
21844                Style);
21845   verifyFormat("test() {\n"
21846                "  (\n"
21847                "      []() -> {\n"
21848                "        int b = 32;\n"
21849                "        return 3;\n"
21850                "      },\n"
21851                "      foo, bar)\n"
21852                "      .foo();\n"
21853                "}",
21854                Style);
21855   verifyFormat("test() {\n"
21856                "  ([]() -> {\n"
21857                "    int b = 32;\n"
21858                "    return 3;\n"
21859                "  })\n"
21860                "      .foo()\n"
21861                "      .bar();\n"
21862                "}",
21863                Style);
21864   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21865             "  return promise.then(\n"
21866             "      [this, &someVariable, someObject = "
21867             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21868             "    return someObject.startAsyncAction().then(\n"
21869             "        [this, &someVariable](AsyncActionResult result) mutable { "
21870             "result.processMore(); });\n"
21871             "  });\n"
21872             "}\n",
21873             format("SomeResult doSomething(SomeObject promise) {\n"
21874                    "  return promise.then([this, &someVariable, someObject = "
21875                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21876                    "    return someObject.startAsyncAction().then([this, "
21877                    "&someVariable](AsyncActionResult result) mutable {\n"
21878                    "      result.processMore();\n"
21879                    "    });\n"
21880                    "  });\n"
21881                    "}\n",
21882                    Style));
21883   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21884             "  return promise.then([this, &someVariable] {\n"
21885             "    return someObject.startAsyncAction().then(\n"
21886             "        [this, &someVariable](AsyncActionResult result) mutable { "
21887             "result.processMore(); });\n"
21888             "  });\n"
21889             "}\n",
21890             format("SomeResult doSomething(SomeObject promise) {\n"
21891                    "  return promise.then([this, &someVariable] {\n"
21892                    "    return someObject.startAsyncAction().then([this, "
21893                    "&someVariable](AsyncActionResult result) mutable {\n"
21894                    "      result.processMore();\n"
21895                    "    });\n"
21896                    "  });\n"
21897                    "}\n",
21898                    Style));
21899   Style = getGoogleStyle();
21900   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21901   EXPECT_EQ("#define A                                       \\\n"
21902             "  [] {                                          \\\n"
21903             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
21904             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
21905             "      }",
21906             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
21907                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
21908                    Style));
21909   // TODO: The current formatting has a minor issue that's not worth fixing
21910   // right now whereby the closing brace is indented relative to the signature
21911   // instead of being aligned. This only happens with macros.
21912 }
21913 
21914 TEST_F(FormatTest, LambdaWithLineComments) {
21915   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21916   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21917   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21918   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21919       FormatStyle::ShortLambdaStyle::SLS_All;
21920 
21921   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
21922   verifyFormat("auto k = []() // comment\n"
21923                "{ return; }",
21924                LLVMWithBeforeLambdaBody);
21925   verifyFormat("auto k = []() /* comment */ { return; }",
21926                LLVMWithBeforeLambdaBody);
21927   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
21928                LLVMWithBeforeLambdaBody);
21929   verifyFormat("auto k = []() // X\n"
21930                "{ return; }",
21931                LLVMWithBeforeLambdaBody);
21932   verifyFormat(
21933       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
21934       "{ return; }",
21935       LLVMWithBeforeLambdaBody);
21936 }
21937 
21938 TEST_F(FormatTest, EmptyLinesInLambdas) {
21939   verifyFormat("auto lambda = []() {\n"
21940                "  x(); //\n"
21941                "};",
21942                "auto lambda = []() {\n"
21943                "\n"
21944                "  x(); //\n"
21945                "\n"
21946                "};");
21947 }
21948 
21949 TEST_F(FormatTest, FormatsBlocks) {
21950   FormatStyle ShortBlocks = getLLVMStyle();
21951   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21952   verifyFormat("int (^Block)(int, int);", ShortBlocks);
21953   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
21954   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
21955   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
21956   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
21957   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
21958 
21959   verifyFormat("foo(^{ bar(); });", ShortBlocks);
21960   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
21961   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
21962 
21963   verifyFormat("[operation setCompletionBlock:^{\n"
21964                "  [self onOperationDone];\n"
21965                "}];");
21966   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
21967                "  [self onOperationDone];\n"
21968                "}]};");
21969   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
21970                "  f();\n"
21971                "}];");
21972   verifyFormat("int a = [operation block:^int(int *i) {\n"
21973                "  return 1;\n"
21974                "}];");
21975   verifyFormat("[myObject doSomethingWith:arg1\n"
21976                "                      aaa:^int(int *a) {\n"
21977                "                        return 1;\n"
21978                "                      }\n"
21979                "                      bbb:f(a * bbbbbbbb)];");
21980 
21981   verifyFormat("[operation setCompletionBlock:^{\n"
21982                "  [self.delegate newDataAvailable];\n"
21983                "}];",
21984                getLLVMStyleWithColumns(60));
21985   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
21986                "  NSString *path = [self sessionFilePath];\n"
21987                "  if (path) {\n"
21988                "    // ...\n"
21989                "  }\n"
21990                "});");
21991   verifyFormat("[[SessionService sharedService]\n"
21992                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21993                "      if (window) {\n"
21994                "        [self windowDidLoad:window];\n"
21995                "      } else {\n"
21996                "        [self errorLoadingWindow];\n"
21997                "      }\n"
21998                "    }];");
21999   verifyFormat("void (^largeBlock)(void) = ^{\n"
22000                "  // ...\n"
22001                "};\n",
22002                getLLVMStyleWithColumns(40));
22003   verifyFormat("[[SessionService sharedService]\n"
22004                "    loadWindowWithCompletionBlock: //\n"
22005                "        ^(SessionWindow *window) {\n"
22006                "          if (window) {\n"
22007                "            [self windowDidLoad:window];\n"
22008                "          } else {\n"
22009                "            [self errorLoadingWindow];\n"
22010                "          }\n"
22011                "        }];",
22012                getLLVMStyleWithColumns(60));
22013   verifyFormat("[myObject doSomethingWith:arg1\n"
22014                "    firstBlock:^(Foo *a) {\n"
22015                "      // ...\n"
22016                "      int i;\n"
22017                "    }\n"
22018                "    secondBlock:^(Bar *b) {\n"
22019                "      // ...\n"
22020                "      int i;\n"
22021                "    }\n"
22022                "    thirdBlock:^Foo(Bar *b) {\n"
22023                "      // ...\n"
22024                "      int i;\n"
22025                "    }];");
22026   verifyFormat("[myObject doSomethingWith:arg1\n"
22027                "               firstBlock:-1\n"
22028                "              secondBlock:^(Bar *b) {\n"
22029                "                // ...\n"
22030                "                int i;\n"
22031                "              }];");
22032 
22033   verifyFormat("f(^{\n"
22034                "  @autoreleasepool {\n"
22035                "    if (a) {\n"
22036                "      g();\n"
22037                "    }\n"
22038                "  }\n"
22039                "});");
22040   verifyFormat("Block b = ^int *(A *a, B *b) {}");
22041   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
22042                "};");
22043 
22044   FormatStyle FourIndent = getLLVMStyle();
22045   FourIndent.ObjCBlockIndentWidth = 4;
22046   verifyFormat("[operation setCompletionBlock:^{\n"
22047                "    [self onOperationDone];\n"
22048                "}];",
22049                FourIndent);
22050 }
22051 
22052 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
22053   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
22054 
22055   verifyFormat("[[SessionService sharedService] "
22056                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22057                "  if (window) {\n"
22058                "    [self windowDidLoad:window];\n"
22059                "  } else {\n"
22060                "    [self errorLoadingWindow];\n"
22061                "  }\n"
22062                "}];",
22063                ZeroColumn);
22064   EXPECT_EQ("[[SessionService sharedService]\n"
22065             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22066             "      if (window) {\n"
22067             "        [self windowDidLoad:window];\n"
22068             "      } else {\n"
22069             "        [self errorLoadingWindow];\n"
22070             "      }\n"
22071             "    }];",
22072             format("[[SessionService sharedService]\n"
22073                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22074                    "                if (window) {\n"
22075                    "    [self windowDidLoad:window];\n"
22076                    "  } else {\n"
22077                    "    [self errorLoadingWindow];\n"
22078                    "  }\n"
22079                    "}];",
22080                    ZeroColumn));
22081   verifyFormat("[myObject doSomethingWith:arg1\n"
22082                "    firstBlock:^(Foo *a) {\n"
22083                "      // ...\n"
22084                "      int i;\n"
22085                "    }\n"
22086                "    secondBlock:^(Bar *b) {\n"
22087                "      // ...\n"
22088                "      int i;\n"
22089                "    }\n"
22090                "    thirdBlock:^Foo(Bar *b) {\n"
22091                "      // ...\n"
22092                "      int i;\n"
22093                "    }];",
22094                ZeroColumn);
22095   verifyFormat("f(^{\n"
22096                "  @autoreleasepool {\n"
22097                "    if (a) {\n"
22098                "      g();\n"
22099                "    }\n"
22100                "  }\n"
22101                "});",
22102                ZeroColumn);
22103   verifyFormat("void (^largeBlock)(void) = ^{\n"
22104                "  // ...\n"
22105                "};",
22106                ZeroColumn);
22107 
22108   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22109   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
22110             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22111   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22112   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
22113             "  int i;\n"
22114             "};",
22115             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22116 }
22117 
22118 TEST_F(FormatTest, SupportsCRLF) {
22119   EXPECT_EQ("int a;\r\n"
22120             "int b;\r\n"
22121             "int c;\r\n",
22122             format("int a;\r\n"
22123                    "  int b;\r\n"
22124                    "    int c;\r\n",
22125                    getLLVMStyle()));
22126   EXPECT_EQ("int a;\r\n"
22127             "int b;\r\n"
22128             "int c;\r\n",
22129             format("int a;\r\n"
22130                    "  int b;\n"
22131                    "    int c;\r\n",
22132                    getLLVMStyle()));
22133   EXPECT_EQ("int a;\n"
22134             "int b;\n"
22135             "int c;\n",
22136             format("int a;\r\n"
22137                    "  int b;\n"
22138                    "    int c;\n",
22139                    getLLVMStyle()));
22140   EXPECT_EQ("\"aaaaaaa \"\r\n"
22141             "\"bbbbbbb\";\r\n",
22142             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
22143   EXPECT_EQ("#define A \\\r\n"
22144             "  b;      \\\r\n"
22145             "  c;      \\\r\n"
22146             "  d;\r\n",
22147             format("#define A \\\r\n"
22148                    "  b; \\\r\n"
22149                    "  c; d; \r\n",
22150                    getGoogleStyle()));
22151 
22152   EXPECT_EQ("/*\r\n"
22153             "multi line block comments\r\n"
22154             "should not introduce\r\n"
22155             "an extra carriage return\r\n"
22156             "*/\r\n",
22157             format("/*\r\n"
22158                    "multi line block comments\r\n"
22159                    "should not introduce\r\n"
22160                    "an extra carriage return\r\n"
22161                    "*/\r\n"));
22162   EXPECT_EQ("/*\r\n"
22163             "\r\n"
22164             "*/",
22165             format("/*\r\n"
22166                    "    \r\r\r\n"
22167                    "*/"));
22168 
22169   FormatStyle style = getLLVMStyle();
22170 
22171   style.DeriveLineEnding = true;
22172   style.UseCRLF = false;
22173   EXPECT_EQ("union FooBarBazQux {\n"
22174             "  int foo;\n"
22175             "  int bar;\n"
22176             "  int baz;\n"
22177             "};",
22178             format("union FooBarBazQux {\r\n"
22179                    "  int foo;\n"
22180                    "  int bar;\r\n"
22181                    "  int baz;\n"
22182                    "};",
22183                    style));
22184   style.UseCRLF = true;
22185   EXPECT_EQ("union FooBarBazQux {\r\n"
22186             "  int foo;\r\n"
22187             "  int bar;\r\n"
22188             "  int baz;\r\n"
22189             "};",
22190             format("union FooBarBazQux {\r\n"
22191                    "  int foo;\n"
22192                    "  int bar;\r\n"
22193                    "  int baz;\n"
22194                    "};",
22195                    style));
22196 
22197   style.DeriveLineEnding = false;
22198   style.UseCRLF = false;
22199   EXPECT_EQ("union FooBarBazQux {\n"
22200             "  int foo;\n"
22201             "  int bar;\n"
22202             "  int baz;\n"
22203             "  int qux;\n"
22204             "};",
22205             format("union FooBarBazQux {\r\n"
22206                    "  int foo;\n"
22207                    "  int bar;\r\n"
22208                    "  int baz;\n"
22209                    "  int qux;\r\n"
22210                    "};",
22211                    style));
22212   style.UseCRLF = true;
22213   EXPECT_EQ("union FooBarBazQux {\r\n"
22214             "  int foo;\r\n"
22215             "  int bar;\r\n"
22216             "  int baz;\r\n"
22217             "  int qux;\r\n"
22218             "};",
22219             format("union FooBarBazQux {\r\n"
22220                    "  int foo;\n"
22221                    "  int bar;\r\n"
22222                    "  int baz;\n"
22223                    "  int qux;\n"
22224                    "};",
22225                    style));
22226 
22227   style.DeriveLineEnding = true;
22228   style.UseCRLF = false;
22229   EXPECT_EQ("union FooBarBazQux {\r\n"
22230             "  int foo;\r\n"
22231             "  int bar;\r\n"
22232             "  int baz;\r\n"
22233             "  int qux;\r\n"
22234             "};",
22235             format("union FooBarBazQux {\r\n"
22236                    "  int foo;\n"
22237                    "  int bar;\r\n"
22238                    "  int baz;\n"
22239                    "  int qux;\r\n"
22240                    "};",
22241                    style));
22242   style.UseCRLF = true;
22243   EXPECT_EQ("union FooBarBazQux {\n"
22244             "  int foo;\n"
22245             "  int bar;\n"
22246             "  int baz;\n"
22247             "  int qux;\n"
22248             "};",
22249             format("union FooBarBazQux {\r\n"
22250                    "  int foo;\n"
22251                    "  int bar;\r\n"
22252                    "  int baz;\n"
22253                    "  int qux;\n"
22254                    "};",
22255                    style));
22256 }
22257 
22258 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
22259   verifyFormat("MY_CLASS(C) {\n"
22260                "  int i;\n"
22261                "  int j;\n"
22262                "};");
22263 }
22264 
22265 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
22266   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
22267   TwoIndent.ContinuationIndentWidth = 2;
22268 
22269   EXPECT_EQ("int i =\n"
22270             "  longFunction(\n"
22271             "    arg);",
22272             format("int i = longFunction(arg);", TwoIndent));
22273 
22274   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
22275   SixIndent.ContinuationIndentWidth = 6;
22276 
22277   EXPECT_EQ("int i =\n"
22278             "      longFunction(\n"
22279             "            arg);",
22280             format("int i = longFunction(arg);", SixIndent));
22281 }
22282 
22283 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
22284   FormatStyle Style = getLLVMStyle();
22285   verifyFormat("int Foo::getter(\n"
22286                "    //\n"
22287                ") const {\n"
22288                "  return foo;\n"
22289                "}",
22290                Style);
22291   verifyFormat("void Foo::setter(\n"
22292                "    //\n"
22293                ") {\n"
22294                "  foo = 1;\n"
22295                "}",
22296                Style);
22297 }
22298 
22299 TEST_F(FormatTest, SpacesInAngles) {
22300   FormatStyle Spaces = getLLVMStyle();
22301   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22302 
22303   verifyFormat("vector< ::std::string > x1;", Spaces);
22304   verifyFormat("Foo< int, Bar > x2;", Spaces);
22305   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22306 
22307   verifyFormat("static_cast< int >(arg);", Spaces);
22308   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22309   verifyFormat("f< int, float >();", Spaces);
22310   verifyFormat("template <> g() {}", Spaces);
22311   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22312   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22313   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22314                Spaces);
22315 
22316   Spaces.Standard = FormatStyle::LS_Cpp03;
22317   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22318   verifyFormat("A< A< int > >();", Spaces);
22319 
22320   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22321   verifyFormat("A<A<int> >();", Spaces);
22322 
22323   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22324   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22325                Spaces);
22326   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22327                Spaces);
22328 
22329   verifyFormat("A<A<int> >();", Spaces);
22330   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22331   verifyFormat("A< A< int > >();", Spaces);
22332 
22333   Spaces.Standard = FormatStyle::LS_Cpp11;
22334   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22335   verifyFormat("A< A< int > >();", Spaces);
22336 
22337   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22338   verifyFormat("vector<::std::string> x4;", Spaces);
22339   verifyFormat("vector<int> x5;", Spaces);
22340   verifyFormat("Foo<int, Bar> x6;", Spaces);
22341   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22342 
22343   verifyFormat("A<A<int>>();", Spaces);
22344 
22345   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22346   verifyFormat("vector<::std::string> x4;", Spaces);
22347   verifyFormat("vector< ::std::string > x4;", Spaces);
22348   verifyFormat("vector<int> x5;", Spaces);
22349   verifyFormat("vector< int > x5;", Spaces);
22350   verifyFormat("Foo<int, Bar> x6;", Spaces);
22351   verifyFormat("Foo< int, Bar > x6;", Spaces);
22352   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22353   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22354 
22355   verifyFormat("A<A<int>>();", Spaces);
22356   verifyFormat("A< A< int > >();", Spaces);
22357   verifyFormat("A<A<int > >();", Spaces);
22358   verifyFormat("A< A< int>>();", Spaces);
22359 
22360   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22361   verifyFormat("// clang-format off\n"
22362                "foo<<<1, 1>>>();\n"
22363                "// clang-format on\n",
22364                Spaces);
22365   verifyFormat("// clang-format off\n"
22366                "foo< < <1, 1> > >();\n"
22367                "// clang-format on\n",
22368                Spaces);
22369 }
22370 
22371 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22372   FormatStyle Style = getLLVMStyle();
22373   Style.SpaceAfterTemplateKeyword = false;
22374   verifyFormat("template<int> void foo();", Style);
22375 }
22376 
22377 TEST_F(FormatTest, TripleAngleBrackets) {
22378   verifyFormat("f<<<1, 1>>>();");
22379   verifyFormat("f<<<1, 1, 1, s>>>();");
22380   verifyFormat("f<<<a, b, c, d>>>();");
22381   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22382   verifyFormat("f<param><<<1, 1>>>();");
22383   verifyFormat("f<1><<<1, 1>>>();");
22384   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22385   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22386                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22387   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22388                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22389 }
22390 
22391 TEST_F(FormatTest, MergeLessLessAtEnd) {
22392   verifyFormat("<<");
22393   EXPECT_EQ("< < <", format("\\\n<<<"));
22394   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22395                "aaallvm::outs() <<");
22396   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22397                "aaaallvm::outs()\n    <<");
22398 }
22399 
22400 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22401   std::string code = "#if A\n"
22402                      "#if B\n"
22403                      "a.\n"
22404                      "#endif\n"
22405                      "    a = 1;\n"
22406                      "#else\n"
22407                      "#endif\n"
22408                      "#if C\n"
22409                      "#else\n"
22410                      "#endif\n";
22411   EXPECT_EQ(code, format(code));
22412 }
22413 
22414 TEST_F(FormatTest, HandleConflictMarkers) {
22415   // Git/SVN conflict markers.
22416   EXPECT_EQ("int a;\n"
22417             "void f() {\n"
22418             "  callme(some(parameter1,\n"
22419             "<<<<<<< text by the vcs\n"
22420             "              parameter2),\n"
22421             "||||||| text by the vcs\n"
22422             "              parameter2),\n"
22423             "         parameter3,\n"
22424             "======= text by the vcs\n"
22425             "              parameter2, parameter3),\n"
22426             ">>>>>>> text by the vcs\n"
22427             "         otherparameter);\n",
22428             format("int a;\n"
22429                    "void f() {\n"
22430                    "  callme(some(parameter1,\n"
22431                    "<<<<<<< text by the vcs\n"
22432                    "  parameter2),\n"
22433                    "||||||| text by the vcs\n"
22434                    "  parameter2),\n"
22435                    "  parameter3,\n"
22436                    "======= text by the vcs\n"
22437                    "  parameter2,\n"
22438                    "  parameter3),\n"
22439                    ">>>>>>> text by the vcs\n"
22440                    "  otherparameter);\n"));
22441 
22442   // Perforce markers.
22443   EXPECT_EQ("void f() {\n"
22444             "  function(\n"
22445             ">>>> text by the vcs\n"
22446             "      parameter,\n"
22447             "==== text by the vcs\n"
22448             "      parameter,\n"
22449             "==== text by the vcs\n"
22450             "      parameter,\n"
22451             "<<<< text by the vcs\n"
22452             "      parameter);\n",
22453             format("void f() {\n"
22454                    "  function(\n"
22455                    ">>>> text by the vcs\n"
22456                    "  parameter,\n"
22457                    "==== text by the vcs\n"
22458                    "  parameter,\n"
22459                    "==== text by the vcs\n"
22460                    "  parameter,\n"
22461                    "<<<< text by the vcs\n"
22462                    "  parameter);\n"));
22463 
22464   EXPECT_EQ("<<<<<<<\n"
22465             "|||||||\n"
22466             "=======\n"
22467             ">>>>>>>",
22468             format("<<<<<<<\n"
22469                    "|||||||\n"
22470                    "=======\n"
22471                    ">>>>>>>"));
22472 
22473   EXPECT_EQ("<<<<<<<\n"
22474             "|||||||\n"
22475             "int i;\n"
22476             "=======\n"
22477             ">>>>>>>",
22478             format("<<<<<<<\n"
22479                    "|||||||\n"
22480                    "int i;\n"
22481                    "=======\n"
22482                    ">>>>>>>"));
22483 
22484   // FIXME: Handle parsing of macros around conflict markers correctly:
22485   EXPECT_EQ("#define Macro \\\n"
22486             "<<<<<<<\n"
22487             "Something \\\n"
22488             "|||||||\n"
22489             "Else \\\n"
22490             "=======\n"
22491             "Other \\\n"
22492             ">>>>>>>\n"
22493             "    End int i;\n",
22494             format("#define Macro \\\n"
22495                    "<<<<<<<\n"
22496                    "  Something \\\n"
22497                    "|||||||\n"
22498                    "  Else \\\n"
22499                    "=======\n"
22500                    "  Other \\\n"
22501                    ">>>>>>>\n"
22502                    "  End\n"
22503                    "int i;\n"));
22504 
22505   verifyFormat(R"(====
22506 #ifdef A
22507 a
22508 #else
22509 b
22510 #endif
22511 )");
22512 }
22513 
22514 TEST_F(FormatTest, DisableRegions) {
22515   EXPECT_EQ("int i;\n"
22516             "// clang-format off\n"
22517             "  int j;\n"
22518             "// clang-format on\n"
22519             "int k;",
22520             format(" int  i;\n"
22521                    "   // clang-format off\n"
22522                    "  int j;\n"
22523                    " // clang-format on\n"
22524                    "   int   k;"));
22525   EXPECT_EQ("int i;\n"
22526             "/* clang-format off */\n"
22527             "  int j;\n"
22528             "/* clang-format on */\n"
22529             "int k;",
22530             format(" int  i;\n"
22531                    "   /* clang-format off */\n"
22532                    "  int j;\n"
22533                    " /* clang-format on */\n"
22534                    "   int   k;"));
22535 
22536   // Don't reflow comments within disabled regions.
22537   EXPECT_EQ("// clang-format off\n"
22538             "// long long long long long long line\n"
22539             "/* clang-format on */\n"
22540             "/* long long long\n"
22541             " * long long long\n"
22542             " * line */\n"
22543             "int i;\n"
22544             "/* clang-format off */\n"
22545             "/* long long long long long long line */\n",
22546             format("// clang-format off\n"
22547                    "// long long long long long long line\n"
22548                    "/* clang-format on */\n"
22549                    "/* long long long long long long line */\n"
22550                    "int i;\n"
22551                    "/* clang-format off */\n"
22552                    "/* long long long long long long line */\n",
22553                    getLLVMStyleWithColumns(20)));
22554 }
22555 
22556 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22557   format("? ) =");
22558   verifyNoCrash("#define a\\\n /**/}");
22559 }
22560 
22561 TEST_F(FormatTest, FormatsTableGenCode) {
22562   FormatStyle Style = getLLVMStyle();
22563   Style.Language = FormatStyle::LK_TableGen;
22564   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22565 }
22566 
22567 TEST_F(FormatTest, ArrayOfTemplates) {
22568   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22569             format("auto a = new unique_ptr<int > [ 10];"));
22570 
22571   FormatStyle Spaces = getLLVMStyle();
22572   Spaces.SpacesInSquareBrackets = true;
22573   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22574             format("auto a = new unique_ptr<int > [10];", Spaces));
22575 }
22576 
22577 TEST_F(FormatTest, ArrayAsTemplateType) {
22578   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22579             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22580 
22581   FormatStyle Spaces = getLLVMStyle();
22582   Spaces.SpacesInSquareBrackets = true;
22583   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22584             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22585 }
22586 
22587 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22588 
22589 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22590   llvm::vfs::InMemoryFileSystem FS;
22591   auto Style1 = getStyle("file", "", "Google", "", &FS);
22592   ASSERT_TRUE((bool)Style1);
22593   ASSERT_EQ(*Style1, getGoogleStyle());
22594 }
22595 
22596 TEST(FormatStyle, GetStyleOfFile) {
22597   llvm::vfs::InMemoryFileSystem FS;
22598   // Test 1: format file in the same directory.
22599   ASSERT_TRUE(
22600       FS.addFile("/a/.clang-format", 0,
22601                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22602   ASSERT_TRUE(
22603       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22604   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22605   ASSERT_TRUE((bool)Style1);
22606   ASSERT_EQ(*Style1, getLLVMStyle());
22607 
22608   // Test 2.1: fallback to default.
22609   ASSERT_TRUE(
22610       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22611   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22612   ASSERT_TRUE((bool)Style2);
22613   ASSERT_EQ(*Style2, getMozillaStyle());
22614 
22615   // Test 2.2: no format on 'none' fallback style.
22616   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22617   ASSERT_TRUE((bool)Style2);
22618   ASSERT_EQ(*Style2, getNoStyle());
22619 
22620   // Test 2.3: format if config is found with no based style while fallback is
22621   // 'none'.
22622   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22623                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22624   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22625   ASSERT_TRUE((bool)Style2);
22626   ASSERT_EQ(*Style2, getLLVMStyle());
22627 
22628   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22629   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22630   ASSERT_TRUE((bool)Style2);
22631   ASSERT_EQ(*Style2, getLLVMStyle());
22632 
22633   // Test 3: format file in parent directory.
22634   ASSERT_TRUE(
22635       FS.addFile("/c/.clang-format", 0,
22636                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22637   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22638                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22639   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22640   ASSERT_TRUE((bool)Style3);
22641   ASSERT_EQ(*Style3, getGoogleStyle());
22642 
22643   // Test 4: error on invalid fallback style
22644   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22645   ASSERT_FALSE((bool)Style4);
22646   llvm::consumeError(Style4.takeError());
22647 
22648   // Test 5: error on invalid yaml on command line
22649   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22650   ASSERT_FALSE((bool)Style5);
22651   llvm::consumeError(Style5.takeError());
22652 
22653   // Test 6: error on invalid style
22654   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22655   ASSERT_FALSE((bool)Style6);
22656   llvm::consumeError(Style6.takeError());
22657 
22658   // Test 7: found config file, error on parsing it
22659   ASSERT_TRUE(
22660       FS.addFile("/d/.clang-format", 0,
22661                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22662                                                   "InvalidKey: InvalidValue")));
22663   ASSERT_TRUE(
22664       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22665   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22666   ASSERT_FALSE((bool)Style7a);
22667   llvm::consumeError(Style7a.takeError());
22668 
22669   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22670   ASSERT_TRUE((bool)Style7b);
22671 
22672   // Test 8: inferred per-language defaults apply.
22673   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22674   ASSERT_TRUE((bool)StyleTd);
22675   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22676 
22677   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22678   // fallback style.
22679   ASSERT_TRUE(FS.addFile(
22680       "/e/sub/.clang-format", 0,
22681       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22682                                        "ColumnLimit: 20")));
22683   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22684                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22685   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22686   ASSERT_TRUE(static_cast<bool>(Style9));
22687   ASSERT_EQ(*Style9, [] {
22688     auto Style = getNoStyle();
22689     Style.ColumnLimit = 20;
22690     return Style;
22691   }());
22692 
22693   // Test 9.1.2: propagate more than one level with no parent file.
22694   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22695                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22696   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22697                          llvm::MemoryBuffer::getMemBuffer(
22698                              "BasedOnStyle: InheritParentConfig\n"
22699                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22700   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22701 
22702   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22703   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22704   ASSERT_TRUE(static_cast<bool>(Style9));
22705   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22706     auto Style = getNoStyle();
22707     Style.ColumnLimit = 20;
22708     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22709     return Style;
22710   }());
22711 
22712   // Test 9.2: with LLVM fallback style
22713   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22714   ASSERT_TRUE(static_cast<bool>(Style9));
22715   ASSERT_EQ(*Style9, [] {
22716     auto Style = getLLVMStyle();
22717     Style.ColumnLimit = 20;
22718     return Style;
22719   }());
22720 
22721   // Test 9.3: with a parent file
22722   ASSERT_TRUE(
22723       FS.addFile("/e/.clang-format", 0,
22724                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
22725                                                   "UseTab: Always")));
22726   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22727   ASSERT_TRUE(static_cast<bool>(Style9));
22728   ASSERT_EQ(*Style9, [] {
22729     auto Style = getGoogleStyle();
22730     Style.ColumnLimit = 20;
22731     Style.UseTab = FormatStyle::UT_Always;
22732     return Style;
22733   }());
22734 
22735   // Test 9.4: propagate more than one level with a parent file.
22736   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
22737     auto Style = getGoogleStyle();
22738     Style.ColumnLimit = 20;
22739     Style.UseTab = FormatStyle::UT_Always;
22740     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22741     return Style;
22742   }();
22743 
22744   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22745   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22746   ASSERT_TRUE(static_cast<bool>(Style9));
22747   ASSERT_EQ(*Style9, SubSubStyle);
22748 
22749   // Test 9.5: use InheritParentConfig as style name
22750   Style9 =
22751       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
22752   ASSERT_TRUE(static_cast<bool>(Style9));
22753   ASSERT_EQ(*Style9, SubSubStyle);
22754 
22755   // Test 9.6: use command line style with inheritance
22756   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
22757                     "none", "", &FS);
22758   ASSERT_TRUE(static_cast<bool>(Style9));
22759   ASSERT_EQ(*Style9, SubSubStyle);
22760 
22761   // Test 9.7: use command line style with inheritance and own config
22762   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
22763                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
22764                     "/e/sub/code.cpp", "none", "", &FS);
22765   ASSERT_TRUE(static_cast<bool>(Style9));
22766   ASSERT_EQ(*Style9, SubSubStyle);
22767 
22768   // Test 9.8: use inheritance from a file without BasedOnStyle
22769   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
22770                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
22771   ASSERT_TRUE(
22772       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
22773                  llvm::MemoryBuffer::getMemBuffer(
22774                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
22775   // Make sure we do not use the fallback style
22776   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
22777   ASSERT_TRUE(static_cast<bool>(Style9));
22778   ASSERT_EQ(*Style9, [] {
22779     auto Style = getLLVMStyle();
22780     Style.ColumnLimit = 123;
22781     return Style;
22782   }());
22783 
22784   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
22785   ASSERT_TRUE(static_cast<bool>(Style9));
22786   ASSERT_EQ(*Style9, [] {
22787     auto Style = getLLVMStyle();
22788     Style.ColumnLimit = 123;
22789     Style.IndentWidth = 7;
22790     return Style;
22791   }());
22792 
22793   // Test 9.9: use inheritance from a specific config file.
22794   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
22795                     "none", "", &FS);
22796   ASSERT_TRUE(static_cast<bool>(Style9));
22797   ASSERT_EQ(*Style9, SubSubStyle);
22798 }
22799 
22800 TEST(FormatStyle, GetStyleOfSpecificFile) {
22801   llvm::vfs::InMemoryFileSystem FS;
22802   // Specify absolute path to a format file in a parent directory.
22803   ASSERT_TRUE(
22804       FS.addFile("/e/.clang-format", 0,
22805                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22806   ASSERT_TRUE(
22807       FS.addFile("/e/explicit.clang-format", 0,
22808                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22809   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
22810                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22811   auto Style = getStyle("file:/e/explicit.clang-format",
22812                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22813   ASSERT_TRUE(static_cast<bool>(Style));
22814   ASSERT_EQ(*Style, getGoogleStyle());
22815 
22816   // Specify relative path to a format file.
22817   ASSERT_TRUE(
22818       FS.addFile("../../e/explicit.clang-format", 0,
22819                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22820   Style = getStyle("file:../../e/explicit.clang-format",
22821                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22822   ASSERT_TRUE(static_cast<bool>(Style));
22823   ASSERT_EQ(*Style, getGoogleStyle());
22824 
22825   // Specify path to a format file that does not exist.
22826   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
22827                    "LLVM", "", &FS);
22828   ASSERT_FALSE(static_cast<bool>(Style));
22829   llvm::consumeError(Style.takeError());
22830 
22831   // Specify path to a file on the filesystem.
22832   SmallString<128> FormatFilePath;
22833   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
22834       "FormatFileTest", "tpl", FormatFilePath);
22835   EXPECT_FALSE((bool)ECF);
22836   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
22837   EXPECT_FALSE((bool)ECF);
22838   FormatFileTest << "BasedOnStyle: Google\n";
22839   FormatFileTest.close();
22840 
22841   SmallString<128> TestFilePath;
22842   std::error_code ECT =
22843       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
22844   EXPECT_FALSE((bool)ECT);
22845   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
22846   CodeFileTest << "int i;\n";
22847   CodeFileTest.close();
22848 
22849   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
22850   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
22851 
22852   llvm::sys::fs::remove(FormatFilePath.c_str());
22853   llvm::sys::fs::remove(TestFilePath.c_str());
22854   ASSERT_TRUE(static_cast<bool>(Style));
22855   ASSERT_EQ(*Style, getGoogleStyle());
22856 }
22857 
22858 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
22859   // Column limit is 20.
22860   std::string Code = "Type *a =\n"
22861                      "    new Type();\n"
22862                      "g(iiiii, 0, jjjjj,\n"
22863                      "  0, kkkkk, 0, mm);\n"
22864                      "int  bad     = format   ;";
22865   std::string Expected = "auto a = new Type();\n"
22866                          "g(iiiii, nullptr,\n"
22867                          "  jjjjj, nullptr,\n"
22868                          "  kkkkk, nullptr,\n"
22869                          "  mm);\n"
22870                          "int  bad     = format   ;";
22871   FileID ID = Context.createInMemoryFile("format.cpp", Code);
22872   tooling::Replacements Replaces = toReplacements(
22873       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
22874                             "auto "),
22875        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
22876                             "nullptr"),
22877        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
22878                             "nullptr"),
22879        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
22880                             "nullptr")});
22881 
22882   FormatStyle Style = getLLVMStyle();
22883   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
22884   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22885   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22886       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22887   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22888   EXPECT_TRUE(static_cast<bool>(Result));
22889   EXPECT_EQ(Expected, *Result);
22890 }
22891 
22892 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
22893   std::string Code = "#include \"a.h\"\n"
22894                      "#include \"c.h\"\n"
22895                      "\n"
22896                      "int main() {\n"
22897                      "  return 0;\n"
22898                      "}";
22899   std::string Expected = "#include \"a.h\"\n"
22900                          "#include \"b.h\"\n"
22901                          "#include \"c.h\"\n"
22902                          "\n"
22903                          "int main() {\n"
22904                          "  return 0;\n"
22905                          "}";
22906   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
22907   tooling::Replacements Replaces = toReplacements(
22908       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
22909                             "#include \"b.h\"\n")});
22910 
22911   FormatStyle Style = getLLVMStyle();
22912   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
22913   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22914   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22915       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22916   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22917   EXPECT_TRUE(static_cast<bool>(Result));
22918   EXPECT_EQ(Expected, *Result);
22919 }
22920 
22921 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
22922   EXPECT_EQ("using std::cin;\n"
22923             "using std::cout;",
22924             format("using std::cout;\n"
22925                    "using std::cin;",
22926                    getGoogleStyle()));
22927 }
22928 
22929 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
22930   FormatStyle Style = getLLVMStyle();
22931   Style.Standard = FormatStyle::LS_Cpp03;
22932   // cpp03 recognize this string as identifier u8 and literal character 'a'
22933   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
22934 }
22935 
22936 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
22937   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
22938   // all modes, including C++11, C++14 and C++17
22939   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
22940 }
22941 
22942 TEST_F(FormatTest, DoNotFormatLikelyXml) {
22943   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
22944   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
22945 }
22946 
22947 TEST_F(FormatTest, StructuredBindings) {
22948   // Structured bindings is a C++17 feature.
22949   // all modes, including C++11, C++14 and C++17
22950   verifyFormat("auto [a, b] = f();");
22951   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
22952   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
22953   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
22954   EXPECT_EQ("auto const volatile [a, b] = f();",
22955             format("auto  const   volatile[a, b] = f();"));
22956   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
22957   EXPECT_EQ("auto &[a, b, c] = f();",
22958             format("auto   &[  a  ,  b,c   ] = f();"));
22959   EXPECT_EQ("auto &&[a, b, c] = f();",
22960             format("auto   &&[  a  ,  b,c   ] = f();"));
22961   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
22962   EXPECT_EQ("auto const volatile &&[a, b] = f();",
22963             format("auto  const  volatile  &&[a, b] = f();"));
22964   EXPECT_EQ("auto const &&[a, b] = f();",
22965             format("auto  const   &&  [a, b] = f();"));
22966   EXPECT_EQ("const auto &[a, b] = f();",
22967             format("const  auto  &  [a, b] = f();"));
22968   EXPECT_EQ("const auto volatile &&[a, b] = f();",
22969             format("const  auto   volatile  &&[a, b] = f();"));
22970   EXPECT_EQ("volatile const auto &&[a, b] = f();",
22971             format("volatile  const  auto   &&[a, b] = f();"));
22972   EXPECT_EQ("const auto &&[a, b] = f();",
22973             format("const  auto  &&  [a, b] = f();"));
22974 
22975   // Make sure we don't mistake structured bindings for lambdas.
22976   FormatStyle PointerMiddle = getLLVMStyle();
22977   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
22978   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
22979   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
22980   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
22981   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
22982   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
22983   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
22984   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
22985   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
22986   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
22987   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
22988   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
22989   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
22990 
22991   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
22992             format("for (const auto   &&   [a, b] : some_range) {\n}"));
22993   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
22994             format("for (const auto   &   [a, b] : some_range) {\n}"));
22995   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
22996             format("for (const auto[a, b] : some_range) {\n}"));
22997   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
22998   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
22999   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
23000   EXPECT_EQ("auto const &[x, y](expr);",
23001             format("auto  const  &  [x,y]  (expr);"));
23002   EXPECT_EQ("auto const &&[x, y](expr);",
23003             format("auto  const  &&  [x,y]  (expr);"));
23004   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
23005   EXPECT_EQ("auto const &[x, y]{expr};",
23006             format("auto  const  &  [x,y]  {expr};"));
23007   EXPECT_EQ("auto const &&[x, y]{expr};",
23008             format("auto  const  &&  [x,y]  {expr};"));
23009 
23010   FormatStyle Spaces = getLLVMStyle();
23011   Spaces.SpacesInSquareBrackets = true;
23012   verifyFormat("auto [ a, b ] = f();", Spaces);
23013   verifyFormat("auto &&[ a, b ] = f();", Spaces);
23014   verifyFormat("auto &[ a, b ] = f();", Spaces);
23015   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
23016   verifyFormat("auto const &[ a, b ] = f();", Spaces);
23017 }
23018 
23019 TEST_F(FormatTest, FileAndCode) {
23020   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
23021   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
23022   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
23023   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
23024   EXPECT_EQ(FormatStyle::LK_ObjC,
23025             guessLanguage("foo.h", "@interface Foo\n@end\n"));
23026   EXPECT_EQ(
23027       FormatStyle::LK_ObjC,
23028       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
23029   EXPECT_EQ(FormatStyle::LK_ObjC,
23030             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
23031   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
23032   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
23033   EXPECT_EQ(FormatStyle::LK_ObjC,
23034             guessLanguage("foo", "@interface Foo\n@end\n"));
23035   EXPECT_EQ(FormatStyle::LK_ObjC,
23036             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
23037   EXPECT_EQ(
23038       FormatStyle::LK_ObjC,
23039       guessLanguage("foo.h",
23040                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
23041   EXPECT_EQ(
23042       FormatStyle::LK_Cpp,
23043       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
23044   // Only one of the two preprocessor regions has ObjC-like code.
23045   EXPECT_EQ(FormatStyle::LK_ObjC,
23046             guessLanguage("foo.h", "#if A\n"
23047                                    "#define B() C\n"
23048                                    "#else\n"
23049                                    "#define B() [NSString a:@\"\"]\n"
23050                                    "#endif\n"));
23051 }
23052 
23053 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
23054   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
23055   EXPECT_EQ(FormatStyle::LK_ObjC,
23056             guessLanguage("foo.h", "array[[calculator getIndex]];"));
23057   EXPECT_EQ(FormatStyle::LK_Cpp,
23058             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
23059   EXPECT_EQ(
23060       FormatStyle::LK_Cpp,
23061       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
23062   EXPECT_EQ(FormatStyle::LK_ObjC,
23063             guessLanguage("foo.h", "[[noreturn foo] bar];"));
23064   EXPECT_EQ(FormatStyle::LK_Cpp,
23065             guessLanguage("foo.h", "[[clang::fallthrough]];"));
23066   EXPECT_EQ(FormatStyle::LK_ObjC,
23067             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
23068   EXPECT_EQ(FormatStyle::LK_Cpp,
23069             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
23070   EXPECT_EQ(FormatStyle::LK_Cpp,
23071             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
23072   EXPECT_EQ(FormatStyle::LK_ObjC,
23073             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
23074   EXPECT_EQ(FormatStyle::LK_Cpp,
23075             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
23076   EXPECT_EQ(
23077       FormatStyle::LK_Cpp,
23078       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
23079   EXPECT_EQ(
23080       FormatStyle::LK_Cpp,
23081       guessLanguage("foo.h",
23082                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
23083   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
23084 }
23085 
23086 TEST_F(FormatTest, GuessLanguageWithCaret) {
23087   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
23088   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
23089   EXPECT_EQ(FormatStyle::LK_ObjC,
23090             guessLanguage("foo.h", "int(^)(char, float);"));
23091   EXPECT_EQ(FormatStyle::LK_ObjC,
23092             guessLanguage("foo.h", "int(^foo)(char, float);"));
23093   EXPECT_EQ(FormatStyle::LK_ObjC,
23094             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
23095   EXPECT_EQ(FormatStyle::LK_ObjC,
23096             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
23097   EXPECT_EQ(
23098       FormatStyle::LK_ObjC,
23099       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
23100 }
23101 
23102 TEST_F(FormatTest, GuessLanguageWithPragmas) {
23103   EXPECT_EQ(FormatStyle::LK_Cpp,
23104             guessLanguage("foo.h", "__pragma(warning(disable:))"));
23105   EXPECT_EQ(FormatStyle::LK_Cpp,
23106             guessLanguage("foo.h", "#pragma(warning(disable:))"));
23107   EXPECT_EQ(FormatStyle::LK_Cpp,
23108             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
23109 }
23110 
23111 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
23112   // ASM symbolic names are identifiers that must be surrounded by [] without
23113   // space in between:
23114   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
23115 
23116   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
23117   verifyFormat(R"(//
23118 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
23119 )");
23120 
23121   // A list of several ASM symbolic names.
23122   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
23123 
23124   // ASM symbolic names in inline ASM with inputs and outputs.
23125   verifyFormat(R"(//
23126 asm("cmoveq %1, %2, %[result]"
23127     : [result] "=r"(result)
23128     : "r"(test), "r"(new), "[result]"(old));
23129 )");
23130 
23131   // ASM symbolic names in inline ASM with no outputs.
23132   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
23133 }
23134 
23135 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
23136   EXPECT_EQ(FormatStyle::LK_Cpp,
23137             guessLanguage("foo.h", "void f() {\n"
23138                                    "  asm (\"mov %[e], %[d]\"\n"
23139                                    "     : [d] \"=rm\" (d)\n"
23140                                    "       [e] \"rm\" (*e));\n"
23141                                    "}"));
23142   EXPECT_EQ(FormatStyle::LK_Cpp,
23143             guessLanguage("foo.h", "void f() {\n"
23144                                    "  _asm (\"mov %[e], %[d]\"\n"
23145                                    "     : [d] \"=rm\" (d)\n"
23146                                    "       [e] \"rm\" (*e));\n"
23147                                    "}"));
23148   EXPECT_EQ(FormatStyle::LK_Cpp,
23149             guessLanguage("foo.h", "void f() {\n"
23150                                    "  __asm (\"mov %[e], %[d]\"\n"
23151                                    "     : [d] \"=rm\" (d)\n"
23152                                    "       [e] \"rm\" (*e));\n"
23153                                    "}"));
23154   EXPECT_EQ(FormatStyle::LK_Cpp,
23155             guessLanguage("foo.h", "void f() {\n"
23156                                    "  __asm__ (\"mov %[e], %[d]\"\n"
23157                                    "     : [d] \"=rm\" (d)\n"
23158                                    "       [e] \"rm\" (*e));\n"
23159                                    "}"));
23160   EXPECT_EQ(FormatStyle::LK_Cpp,
23161             guessLanguage("foo.h", "void f() {\n"
23162                                    "  asm (\"mov %[e], %[d]\"\n"
23163                                    "     : [d] \"=rm\" (d),\n"
23164                                    "       [e] \"rm\" (*e));\n"
23165                                    "}"));
23166   EXPECT_EQ(FormatStyle::LK_Cpp,
23167             guessLanguage("foo.h", "void f() {\n"
23168                                    "  asm volatile (\"mov %[e], %[d]\"\n"
23169                                    "     : [d] \"=rm\" (d)\n"
23170                                    "       [e] \"rm\" (*e));\n"
23171                                    "}"));
23172 }
23173 
23174 TEST_F(FormatTest, GuessLanguageWithChildLines) {
23175   EXPECT_EQ(FormatStyle::LK_Cpp,
23176             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
23177   EXPECT_EQ(FormatStyle::LK_ObjC,
23178             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
23179   EXPECT_EQ(
23180       FormatStyle::LK_Cpp,
23181       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
23182   EXPECT_EQ(
23183       FormatStyle::LK_ObjC,
23184       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
23185 }
23186 
23187 TEST_F(FormatTest, TypenameMacros) {
23188   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
23189 
23190   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
23191   FormatStyle Google = getGoogleStyleWithColumns(0);
23192   Google.TypenameMacros = TypenameMacros;
23193   verifyFormat("struct foo {\n"
23194                "  int bar;\n"
23195                "  TAILQ_ENTRY(a) bleh;\n"
23196                "};",
23197                Google);
23198 
23199   FormatStyle Macros = getLLVMStyle();
23200   Macros.TypenameMacros = TypenameMacros;
23201 
23202   verifyFormat("STACK_OF(int) a;", Macros);
23203   verifyFormat("STACK_OF(int) *a;", Macros);
23204   verifyFormat("STACK_OF(int const *) *a;", Macros);
23205   verifyFormat("STACK_OF(int *const) *a;", Macros);
23206   verifyFormat("STACK_OF(int, string) a;", Macros);
23207   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
23208   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
23209   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
23210   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
23211   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
23212   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
23213 
23214   Macros.PointerAlignment = FormatStyle::PAS_Left;
23215   verifyFormat("STACK_OF(int)* a;", Macros);
23216   verifyFormat("STACK_OF(int*)* a;", Macros);
23217   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
23218   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
23219   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
23220 }
23221 
23222 TEST_F(FormatTest, AtomicQualifier) {
23223   // Check that we treate _Atomic as a type and not a function call
23224   FormatStyle Google = getGoogleStyleWithColumns(0);
23225   verifyFormat("struct foo {\n"
23226                "  int a1;\n"
23227                "  _Atomic(a) a2;\n"
23228                "  _Atomic(_Atomic(int) *const) a3;\n"
23229                "};",
23230                Google);
23231   verifyFormat("_Atomic(uint64_t) a;");
23232   verifyFormat("_Atomic(uint64_t) *a;");
23233   verifyFormat("_Atomic(uint64_t const *) *a;");
23234   verifyFormat("_Atomic(uint64_t *const) *a;");
23235   verifyFormat("_Atomic(const uint64_t *) *a;");
23236   verifyFormat("_Atomic(uint64_t) a;");
23237   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
23238   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
23239   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
23240   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
23241 
23242   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
23243   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
23244   FormatStyle Style = getLLVMStyle();
23245   Style.PointerAlignment = FormatStyle::PAS_Left;
23246   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
23247   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
23248   verifyFormat("_Atomic(int)* a;", Style);
23249   verifyFormat("_Atomic(int*)* a;", Style);
23250   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
23251 
23252   Style.SpacesInCStyleCastParentheses = true;
23253   Style.SpacesInParentheses = false;
23254   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
23255   Style.SpacesInCStyleCastParentheses = false;
23256   Style.SpacesInParentheses = true;
23257   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
23258   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
23259 }
23260 
23261 TEST_F(FormatTest, AmbersandInLamda) {
23262   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
23263   FormatStyle AlignStyle = getLLVMStyle();
23264   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
23265   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23266   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
23267   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23268 }
23269 
23270 TEST_F(FormatTest, SpacesInConditionalStatement) {
23271   FormatStyle Spaces = getLLVMStyle();
23272   Spaces.IfMacros.clear();
23273   Spaces.IfMacros.push_back("MYIF");
23274   Spaces.SpacesInConditionalStatement = true;
23275   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
23276   verifyFormat("if ( !a )\n  return;", Spaces);
23277   verifyFormat("if ( a )\n  return;", Spaces);
23278   verifyFormat("if constexpr ( a )\n  return;", Spaces);
23279   verifyFormat("MYIF ( a )\n  return;", Spaces);
23280   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
23281   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
23282   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
23283   verifyFormat("while ( a )\n  return;", Spaces);
23284   verifyFormat("while ( (a && b) )\n  return;", Spaces);
23285   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
23286   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
23287   // Check that space on the left of "::" is inserted as expected at beginning
23288   // of condition.
23289   verifyFormat("while ( ::func() )\n  return;", Spaces);
23290 
23291   // Check impact of ControlStatementsExceptControlMacros is honored.
23292   Spaces.SpaceBeforeParens =
23293       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
23294   verifyFormat("MYIF( a )\n  return;", Spaces);
23295   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
23296   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
23297 }
23298 
23299 TEST_F(FormatTest, AlternativeOperators) {
23300   // Test case for ensuring alternate operators are not
23301   // combined with their right most neighbour.
23302   verifyFormat("int a and b;");
23303   verifyFormat("int a and_eq b;");
23304   verifyFormat("int a bitand b;");
23305   verifyFormat("int a bitor b;");
23306   verifyFormat("int a compl b;");
23307   verifyFormat("int a not b;");
23308   verifyFormat("int a not_eq b;");
23309   verifyFormat("int a or b;");
23310   verifyFormat("int a xor b;");
23311   verifyFormat("int a xor_eq b;");
23312   verifyFormat("return this not_eq bitand other;");
23313   verifyFormat("bool operator not_eq(const X bitand other)");
23314 
23315   verifyFormat("int a and 5;");
23316   verifyFormat("int a and_eq 5;");
23317   verifyFormat("int a bitand 5;");
23318   verifyFormat("int a bitor 5;");
23319   verifyFormat("int a compl 5;");
23320   verifyFormat("int a not 5;");
23321   verifyFormat("int a not_eq 5;");
23322   verifyFormat("int a or 5;");
23323   verifyFormat("int a xor 5;");
23324   verifyFormat("int a xor_eq 5;");
23325 
23326   verifyFormat("int a compl(5);");
23327   verifyFormat("int a not(5);");
23328 
23329   /* FIXME handle alternate tokens
23330    * https://en.cppreference.com/w/cpp/language/operator_alternative
23331   // alternative tokens
23332   verifyFormat("compl foo();");     //  ~foo();
23333   verifyFormat("foo() <%%>;");      // foo();
23334   verifyFormat("void foo() <%%>;"); // void foo(){}
23335   verifyFormat("int a <:1:>;");     // int a[1];[
23336   verifyFormat("%:define ABC abc"); // #define ABC abc
23337   verifyFormat("%:%:");             // ##
23338   */
23339 }
23340 
23341 TEST_F(FormatTest, STLWhileNotDefineChed) {
23342   verifyFormat("#if defined(while)\n"
23343                "#define while EMIT WARNING C4005\n"
23344                "#endif // while");
23345 }
23346 
23347 TEST_F(FormatTest, OperatorSpacing) {
23348   FormatStyle Style = getLLVMStyle();
23349   Style.PointerAlignment = FormatStyle::PAS_Right;
23350   verifyFormat("Foo::operator*();", Style);
23351   verifyFormat("Foo::operator void *();", Style);
23352   verifyFormat("Foo::operator void **();", Style);
23353   verifyFormat("Foo::operator void *&();", Style);
23354   verifyFormat("Foo::operator void *&&();", Style);
23355   verifyFormat("Foo::operator void const *();", Style);
23356   verifyFormat("Foo::operator void const **();", Style);
23357   verifyFormat("Foo::operator void const *&();", Style);
23358   verifyFormat("Foo::operator void const *&&();", Style);
23359   verifyFormat("Foo::operator()(void *);", Style);
23360   verifyFormat("Foo::operator*(void *);", Style);
23361   verifyFormat("Foo::operator*();", Style);
23362   verifyFormat("Foo::operator**();", Style);
23363   verifyFormat("Foo::operator&();", Style);
23364   verifyFormat("Foo::operator<int> *();", Style);
23365   verifyFormat("Foo::operator<Foo> *();", Style);
23366   verifyFormat("Foo::operator<int> **();", Style);
23367   verifyFormat("Foo::operator<Foo> **();", Style);
23368   verifyFormat("Foo::operator<int> &();", Style);
23369   verifyFormat("Foo::operator<Foo> &();", Style);
23370   verifyFormat("Foo::operator<int> &&();", Style);
23371   verifyFormat("Foo::operator<Foo> &&();", Style);
23372   verifyFormat("Foo::operator<int> *&();", Style);
23373   verifyFormat("Foo::operator<Foo> *&();", Style);
23374   verifyFormat("Foo::operator<int> *&&();", Style);
23375   verifyFormat("Foo::operator<Foo> *&&();", Style);
23376   verifyFormat("operator*(int (*)(), class Foo);", Style);
23377 
23378   verifyFormat("Foo::operator&();", Style);
23379   verifyFormat("Foo::operator void &();", Style);
23380   verifyFormat("Foo::operator void const &();", Style);
23381   verifyFormat("Foo::operator()(void &);", Style);
23382   verifyFormat("Foo::operator&(void &);", Style);
23383   verifyFormat("Foo::operator&();", Style);
23384   verifyFormat("operator&(int (&)(), class Foo);", Style);
23385   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23386 
23387   verifyFormat("Foo::operator&&();", Style);
23388   verifyFormat("Foo::operator**();", Style);
23389   verifyFormat("Foo::operator void &&();", Style);
23390   verifyFormat("Foo::operator void const &&();", Style);
23391   verifyFormat("Foo::operator()(void &&);", Style);
23392   verifyFormat("Foo::operator&&(void &&);", Style);
23393   verifyFormat("Foo::operator&&();", Style);
23394   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23395   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23396   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23397                Style);
23398   verifyFormat("operator void **()", Style);
23399   verifyFormat("operator const FooRight<Object> &()", Style);
23400   verifyFormat("operator const FooRight<Object> *()", Style);
23401   verifyFormat("operator const FooRight<Object> **()", Style);
23402   verifyFormat("operator const FooRight<Object> *&()", Style);
23403   verifyFormat("operator const FooRight<Object> *&&()", Style);
23404 
23405   Style.PointerAlignment = FormatStyle::PAS_Left;
23406   verifyFormat("Foo::operator*();", Style);
23407   verifyFormat("Foo::operator**();", Style);
23408   verifyFormat("Foo::operator void*();", Style);
23409   verifyFormat("Foo::operator void**();", Style);
23410   verifyFormat("Foo::operator void*&();", Style);
23411   verifyFormat("Foo::operator void*&&();", Style);
23412   verifyFormat("Foo::operator void const*();", Style);
23413   verifyFormat("Foo::operator void const**();", Style);
23414   verifyFormat("Foo::operator void const*&();", Style);
23415   verifyFormat("Foo::operator void const*&&();", Style);
23416   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23417   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23418   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23419   verifyFormat("Foo::operator()(void*);", Style);
23420   verifyFormat("Foo::operator*(void*);", Style);
23421   verifyFormat("Foo::operator*();", Style);
23422   verifyFormat("Foo::operator<int>*();", Style);
23423   verifyFormat("Foo::operator<Foo>*();", Style);
23424   verifyFormat("Foo::operator<int>**();", Style);
23425   verifyFormat("Foo::operator<Foo>**();", Style);
23426   verifyFormat("Foo::operator<Foo>*&();", Style);
23427   verifyFormat("Foo::operator<int>&();", Style);
23428   verifyFormat("Foo::operator<Foo>&();", Style);
23429   verifyFormat("Foo::operator<int>&&();", Style);
23430   verifyFormat("Foo::operator<Foo>&&();", Style);
23431   verifyFormat("Foo::operator<int>*&();", Style);
23432   verifyFormat("Foo::operator<Foo>*&();", Style);
23433   verifyFormat("operator*(int (*)(), class Foo);", Style);
23434 
23435   verifyFormat("Foo::operator&();", Style);
23436   verifyFormat("Foo::operator void&();", Style);
23437   verifyFormat("Foo::operator void const&();", Style);
23438   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23439   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23440   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23441   verifyFormat("Foo::operator()(void&);", Style);
23442   verifyFormat("Foo::operator&(void&);", Style);
23443   verifyFormat("Foo::operator&();", Style);
23444   verifyFormat("operator&(int (&)(), class Foo);", Style);
23445   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23446   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23447 
23448   verifyFormat("Foo::operator&&();", Style);
23449   verifyFormat("Foo::operator void&&();", Style);
23450   verifyFormat("Foo::operator void const&&();", Style);
23451   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23452   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23453   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23454   verifyFormat("Foo::operator()(void&&);", Style);
23455   verifyFormat("Foo::operator&&(void&&);", Style);
23456   verifyFormat("Foo::operator&&();", Style);
23457   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23458   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23459   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23460                Style);
23461   verifyFormat("operator void**()", Style);
23462   verifyFormat("operator const FooLeft<Object>&()", Style);
23463   verifyFormat("operator const FooLeft<Object>*()", Style);
23464   verifyFormat("operator const FooLeft<Object>**()", Style);
23465   verifyFormat("operator const FooLeft<Object>*&()", Style);
23466   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23467 
23468   // PR45107
23469   verifyFormat("operator Vector<String>&();", Style);
23470   verifyFormat("operator const Vector<String>&();", Style);
23471   verifyFormat("operator foo::Bar*();", Style);
23472   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23473   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23474                Style);
23475 
23476   Style.PointerAlignment = FormatStyle::PAS_Middle;
23477   verifyFormat("Foo::operator*();", Style);
23478   verifyFormat("Foo::operator void *();", Style);
23479   verifyFormat("Foo::operator()(void *);", Style);
23480   verifyFormat("Foo::operator*(void *);", Style);
23481   verifyFormat("Foo::operator*();", Style);
23482   verifyFormat("operator*(int (*)(), class Foo);", Style);
23483 
23484   verifyFormat("Foo::operator&();", Style);
23485   verifyFormat("Foo::operator void &();", Style);
23486   verifyFormat("Foo::operator void const &();", Style);
23487   verifyFormat("Foo::operator()(void &);", Style);
23488   verifyFormat("Foo::operator&(void &);", Style);
23489   verifyFormat("Foo::operator&();", Style);
23490   verifyFormat("operator&(int (&)(), class Foo);", Style);
23491 
23492   verifyFormat("Foo::operator&&();", Style);
23493   verifyFormat("Foo::operator void &&();", Style);
23494   verifyFormat("Foo::operator void const &&();", Style);
23495   verifyFormat("Foo::operator()(void &&);", Style);
23496   verifyFormat("Foo::operator&&(void &&);", Style);
23497   verifyFormat("Foo::operator&&();", Style);
23498   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23499 }
23500 
23501 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23502   FormatStyle Style = getLLVMStyle();
23503   // PR46157
23504   verifyFormat("foo(operator+, -42);", Style);
23505   verifyFormat("foo(operator++, -42);", Style);
23506   verifyFormat("foo(operator--, -42);", Style);
23507   verifyFormat("foo(-42, operator--);", Style);
23508   verifyFormat("foo(-42, operator, );", Style);
23509   verifyFormat("foo(operator, , -42);", Style);
23510 }
23511 
23512 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23513   FormatStyle Style = getLLVMStyle();
23514   Style.WhitespaceSensitiveMacros.push_back("FOO");
23515 
23516   // Don't use the helpers here, since 'mess up' will change the whitespace
23517   // and these are all whitespace sensitive by definition
23518   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23519             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23520   EXPECT_EQ(
23521       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23522       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23523   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23524             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23525   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23526             "       Still=Intentional);",
23527             format("FOO(String-ized&Messy+But,: :\n"
23528                    "       Still=Intentional);",
23529                    Style));
23530   Style.AlignConsecutiveAssignments.Enabled = true;
23531   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23532             "       Still=Intentional);",
23533             format("FOO(String-ized=&Messy+But,: :\n"
23534                    "       Still=Intentional);",
23535                    Style));
23536 
23537   Style.ColumnLimit = 21;
23538   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23539             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23540 }
23541 
23542 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23543   // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
23544   // test its interaction with line wrapping
23545   FormatStyle Style = getLLVMStyleWithColumns(80);
23546   verifyFormat("namespace {\n"
23547                "int i;\n"
23548                "int j;\n"
23549                "} // namespace",
23550                Style);
23551 
23552   verifyFormat("namespace AAA {\n"
23553                "int i;\n"
23554                "int j;\n"
23555                "} // namespace AAA",
23556                Style);
23557 
23558   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23559             "int i;\n"
23560             "int j;\n"
23561             "} // namespace Averyveryveryverylongnamespace",
23562             format("namespace Averyveryveryverylongnamespace {\n"
23563                    "int i;\n"
23564                    "int j;\n"
23565                    "}",
23566                    Style));
23567 
23568   EXPECT_EQ(
23569       "namespace "
23570       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23571       "    went::mad::now {\n"
23572       "int i;\n"
23573       "int j;\n"
23574       "} // namespace\n"
23575       "  // "
23576       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23577       "went::mad::now",
23578       format("namespace "
23579              "would::it::save::you::a::lot::of::time::if_::i::"
23580              "just::gave::up::and_::went::mad::now {\n"
23581              "int i;\n"
23582              "int j;\n"
23583              "}",
23584              Style));
23585 
23586   // This used to duplicate the comment again and again on subsequent runs
23587   EXPECT_EQ(
23588       "namespace "
23589       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23590       "    went::mad::now {\n"
23591       "int i;\n"
23592       "int j;\n"
23593       "} // namespace\n"
23594       "  // "
23595       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23596       "went::mad::now",
23597       format("namespace "
23598              "would::it::save::you::a::lot::of::time::if_::i::"
23599              "just::gave::up::and_::went::mad::now {\n"
23600              "int i;\n"
23601              "int j;\n"
23602              "} // namespace\n"
23603              "  // "
23604              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23605              "and_::went::mad::now",
23606              Style));
23607 }
23608 
23609 TEST_F(FormatTest, LikelyUnlikely) {
23610   FormatStyle Style = getLLVMStyle();
23611 
23612   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23613                "  return 29;\n"
23614                "}",
23615                Style);
23616 
23617   verifyFormat("if (argc > 5) [[likely]] {\n"
23618                "  return 29;\n"
23619                "}",
23620                Style);
23621 
23622   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23623                "  return 29;\n"
23624                "} else [[likely]] {\n"
23625                "  return 42;\n"
23626                "}\n",
23627                Style);
23628 
23629   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23630                "  return 29;\n"
23631                "} else if (argc > 10) [[likely]] {\n"
23632                "  return 99;\n"
23633                "} else {\n"
23634                "  return 42;\n"
23635                "}\n",
23636                Style);
23637 
23638   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23639                "  return 29;\n"
23640                "}",
23641                Style);
23642 
23643   verifyFormat("if (argc > 5) [[unlikely]]\n"
23644                "  return 29;\n",
23645                Style);
23646   verifyFormat("if (argc > 5) [[likely]]\n"
23647                "  return 29;\n",
23648                Style);
23649 
23650   Style.AttributeMacros.push_back("UNLIKELY");
23651   Style.AttributeMacros.push_back("LIKELY");
23652   verifyFormat("if (argc > 5) UNLIKELY\n"
23653                "  return 29;\n",
23654                Style);
23655 
23656   verifyFormat("if (argc > 5) UNLIKELY {\n"
23657                "  return 29;\n"
23658                "}",
23659                Style);
23660   verifyFormat("if (argc > 5) UNLIKELY {\n"
23661                "  return 29;\n"
23662                "} else [[likely]] {\n"
23663                "  return 42;\n"
23664                "}\n",
23665                Style);
23666   verifyFormat("if (argc > 5) UNLIKELY {\n"
23667                "  return 29;\n"
23668                "} else LIKELY {\n"
23669                "  return 42;\n"
23670                "}\n",
23671                Style);
23672   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23673                "  return 29;\n"
23674                "} else LIKELY {\n"
23675                "  return 42;\n"
23676                "}\n",
23677                Style);
23678 }
23679 
23680 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23681   verifyFormat("Constructor()\n"
23682                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23683                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23684                "aaaaaaaaaaaaaaaaaat))");
23685   verifyFormat("Constructor()\n"
23686                "    : aaaaaaaaaaaaa(aaaaaa), "
23687                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
23688 
23689   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
23690   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
23691   verifyFormat("Constructor()\n"
23692                "    : aaaaaa(aaaaaa),\n"
23693                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23694                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
23695                StyleWithWhitespacePenalty);
23696   verifyFormat("Constructor()\n"
23697                "    : aaaaaaaaaaaaa(aaaaaa), "
23698                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
23699                StyleWithWhitespacePenalty);
23700 }
23701 
23702 TEST_F(FormatTest, LLVMDefaultStyle) {
23703   FormatStyle Style = getLLVMStyle();
23704   verifyFormat("extern \"C\" {\n"
23705                "int foo();\n"
23706                "}",
23707                Style);
23708 }
23709 TEST_F(FormatTest, GNUDefaultStyle) {
23710   FormatStyle Style = getGNUStyle();
23711   verifyFormat("extern \"C\"\n"
23712                "{\n"
23713                "  int foo ();\n"
23714                "}",
23715                Style);
23716 }
23717 TEST_F(FormatTest, MozillaDefaultStyle) {
23718   FormatStyle Style = getMozillaStyle();
23719   verifyFormat("extern \"C\"\n"
23720                "{\n"
23721                "  int foo();\n"
23722                "}",
23723                Style);
23724 }
23725 TEST_F(FormatTest, GoogleDefaultStyle) {
23726   FormatStyle Style = getGoogleStyle();
23727   verifyFormat("extern \"C\" {\n"
23728                "int foo();\n"
23729                "}",
23730                Style);
23731 }
23732 TEST_F(FormatTest, ChromiumDefaultStyle) {
23733   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
23734   verifyFormat("extern \"C\" {\n"
23735                "int foo();\n"
23736                "}",
23737                Style);
23738 }
23739 TEST_F(FormatTest, MicrosoftDefaultStyle) {
23740   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
23741   verifyFormat("extern \"C\"\n"
23742                "{\n"
23743                "    int foo();\n"
23744                "}",
23745                Style);
23746 }
23747 TEST_F(FormatTest, WebKitDefaultStyle) {
23748   FormatStyle Style = getWebKitStyle();
23749   verifyFormat("extern \"C\" {\n"
23750                "int foo();\n"
23751                "}",
23752                Style);
23753 }
23754 
23755 TEST_F(FormatTest, Concepts) {
23756   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
23757             FormatStyle::BBCDS_Always);
23758   verifyFormat("template <typename T>\n"
23759                "concept True = true;");
23760 
23761   verifyFormat("template <typename T>\n"
23762                "concept C = ((false || foo()) && C2<T>) ||\n"
23763                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
23764                getLLVMStyleWithColumns(60));
23765 
23766   verifyFormat("template <typename T>\n"
23767                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
23768                "sizeof(T) <= 8;");
23769 
23770   verifyFormat("template <typename T>\n"
23771                "concept DelayedCheck = true && requires(T t) {\n"
23772                "                                 t.bar();\n"
23773                "                                 t.baz();\n"
23774                "                               } && sizeof(T) <= 8;");
23775 
23776   verifyFormat("template <typename T>\n"
23777                "concept DelayedCheck = true && requires(T t) { // Comment\n"
23778                "                                 t.bar();\n"
23779                "                                 t.baz();\n"
23780                "                               } && sizeof(T) <= 8;");
23781 
23782   verifyFormat("template <typename T>\n"
23783                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
23784                "sizeof(T) <= 8;");
23785 
23786   verifyFormat("template <typename T>\n"
23787                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
23788                "&& sizeof(T) <= 8;");
23789 
23790   verifyFormat(
23791       "template <typename T>\n"
23792       "concept DelayedCheck = static_cast<bool>(0) ||\n"
23793       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23794 
23795   verifyFormat("template <typename T>\n"
23796                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
23797                "&& sizeof(T) <= 8;");
23798 
23799   verifyFormat(
23800       "template <typename T>\n"
23801       "concept DelayedCheck = (bool)(0) ||\n"
23802       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23803 
23804   verifyFormat("template <typename T>\n"
23805                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
23806                "&& sizeof(T) <= 8;");
23807 
23808   verifyFormat("template <typename T>\n"
23809                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
23810                "sizeof(T) <= 8;");
23811 
23812   verifyFormat("template <typename T>\n"
23813                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
23814                "               requires(T t) {\n"
23815                "                 t.bar();\n"
23816                "                 t.baz();\n"
23817                "               } && sizeof(T) <= 8 && !(4 < 3);",
23818                getLLVMStyleWithColumns(60));
23819 
23820   verifyFormat("template <typename T>\n"
23821                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
23822 
23823   verifyFormat("template <typename T>\n"
23824                "concept C = foo();");
23825 
23826   verifyFormat("template <typename T>\n"
23827                "concept C = foo(T());");
23828 
23829   verifyFormat("template <typename T>\n"
23830                "concept C = foo(T{});");
23831 
23832   verifyFormat("template <typename T>\n"
23833                "concept Size = V<sizeof(T)>::Value > 5;");
23834 
23835   verifyFormat("template <typename T>\n"
23836                "concept True = S<T>::Value;");
23837 
23838   verifyFormat(
23839       "template <typename T>\n"
23840       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
23841       "            sizeof(T) <= 8;");
23842 
23843   // FIXME: This is misformatted because the fake l paren starts at bool, not at
23844   // the lambda l square.
23845   verifyFormat("template <typename T>\n"
23846                "concept C = [] -> bool { return true; }() && requires(T t) { "
23847                "t.bar(); } &&\n"
23848                "                      sizeof(T) <= 8;");
23849 
23850   verifyFormat(
23851       "template <typename T>\n"
23852       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
23853       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23854 
23855   verifyFormat("template <typename T>\n"
23856                "concept C = decltype([]() { return std::true_type{}; "
23857                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
23858                getLLVMStyleWithColumns(120));
23859 
23860   verifyFormat("template <typename T>\n"
23861                "concept C = decltype([]() -> std::true_type { return {}; "
23862                "}())::value &&\n"
23863                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23864 
23865   verifyFormat("template <typename T>\n"
23866                "concept C = true;\n"
23867                "Foo Bar;");
23868 
23869   verifyFormat("template <typename T>\n"
23870                "concept Hashable = requires(T a) {\n"
23871                "                     { std::hash<T>{}(a) } -> "
23872                "std::convertible_to<std::size_t>;\n"
23873                "                   };");
23874 
23875   verifyFormat(
23876       "template <typename T>\n"
23877       "concept EqualityComparable = requires(T a, T b) {\n"
23878       "                               { a == b } -> std::same_as<bool>;\n"
23879       "                             };");
23880 
23881   verifyFormat(
23882       "template <typename T>\n"
23883       "concept EqualityComparable = requires(T a, T b) {\n"
23884       "                               { a == b } -> std::same_as<bool>;\n"
23885       "                               { a != b } -> std::same_as<bool>;\n"
23886       "                             };");
23887 
23888   verifyFormat("template <typename T>\n"
23889                "concept WeakEqualityComparable = requires(T a, T b) {\n"
23890                "                                   { a == b };\n"
23891                "                                   { a != b };\n"
23892                "                                 };");
23893 
23894   verifyFormat("template <typename T>\n"
23895                "concept HasSizeT = requires { typename T::size_t; };");
23896 
23897   verifyFormat("template <typename T>\n"
23898                "concept Semiregular =\n"
23899                "    DefaultConstructible<T> && CopyConstructible<T> && "
23900                "CopyAssignable<T> &&\n"
23901                "    requires(T a, std::size_t n) {\n"
23902                "      requires Same<T *, decltype(&a)>;\n"
23903                "      { a.~T() } noexcept;\n"
23904                "      requires Same<T *, decltype(new T)>;\n"
23905                "      requires Same<T *, decltype(new T[n])>;\n"
23906                "      { delete new T; };\n"
23907                "      { delete new T[n]; };\n"
23908                "    };");
23909 
23910   verifyFormat("template <typename T>\n"
23911                "concept Semiregular =\n"
23912                "    requires(T a, std::size_t n) {\n"
23913                "      requires Same<T *, decltype(&a)>;\n"
23914                "      { a.~T() } noexcept;\n"
23915                "      requires Same<T *, decltype(new T)>;\n"
23916                "      requires Same<T *, decltype(new T[n])>;\n"
23917                "      { delete new T; };\n"
23918                "      { delete new T[n]; };\n"
23919                "      { new T } -> std::same_as<T *>;\n"
23920                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
23921                "CopyAssignable<T>;");
23922 
23923   verifyFormat(
23924       "template <typename T>\n"
23925       "concept Semiregular =\n"
23926       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
23927       "                                 requires Same<T *, decltype(&a)>;\n"
23928       "                                 { a.~T() } noexcept;\n"
23929       "                                 requires Same<T *, decltype(new T)>;\n"
23930       "                                 requires Same<T *, decltype(new "
23931       "T[n])>;\n"
23932       "                                 { delete new T; };\n"
23933       "                                 { delete new T[n]; };\n"
23934       "                               } && CopyConstructible<T> && "
23935       "CopyAssignable<T>;");
23936 
23937   verifyFormat("template <typename T>\n"
23938                "concept Two = requires(T t) {\n"
23939                "                { t.foo() } -> std::same_as<Bar>;\n"
23940                "              } && requires(T &&t) {\n"
23941                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
23942                "                   };");
23943 
23944   verifyFormat(
23945       "template <typename T>\n"
23946       "concept C = requires(T x) {\n"
23947       "              { *x } -> std::convertible_to<typename T::inner>;\n"
23948       "              { x + 1 } noexcept -> std::same_as<int>;\n"
23949       "              { x * 1 } -> std::convertible_to<T>;\n"
23950       "            };");
23951 
23952   verifyFormat(
23953       "template <typename T, typename U = T>\n"
23954       "concept Swappable = requires(T &&t, U &&u) {\n"
23955       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
23956       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
23957       "                    };");
23958 
23959   verifyFormat("template <typename T, typename U>\n"
23960                "concept Common = requires(T &&t, U &&u) {\n"
23961                "                   typename CommonType<T, U>;\n"
23962                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
23963                "                 };");
23964 
23965   verifyFormat("template <typename T, typename U>\n"
23966                "concept Common = requires(T &&t, U &&u) {\n"
23967                "                   typename CommonType<T, U>;\n"
23968                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
23969                "                 };");
23970 
23971   verifyFormat(
23972       "template <typename T>\n"
23973       "concept C = requires(T t) {\n"
23974       "              requires Bar<T> && Foo<T>;\n"
23975       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
23976       "            };");
23977 
23978   verifyFormat("template <typename T>\n"
23979                "concept HasFoo = requires(T t) {\n"
23980                "                   { t.foo() };\n"
23981                "                   t.foo();\n"
23982                "                 };\n"
23983                "template <typename T>\n"
23984                "concept HasBar = requires(T t) {\n"
23985                "                   { t.bar() };\n"
23986                "                   t.bar();\n"
23987                "                 };");
23988 
23989   verifyFormat("template <typename T>\n"
23990                "concept Large = sizeof(T) > 10;");
23991 
23992   verifyFormat("template <typename T, typename U>\n"
23993                "concept FooableWith = requires(T t, U u) {\n"
23994                "                        typename T::foo_type;\n"
23995                "                        { t.foo(u) } -> typename T::foo_type;\n"
23996                "                        t++;\n"
23997                "                      };\n"
23998                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
23999 
24000   verifyFormat("template <typename T>\n"
24001                "concept Context = is_specialization_of_v<context, T>;");
24002 
24003   verifyFormat("template <typename T>\n"
24004                "concept Node = std::is_object_v<T>;");
24005 
24006   verifyFormat("template <class T>\n"
24007                "concept integral = __is_integral(T);");
24008 
24009   verifyFormat("template <class T>\n"
24010                "concept is2D = __array_extent(T, 1) == 2;");
24011 
24012   verifyFormat("template <class T>\n"
24013                "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
24014 
24015   verifyFormat("template <class T, class T2>\n"
24016                "concept Same = __is_same_as<T, T2>;");
24017 
24018   auto Style = getLLVMStyle();
24019   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
24020 
24021   verifyFormat(
24022       "template <typename T>\n"
24023       "concept C = requires(T t) {\n"
24024       "              requires Bar<T> && Foo<T>;\n"
24025       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24026       "            };",
24027       Style);
24028 
24029   verifyFormat("template <typename T>\n"
24030                "concept HasFoo = requires(T t) {\n"
24031                "                   { t.foo() };\n"
24032                "                   t.foo();\n"
24033                "                 };\n"
24034                "template <typename T>\n"
24035                "concept HasBar = requires(T t) {\n"
24036                "                   { t.bar() };\n"
24037                "                   t.bar();\n"
24038                "                 };",
24039                Style);
24040 
24041   verifyFormat("template <typename T> concept True = true;", Style);
24042 
24043   verifyFormat("template <typename T>\n"
24044                "concept C = decltype([]() -> std::true_type { return {}; "
24045                "}())::value &&\n"
24046                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24047                Style);
24048 
24049   verifyFormat("template <typename T>\n"
24050                "concept Semiregular =\n"
24051                "    DefaultConstructible<T> && CopyConstructible<T> && "
24052                "CopyAssignable<T> &&\n"
24053                "    requires(T a, std::size_t n) {\n"
24054                "      requires Same<T *, decltype(&a)>;\n"
24055                "      { a.~T() } noexcept;\n"
24056                "      requires Same<T *, decltype(new T)>;\n"
24057                "      requires Same<T *, decltype(new T[n])>;\n"
24058                "      { delete new T; };\n"
24059                "      { delete new T[n]; };\n"
24060                "    };",
24061                Style);
24062 
24063   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
24064 
24065   verifyFormat("template <typename T> concept C =\n"
24066                "    requires(T t) {\n"
24067                "      requires Bar<T> && Foo<T>;\n"
24068                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24069                "    };",
24070                Style);
24071 
24072   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
24073                "                                         { t.foo() };\n"
24074                "                                         t.foo();\n"
24075                "                                       };\n"
24076                "template <typename T> concept HasBar = requires(T t) {\n"
24077                "                                         { t.bar() };\n"
24078                "                                         t.bar();\n"
24079                "                                       };",
24080                Style);
24081 
24082   verifyFormat("template <typename T> concept True = true;", Style);
24083 
24084   verifyFormat(
24085       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
24086       "                                    return {};\n"
24087       "                                  }())::value &&\n"
24088       "                                  requires(T t) { t.bar(); } && "
24089       "sizeof(T) <= 8;",
24090       Style);
24091 
24092   verifyFormat("template <typename T> concept Semiregular =\n"
24093                "    DefaultConstructible<T> && CopyConstructible<T> && "
24094                "CopyAssignable<T> &&\n"
24095                "    requires(T a, std::size_t n) {\n"
24096                "      requires Same<T *, decltype(&a)>;\n"
24097                "      { a.~T() } noexcept;\n"
24098                "      requires Same<T *, decltype(new T)>;\n"
24099                "      requires Same<T *, decltype(new T[n])>;\n"
24100                "      { delete new T; };\n"
24101                "      { delete new T[n]; };\n"
24102                "    };",
24103                Style);
24104 
24105   // The following tests are invalid C++, we just want to make sure we don't
24106   // assert.
24107   verifyFormat("template <typename T>\n"
24108                "concept C = requires C2<T>;");
24109 
24110   verifyFormat("template <typename T>\n"
24111                "concept C = 5 + 4;");
24112 
24113   verifyFormat("template <typename T>\n"
24114                "concept C =\n"
24115                "class X;");
24116 
24117   verifyFormat("template <typename T>\n"
24118                "concept C = [] && true;");
24119 
24120   verifyFormat("template <typename T>\n"
24121                "concept C = [] && requires(T t) { typename T::size_type; };");
24122 }
24123 
24124 TEST_F(FormatTest, RequiresClausesPositions) {
24125   auto Style = getLLVMStyle();
24126   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
24127   EXPECT_EQ(Style.IndentRequiresClause, true);
24128 
24129   verifyFormat("template <typename T>\n"
24130                "  requires(Foo<T> && std::trait<T>)\n"
24131                "struct Bar;",
24132                Style);
24133 
24134   verifyFormat("template <typename T>\n"
24135                "  requires(Foo<T> && std::trait<T>)\n"
24136                "class Bar {\n"
24137                "public:\n"
24138                "  Bar(T t);\n"
24139                "  bool baz();\n"
24140                "};",
24141                Style);
24142 
24143   verifyFormat(
24144       "template <typename T>\n"
24145       "  requires requires(T &&t) {\n"
24146       "             typename T::I;\n"
24147       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
24148       "           }\n"
24149       "Bar(T) -> Bar<typename T::I>;",
24150       Style);
24151 
24152   verifyFormat("template <typename T>\n"
24153                "  requires(Foo<T> && std::trait<T>)\n"
24154                "constexpr T MyGlobal;",
24155                Style);
24156 
24157   verifyFormat("template <typename T>\n"
24158                "  requires Foo<T> && requires(T t) {\n"
24159                "                       { t.baz() } -> std::same_as<bool>;\n"
24160                "                       requires std::same_as<T::Factor, int>;\n"
24161                "                     }\n"
24162                "inline int bar(T t) {\n"
24163                "  return t.baz() ? T::Factor : 5;\n"
24164                "}",
24165                Style);
24166 
24167   verifyFormat("template <typename T>\n"
24168                "inline int bar(T t)\n"
24169                "  requires Foo<T> && requires(T t) {\n"
24170                "                       { t.baz() } -> std::same_as<bool>;\n"
24171                "                       requires std::same_as<T::Factor, int>;\n"
24172                "                     }\n"
24173                "{\n"
24174                "  return t.baz() ? T::Factor : 5;\n"
24175                "}",
24176                Style);
24177 
24178   verifyFormat("template <typename T>\n"
24179                "  requires F<T>\n"
24180                "int bar(T t) {\n"
24181                "  return 5;\n"
24182                "}",
24183                Style);
24184 
24185   verifyFormat("template <typename T>\n"
24186                "int bar(T t)\n"
24187                "  requires F<T>\n"
24188                "{\n"
24189                "  return 5;\n"
24190                "}",
24191                Style);
24192 
24193   verifyFormat("template <typename T>\n"
24194                "int bar(T t)\n"
24195                "  requires F<T>;",
24196                Style);
24197 
24198   Style.IndentRequiresClause = false;
24199   verifyFormat("template <typename T>\n"
24200                "requires F<T>\n"
24201                "int bar(T t) {\n"
24202                "  return 5;\n"
24203                "}",
24204                Style);
24205 
24206   verifyFormat("template <typename T>\n"
24207                "int bar(T t)\n"
24208                "requires F<T>\n"
24209                "{\n"
24210                "  return 5;\n"
24211                "}",
24212                Style);
24213 
24214   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
24215   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
24216                "template <typename T> requires Foo<T> void bar() {}\n"
24217                "template <typename T> void bar() requires Foo<T> {}\n"
24218                "template <typename T> void bar() requires Foo<T>;\n"
24219                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
24220                Style);
24221 
24222   auto ColumnStyle = Style;
24223   ColumnStyle.ColumnLimit = 40;
24224   verifyFormat("template <typename AAAAAAA>\n"
24225                "requires Foo<T> struct Bar {};\n"
24226                "template <typename AAAAAAA>\n"
24227                "requires Foo<T> void bar() {}\n"
24228                "template <typename AAAAAAA>\n"
24229                "void bar() requires Foo<T> {}\n"
24230                "template <typename AAAAAAA>\n"
24231                "requires Foo<T> Baz(T) -> Baz<T>;",
24232                ColumnStyle);
24233 
24234   verifyFormat("template <typename T>\n"
24235                "requires Foo<AAAAAAA> struct Bar {};\n"
24236                "template <typename T>\n"
24237                "requires Foo<AAAAAAA> void bar() {}\n"
24238                "template <typename T>\n"
24239                "void bar() requires Foo<AAAAAAA> {}\n"
24240                "template <typename T>\n"
24241                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
24242                ColumnStyle);
24243 
24244   verifyFormat("template <typename AAAAAAA>\n"
24245                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24246                "struct Bar {};\n"
24247                "template <typename AAAAAAA>\n"
24248                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24249                "void bar() {}\n"
24250                "template <typename AAAAAAA>\n"
24251                "void bar()\n"
24252                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24253                "template <typename AAAAAAA>\n"
24254                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24255                "template <typename AAAAAAA>\n"
24256                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24257                "Bar(T) -> Bar<T>;",
24258                ColumnStyle);
24259 
24260   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24261   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24262 
24263   verifyFormat("template <typename T>\n"
24264                "requires Foo<T> struct Bar {};\n"
24265                "template <typename T>\n"
24266                "requires Foo<T> void bar() {}\n"
24267                "template <typename T>\n"
24268                "void bar()\n"
24269                "requires Foo<T> {}\n"
24270                "template <typename T>\n"
24271                "void bar()\n"
24272                "requires Foo<T>;\n"
24273                "template <typename T>\n"
24274                "requires Foo<T> Bar(T) -> Bar<T>;",
24275                Style);
24276 
24277   verifyFormat("template <typename AAAAAAA>\n"
24278                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24279                "struct Bar {};\n"
24280                "template <typename AAAAAAA>\n"
24281                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24282                "void bar() {}\n"
24283                "template <typename AAAAAAA>\n"
24284                "void bar()\n"
24285                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24286                "template <typename AAAAAAA>\n"
24287                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24288                "template <typename AAAAAAA>\n"
24289                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24290                "Bar(T) -> Bar<T>;",
24291                ColumnStyle);
24292 
24293   Style.IndentRequiresClause = true;
24294   ColumnStyle.IndentRequiresClause = true;
24295 
24296   verifyFormat("template <typename T>\n"
24297                "  requires Foo<T> struct Bar {};\n"
24298                "template <typename T>\n"
24299                "  requires Foo<T> void bar() {}\n"
24300                "template <typename T>\n"
24301                "void bar()\n"
24302                "  requires Foo<T> {}\n"
24303                "template <typename T>\n"
24304                "  requires Foo<T> Bar(T) -> Bar<T>;",
24305                Style);
24306 
24307   verifyFormat("template <typename AAAAAAA>\n"
24308                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24309                "struct Bar {};\n"
24310                "template <typename AAAAAAA>\n"
24311                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24312                "void bar() {}\n"
24313                "template <typename AAAAAAA>\n"
24314                "void bar()\n"
24315                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24316                "template <typename AAAAAAA>\n"
24317                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24318                "template <typename AAAAAAA>\n"
24319                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24320                "Bar(T) -> Bar<T>;",
24321                ColumnStyle);
24322 
24323   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24324   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24325 
24326   verifyFormat("template <typename T> requires Foo<T>\n"
24327                "struct Bar {};\n"
24328                "template <typename T> requires Foo<T>\n"
24329                "void bar() {}\n"
24330                "template <typename T>\n"
24331                "void bar() requires Foo<T>\n"
24332                "{}\n"
24333                "template <typename T> void bar() requires Foo<T>;\n"
24334                "template <typename T> requires Foo<T>\n"
24335                "Bar(T) -> Bar<T>;",
24336                Style);
24337 
24338   verifyFormat("template <typename AAAAAAA>\n"
24339                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24340                "struct Bar {};\n"
24341                "template <typename AAAAAAA>\n"
24342                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24343                "void bar() {}\n"
24344                "template <typename AAAAAAA>\n"
24345                "void bar()\n"
24346                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24347                "{}\n"
24348                "template <typename AAAAAAA>\n"
24349                "requires Foo<AAAAAAAA>\n"
24350                "Bar(T) -> Bar<T>;\n"
24351                "template <typename AAAAAAA>\n"
24352                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24353                "Bar(T) -> Bar<T>;",
24354                ColumnStyle);
24355 }
24356 
24357 TEST_F(FormatTest, RequiresClauses) {
24358   verifyFormat("struct [[nodiscard]] zero_t {\n"
24359                "  template <class T>\n"
24360                "    requires requires { number_zero_v<T>; }\n"
24361                "  [[nodiscard]] constexpr operator T() const {\n"
24362                "    return number_zero_v<T>;\n"
24363                "  }\n"
24364                "};");
24365 
24366   auto Style = getLLVMStyle();
24367 
24368   verifyFormat(
24369       "template <typename T>\n"
24370       "  requires is_default_constructible_v<hash<T>> and\n"
24371       "           is_copy_constructible_v<hash<T>> and\n"
24372       "           is_move_constructible_v<hash<T>> and\n"
24373       "           is_copy_assignable_v<hash<T>> and "
24374       "is_move_assignable_v<hash<T>> and\n"
24375       "           is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
24376       "           is_callable_v<hash<T>(T)> and\n"
24377       "           is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
24378       "           is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
24379       "           is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
24380       "struct S {};",
24381       Style);
24382 
24383   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
24384   verifyFormat(
24385       "template <typename T>\n"
24386       "  requires is_default_constructible_v<hash<T>>\n"
24387       "           and is_copy_constructible_v<hash<T>>\n"
24388       "           and is_move_constructible_v<hash<T>>\n"
24389       "           and is_copy_assignable_v<hash<T>> and "
24390       "is_move_assignable_v<hash<T>>\n"
24391       "           and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
24392       "           and is_callable_v<hash<T>(T)>\n"
24393       "           and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
24394       "           and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
24395       "           and is_same_v<size_t, decltype(hash<T>(declval<const T "
24396       "&>()))>\n"
24397       "struct S {};",
24398       Style);
24399 
24400   // Not a clause, but we once hit an assert.
24401   verifyFormat("#if 0\n"
24402                "#else\n"
24403                "foo();\n"
24404                "#endif\n"
24405                "bar(requires);");
24406 }
24407 
24408 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24409   FormatStyle Style = getLLVMStyle();
24410   StringRef Source = "void Foo::slot() {\n"
24411                      "  unsigned char MyChar = 'x';\n"
24412                      "  emit signal(MyChar);\n"
24413                      "  Q_EMIT signal(MyChar);\n"
24414                      "}";
24415 
24416   EXPECT_EQ(Source, format(Source, Style));
24417 
24418   Style.AlignConsecutiveDeclarations.Enabled = true;
24419   EXPECT_EQ("void Foo::slot() {\n"
24420             "  unsigned char MyChar = 'x';\n"
24421             "  emit          signal(MyChar);\n"
24422             "  Q_EMIT signal(MyChar);\n"
24423             "}",
24424             format(Source, Style));
24425 
24426   Style.StatementAttributeLikeMacros.push_back("emit");
24427   EXPECT_EQ(Source, format(Source, Style));
24428 
24429   Style.StatementAttributeLikeMacros = {};
24430   EXPECT_EQ("void Foo::slot() {\n"
24431             "  unsigned char MyChar = 'x';\n"
24432             "  emit          signal(MyChar);\n"
24433             "  Q_EMIT        signal(MyChar);\n"
24434             "}",
24435             format(Source, Style));
24436 }
24437 
24438 TEST_F(FormatTest, IndentAccessModifiers) {
24439   FormatStyle Style = getLLVMStyle();
24440   Style.IndentAccessModifiers = true;
24441   // Members are *two* levels below the record;
24442   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24443   verifyFormat("class C {\n"
24444                "    int i;\n"
24445                "};\n",
24446                Style);
24447   verifyFormat("union C {\n"
24448                "    int i;\n"
24449                "    unsigned u;\n"
24450                "};\n",
24451                Style);
24452   // Access modifiers should be indented one level below the record.
24453   verifyFormat("class C {\n"
24454                "  public:\n"
24455                "    int i;\n"
24456                "};\n",
24457                Style);
24458   verifyFormat("struct S {\n"
24459                "  private:\n"
24460                "    class C {\n"
24461                "        int j;\n"
24462                "\n"
24463                "      public:\n"
24464                "        C();\n"
24465                "    };\n"
24466                "\n"
24467                "  public:\n"
24468                "    int i;\n"
24469                "};\n",
24470                Style);
24471   // Enumerations are not records and should be unaffected.
24472   Style.AllowShortEnumsOnASingleLine = false;
24473   verifyFormat("enum class E {\n"
24474                "  A,\n"
24475                "  B\n"
24476                "};\n",
24477                Style);
24478   // Test with a different indentation width;
24479   // also proves that the result is Style.AccessModifierOffset agnostic.
24480   Style.IndentWidth = 3;
24481   verifyFormat("class C {\n"
24482                "   public:\n"
24483                "      int i;\n"
24484                "};\n",
24485                Style);
24486 }
24487 
24488 TEST_F(FormatTest, LimitlessStringsAndComments) {
24489   auto Style = getLLVMStyleWithColumns(0);
24490   constexpr StringRef Code =
24491       "/**\n"
24492       " * This is a multiline comment with quite some long lines, at least for "
24493       "the LLVM Style.\n"
24494       " * We will redo this with strings and line comments. Just to  check if "
24495       "everything is working.\n"
24496       " */\n"
24497       "bool foo() {\n"
24498       "  /* Single line multi line comment. */\n"
24499       "  const std::string String = \"This is a multiline string with quite "
24500       "some long lines, at least for the LLVM Style.\"\n"
24501       "                             \"We already did it with multi line "
24502       "comments, and we will do it with line comments. Just to check if "
24503       "everything is working.\";\n"
24504       "  // This is a line comment (block) with quite some long lines, at "
24505       "least for the LLVM Style.\n"
24506       "  // We already did this with multi line comments and strings. Just to "
24507       "check if everything is working.\n"
24508       "  const std::string SmallString = \"Hello World\";\n"
24509       "  // Small line comment\n"
24510       "  return String.size() > SmallString.size();\n"
24511       "}";
24512   EXPECT_EQ(Code, format(Code, Style));
24513 }
24514 
24515 TEST_F(FormatTest, FormatDecayCopy) {
24516   // error cases from unit tests
24517   verifyFormat("foo(auto())");
24518   verifyFormat("foo(auto{})");
24519   verifyFormat("foo(auto({}))");
24520   verifyFormat("foo(auto{{}})");
24521 
24522   verifyFormat("foo(auto(1))");
24523   verifyFormat("foo(auto{1})");
24524   verifyFormat("foo(new auto(1))");
24525   verifyFormat("foo(new auto{1})");
24526   verifyFormat("decltype(auto(1)) x;");
24527   verifyFormat("decltype(auto{1}) x;");
24528   verifyFormat("auto(x);");
24529   verifyFormat("auto{x};");
24530   verifyFormat("new auto{x};");
24531   verifyFormat("auto{x} = y;");
24532   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24533                                 // the user's own fault
24534   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24535                                          // clearly the user's own fault
24536   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24537 }
24538 
24539 TEST_F(FormatTest, Cpp20ModulesSupport) {
24540   FormatStyle Style = getLLVMStyle();
24541   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24542   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24543 
24544   verifyFormat("export import foo;", Style);
24545   verifyFormat("export import foo:bar;", Style);
24546   verifyFormat("export import foo.bar;", Style);
24547   verifyFormat("export import foo.bar:baz;", Style);
24548   verifyFormat("export import :bar;", Style);
24549   verifyFormat("export module foo:bar;", Style);
24550   verifyFormat("export module foo;", Style);
24551   verifyFormat("export module foo.bar;", Style);
24552   verifyFormat("export module foo.bar:baz;", Style);
24553   verifyFormat("export import <string_view>;", Style);
24554 
24555   verifyFormat("export type_name var;", Style);
24556   verifyFormat("template <class T> export using A = B<T>;", Style);
24557   verifyFormat("export using A = B;", Style);
24558   verifyFormat("export int func() {\n"
24559                "  foo();\n"
24560                "}",
24561                Style);
24562   verifyFormat("export struct {\n"
24563                "  int foo;\n"
24564                "};",
24565                Style);
24566   verifyFormat("export {\n"
24567                "  int foo;\n"
24568                "};",
24569                Style);
24570   verifyFormat("export export char const *hello() { return \"hello\"; }");
24571 
24572   verifyFormat("import bar;", Style);
24573   verifyFormat("import foo.bar;", Style);
24574   verifyFormat("import foo:bar;", Style);
24575   verifyFormat("import :bar;", Style);
24576   verifyFormat("import <ctime>;", Style);
24577   verifyFormat("import \"header\";", Style);
24578 
24579   verifyFormat("module foo;", Style);
24580   verifyFormat("module foo:bar;", Style);
24581   verifyFormat("module foo.bar;", Style);
24582   verifyFormat("module;", Style);
24583 
24584   verifyFormat("export namespace hi {\n"
24585                "const char *sayhi();\n"
24586                "}",
24587                Style);
24588 
24589   verifyFormat("module :private;", Style);
24590   verifyFormat("import <foo/bar.h>;", Style);
24591   verifyFormat("import foo...bar;", Style);
24592   verifyFormat("import ..........;", Style);
24593   verifyFormat("module foo:private;", Style);
24594   verifyFormat("import a", Style);
24595   verifyFormat("module a", Style);
24596   verifyFormat("export import a", Style);
24597   verifyFormat("export module a", Style);
24598 
24599   verifyFormat("import", Style);
24600   verifyFormat("module", Style);
24601   verifyFormat("export", Style);
24602 }
24603 
24604 TEST_F(FormatTest, CoroutineForCoawait) {
24605   FormatStyle Style = getLLVMStyle();
24606   verifyFormat("for co_await (auto x : range())\n  ;");
24607   verifyFormat("for (auto i : arr) {\n"
24608                "}",
24609                Style);
24610   verifyFormat("for co_await (auto i : arr) {\n"
24611                "}",
24612                Style);
24613   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24614                "}",
24615                Style);
24616 }
24617 
24618 TEST_F(FormatTest, CoroutineCoAwait) {
24619   verifyFormat("int x = co_await foo();");
24620   verifyFormat("int x = (co_await foo());");
24621   verifyFormat("co_await (42);");
24622   verifyFormat("void operator co_await(int);");
24623   verifyFormat("void operator co_await(a);");
24624   verifyFormat("co_await a;");
24625   verifyFormat("co_await missing_await_resume{};");
24626   verifyFormat("co_await a; // comment");
24627   verifyFormat("void test0() { co_await a; }");
24628   verifyFormat("co_await co_await co_await foo();");
24629   verifyFormat("co_await foo().bar();");
24630   verifyFormat("co_await [this]() -> Task { co_return x; }");
24631   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24632                "foo(); }(x, y);");
24633 
24634   FormatStyle Style = getLLVMStyleWithColumns(40);
24635   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24636                "  co_return co_await foo();\n"
24637                "}(x, y);",
24638                Style);
24639   verifyFormat("co_await;");
24640 }
24641 
24642 TEST_F(FormatTest, CoroutineCoYield) {
24643   verifyFormat("int x = co_yield foo();");
24644   verifyFormat("int x = (co_yield foo());");
24645   verifyFormat("co_yield (42);");
24646   verifyFormat("co_yield {42};");
24647   verifyFormat("co_yield 42;");
24648   verifyFormat("co_yield n++;");
24649   verifyFormat("co_yield ++n;");
24650   verifyFormat("co_yield;");
24651 }
24652 
24653 TEST_F(FormatTest, CoroutineCoReturn) {
24654   verifyFormat("co_return (42);");
24655   verifyFormat("co_return;");
24656   verifyFormat("co_return {};");
24657   verifyFormat("co_return x;");
24658   verifyFormat("co_return co_await foo();");
24659   verifyFormat("co_return co_yield foo();");
24660 }
24661 
24662 TEST_F(FormatTest, EmptyShortBlock) {
24663   auto Style = getLLVMStyle();
24664   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24665 
24666   verifyFormat("try {\n"
24667                "  doA();\n"
24668                "} catch (Exception &e) {\n"
24669                "  e.printStackTrace();\n"
24670                "}\n",
24671                Style);
24672 
24673   verifyFormat("try {\n"
24674                "  doA();\n"
24675                "} catch (Exception &e) {}\n",
24676                Style);
24677 }
24678 
24679 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
24680   auto Style = getLLVMStyle();
24681 
24682   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
24683   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
24684   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
24685   verifyFormat("struct Y<[] { return 0; }> {};", Style);
24686 
24687   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
24688   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
24689 }
24690 
24691 TEST_F(FormatTest, InsertBraces) {
24692   FormatStyle Style = getLLVMStyle();
24693   Style.InsertBraces = true;
24694 
24695   verifyFormat("// clang-format off\n"
24696                "// comment\n"
24697                "if (a) f();\n"
24698                "// clang-format on\n"
24699                "if (b) {\n"
24700                "  g();\n"
24701                "}",
24702                "// clang-format off\n"
24703                "// comment\n"
24704                "if (a) f();\n"
24705                "// clang-format on\n"
24706                "if (b) g();",
24707                Style);
24708 
24709   verifyFormat("if (a) {\n"
24710                "  switch (b) {\n"
24711                "  case 1:\n"
24712                "    c = 0;\n"
24713                "    break;\n"
24714                "  default:\n"
24715                "    c = 1;\n"
24716                "  }\n"
24717                "}",
24718                "if (a)\n"
24719                "  switch (b) {\n"
24720                "  case 1:\n"
24721                "    c = 0;\n"
24722                "    break;\n"
24723                "  default:\n"
24724                "    c = 1;\n"
24725                "  }",
24726                Style);
24727 
24728   verifyFormat("for (auto node : nodes) {\n"
24729                "  if (node) {\n"
24730                "    break;\n"
24731                "  }\n"
24732                "}",
24733                "for (auto node : nodes)\n"
24734                "  if (node)\n"
24735                "    break;",
24736                Style);
24737 
24738   verifyFormat("for (auto node : nodes) {\n"
24739                "  if (node)\n"
24740                "}",
24741                "for (auto node : nodes)\n"
24742                "  if (node)",
24743                Style);
24744 
24745   verifyFormat("do {\n"
24746                "  --a;\n"
24747                "} while (a);",
24748                "do\n"
24749                "  --a;\n"
24750                "while (a);",
24751                Style);
24752 
24753   verifyFormat("if (i) {\n"
24754                "  ++i;\n"
24755                "} else {\n"
24756                "  --i;\n"
24757                "}",
24758                "if (i)\n"
24759                "  ++i;\n"
24760                "else {\n"
24761                "  --i;\n"
24762                "}",
24763                Style);
24764 
24765   verifyFormat("void f() {\n"
24766                "  while (j--) {\n"
24767                "    while (i) {\n"
24768                "      --i;\n"
24769                "    }\n"
24770                "  }\n"
24771                "}",
24772                "void f() {\n"
24773                "  while (j--)\n"
24774                "    while (i)\n"
24775                "      --i;\n"
24776                "}",
24777                Style);
24778 
24779   verifyFormat("f({\n"
24780                "  if (a) {\n"
24781                "    g();\n"
24782                "  }\n"
24783                "});",
24784                "f({\n"
24785                "  if (a)\n"
24786                "    g();\n"
24787                "});",
24788                Style);
24789 
24790   verifyFormat("if (a) {\n"
24791                "  f();\n"
24792                "} else if (b) {\n"
24793                "  g();\n"
24794                "} else {\n"
24795                "  h();\n"
24796                "}",
24797                "if (a)\n"
24798                "  f();\n"
24799                "else if (b)\n"
24800                "  g();\n"
24801                "else\n"
24802                "  h();",
24803                Style);
24804 
24805   verifyFormat("if (a) {\n"
24806                "  f();\n"
24807                "}\n"
24808                "// comment\n"
24809                "/* comment */",
24810                "if (a)\n"
24811                "  f();\n"
24812                "// comment\n"
24813                "/* comment */",
24814                Style);
24815 
24816   verifyFormat("if (a) {\n"
24817                "  // foo\n"
24818                "  // bar\n"
24819                "  f();\n"
24820                "}",
24821                "if (a)\n"
24822                "  // foo\n"
24823                "  // bar\n"
24824                "  f();",
24825                Style);
24826 
24827   verifyFormat("if (a) { // comment\n"
24828                "  // comment\n"
24829                "  f();\n"
24830                "}",
24831                "if (a) // comment\n"
24832                "  // comment\n"
24833                "  f();",
24834                Style);
24835 
24836   verifyFormat("if (a) {\n"
24837                "  f(); // comment\n"
24838                "}",
24839                "if (a)\n"
24840                "  f(); // comment",
24841                Style);
24842 
24843   verifyFormat("if (a) {\n"
24844                "  f();\n"
24845                "}\n"
24846                "#undef A\n"
24847                "#undef B",
24848                "if (a)\n"
24849                "  f();\n"
24850                "#undef A\n"
24851                "#undef B",
24852                Style);
24853 
24854   verifyFormat("if (a)\n"
24855                "#ifdef A\n"
24856                "  f();\n"
24857                "#else\n"
24858                "  g();\n"
24859                "#endif",
24860                Style);
24861 
24862   verifyFormat("#if 0\n"
24863                "#elif 1\n"
24864                "#endif\n"
24865                "void f() {\n"
24866                "  if (a) {\n"
24867                "    g();\n"
24868                "  }\n"
24869                "}",
24870                "#if 0\n"
24871                "#elif 1\n"
24872                "#endif\n"
24873                "void f() {\n"
24874                "  if (a) g();\n"
24875                "}",
24876                Style);
24877 
24878   Style.ColumnLimit = 15;
24879 
24880   verifyFormat("#define A     \\\n"
24881                "  if (a)      \\\n"
24882                "    f();",
24883                Style);
24884 
24885   verifyFormat("if (a + b >\n"
24886                "    c) {\n"
24887                "  f();\n"
24888                "}",
24889                "if (a + b > c)\n"
24890                "  f();",
24891                Style);
24892 }
24893 
24894 TEST_F(FormatTest, RemoveBraces) {
24895   FormatStyle Style = getLLVMStyle();
24896   Style.RemoveBracesLLVM = true;
24897 
24898   // The following eight test cases are fully-braced versions of the examples at
24899   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
24900   // statement-bodies-of-if-else-loop-statements".
24901 
24902   // 1. Omit the braces, since the body is simple and clearly associated with
24903   // the if.
24904   verifyFormat("if (isa<FunctionDecl>(D))\n"
24905                "  handleFunctionDecl(D);\n"
24906                "else if (isa<VarDecl>(D))\n"
24907                "  handleVarDecl(D);",
24908                "if (isa<FunctionDecl>(D)) {\n"
24909                "  handleFunctionDecl(D);\n"
24910                "} else if (isa<VarDecl>(D)) {\n"
24911                "  handleVarDecl(D);\n"
24912                "}",
24913                Style);
24914 
24915   // 2. Here we document the condition itself and not the body.
24916   verifyFormat("if (isa<VarDecl>(D)) {\n"
24917                "  // It is necessary that we explain the situation with this\n"
24918                "  // surprisingly long comment, so it would be unclear\n"
24919                "  // without the braces whether the following statement is in\n"
24920                "  // the scope of the `if`.\n"
24921                "  // Because the condition is documented, we can't really\n"
24922                "  // hoist this comment that applies to the body above the\n"
24923                "  // if.\n"
24924                "  handleOtherDecl(D);\n"
24925                "}",
24926                Style);
24927 
24928   // 3. Use braces on the outer `if` to avoid a potential dangling else
24929   // situation.
24930   verifyFormat("if (isa<VarDecl>(D)) {\n"
24931                "  for (auto *A : D.attrs())\n"
24932                "    if (shouldProcessAttr(A))\n"
24933                "      handleAttr(A);\n"
24934                "}",
24935                "if (isa<VarDecl>(D)) {\n"
24936                "  for (auto *A : D.attrs()) {\n"
24937                "    if (shouldProcessAttr(A)) {\n"
24938                "      handleAttr(A);\n"
24939                "    }\n"
24940                "  }\n"
24941                "}",
24942                Style);
24943 
24944   // 4. Use braces for the `if` block to keep it uniform with the else block.
24945   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24946                "  handleFunctionDecl(D);\n"
24947                "} else {\n"
24948                "  // In this else case, it is necessary that we explain the\n"
24949                "  // situation with this surprisingly long comment, so it\n"
24950                "  // would be unclear without the braces whether the\n"
24951                "  // following statement is in the scope of the `if`.\n"
24952                "  handleOtherDecl(D);\n"
24953                "}",
24954                Style);
24955 
24956   // 5. This should also omit braces.  The `for` loop contains only a single
24957   // statement, so it shouldn't have braces.  The `if` also only contains a
24958   // single simple statement (the for loop), so it also should omit braces.
24959   verifyFormat("if (isa<FunctionDecl>(D))\n"
24960                "  for (auto *A : D.attrs())\n"
24961                "    handleAttr(A);",
24962                "if (isa<FunctionDecl>(D)) {\n"
24963                "  for (auto *A : D.attrs()) {\n"
24964                "    handleAttr(A);\n"
24965                "  }\n"
24966                "}",
24967                Style);
24968 
24969   // 6. Use braces for the outer `if` since the nested `for` is braced.
24970   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24971                "  for (auto *A : D.attrs()) {\n"
24972                "    // In this for loop body, it is necessary that we explain\n"
24973                "    // the situation with this surprisingly long comment,\n"
24974                "    // forcing braces on the `for` block.\n"
24975                "    handleAttr(A);\n"
24976                "  }\n"
24977                "}",
24978                Style);
24979 
24980   // 7. Use braces on the outer block because there are more than two levels of
24981   // nesting.
24982   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24983                "  for (auto *A : D.attrs())\n"
24984                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
24985                "      handleAttrOnDecl(D, A, i);\n"
24986                "}",
24987                "if (isa<FunctionDecl>(D)) {\n"
24988                "  for (auto *A : D.attrs()) {\n"
24989                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
24990                "      handleAttrOnDecl(D, A, i);\n"
24991                "    }\n"
24992                "  }\n"
24993                "}",
24994                Style);
24995 
24996   // 8. Use braces on the outer block because of a nested `if`, otherwise the
24997   // compiler would warn: `add explicit braces to avoid dangling else`
24998   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
24999                "  if (shouldProcess(D))\n"
25000                "    handleVarDecl(D);\n"
25001                "  else\n"
25002                "    markAsIgnored(D);\n"
25003                "}",
25004                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25005                "  if (shouldProcess(D)) {\n"
25006                "    handleVarDecl(D);\n"
25007                "  } else {\n"
25008                "    markAsIgnored(D);\n"
25009                "  }\n"
25010                "}",
25011                Style);
25012 
25013   verifyFormat("// clang-format off\n"
25014                "// comment\n"
25015                "while (i > 0) { --i; }\n"
25016                "// clang-format on\n"
25017                "while (j < 0)\n"
25018                "  ++j;",
25019                "// clang-format off\n"
25020                "// comment\n"
25021                "while (i > 0) { --i; }\n"
25022                "// clang-format on\n"
25023                "while (j < 0) { ++j; }",
25024                Style);
25025 
25026   verifyFormat("if (a)\n"
25027                "  b; // comment\n"
25028                "else if (c)\n"
25029                "  d; /* comment */\n"
25030                "else\n"
25031                "  e;",
25032                "if (a) {\n"
25033                "  b; // comment\n"
25034                "} else if (c) {\n"
25035                "  d; /* comment */\n"
25036                "} else {\n"
25037                "  e;\n"
25038                "}",
25039                Style);
25040 
25041   verifyFormat("if (a) {\n"
25042                "  b;\n"
25043                "  c;\n"
25044                "} else if (d) {\n"
25045                "  e;\n"
25046                "}",
25047                Style);
25048 
25049   verifyFormat("if (a) {\n"
25050                "#undef NDEBUG\n"
25051                "  b;\n"
25052                "} else {\n"
25053                "  c;\n"
25054                "}",
25055                Style);
25056 
25057   verifyFormat("if (a) {\n"
25058                "  // comment\n"
25059                "} else if (b) {\n"
25060                "  c;\n"
25061                "}",
25062                Style);
25063 
25064   verifyFormat("if (a) {\n"
25065                "  b;\n"
25066                "} else {\n"
25067                "  { c; }\n"
25068                "}",
25069                Style);
25070 
25071   verifyFormat("if (a) {\n"
25072                "  if (b) // comment\n"
25073                "    c;\n"
25074                "} else if (d) {\n"
25075                "  e;\n"
25076                "}",
25077                "if (a) {\n"
25078                "  if (b) { // comment\n"
25079                "    c;\n"
25080                "  }\n"
25081                "} else if (d) {\n"
25082                "  e;\n"
25083                "}",
25084                Style);
25085 
25086   verifyFormat("if (a) {\n"
25087                "  if (b) {\n"
25088                "    c;\n"
25089                "    // comment\n"
25090                "  } else if (d) {\n"
25091                "    e;\n"
25092                "  }\n"
25093                "}",
25094                Style);
25095 
25096   verifyFormat("if (a) {\n"
25097                "  if (b)\n"
25098                "    c;\n"
25099                "}",
25100                "if (a) {\n"
25101                "  if (b) {\n"
25102                "    c;\n"
25103                "  }\n"
25104                "}",
25105                Style);
25106 
25107   verifyFormat("if (a)\n"
25108                "  if (b)\n"
25109                "    c;\n"
25110                "  else\n"
25111                "    d;\n"
25112                "else\n"
25113                "  e;",
25114                "if (a) {\n"
25115                "  if (b) {\n"
25116                "    c;\n"
25117                "  } else {\n"
25118                "    d;\n"
25119                "  }\n"
25120                "} else {\n"
25121                "  e;\n"
25122                "}",
25123                Style);
25124 
25125   verifyFormat("if (a) {\n"
25126                "  // comment\n"
25127                "  if (b)\n"
25128                "    c;\n"
25129                "  else if (d)\n"
25130                "    e;\n"
25131                "} else {\n"
25132                "  g;\n"
25133                "}",
25134                "if (a) {\n"
25135                "  // comment\n"
25136                "  if (b) {\n"
25137                "    c;\n"
25138                "  } else if (d) {\n"
25139                "    e;\n"
25140                "  }\n"
25141                "} else {\n"
25142                "  g;\n"
25143                "}",
25144                Style);
25145 
25146   verifyFormat("if (a)\n"
25147                "  b;\n"
25148                "else if (c)\n"
25149                "  d;\n"
25150                "else\n"
25151                "  e;",
25152                "if (a) {\n"
25153                "  b;\n"
25154                "} else {\n"
25155                "  if (c) {\n"
25156                "    d;\n"
25157                "  } else {\n"
25158                "    e;\n"
25159                "  }\n"
25160                "}",
25161                Style);
25162 
25163   verifyFormat("if (a) {\n"
25164                "  if (b)\n"
25165                "    c;\n"
25166                "  else if (d)\n"
25167                "    e;\n"
25168                "} else {\n"
25169                "  g;\n"
25170                "}",
25171                "if (a) {\n"
25172                "  if (b)\n"
25173                "    c;\n"
25174                "  else {\n"
25175                "    if (d)\n"
25176                "      e;\n"
25177                "  }\n"
25178                "} else {\n"
25179                "  g;\n"
25180                "}",
25181                Style);
25182 
25183   verifyFormat("if (a)\n"
25184                "  b;\n"
25185                "else if (c)\n"
25186                "  while (d)\n"
25187                "    e;\n"
25188                "// comment",
25189                "if (a)\n"
25190                "{\n"
25191                "  b;\n"
25192                "} else if (c) {\n"
25193                "  while (d) {\n"
25194                "    e;\n"
25195                "  }\n"
25196                "}\n"
25197                "// comment",
25198                Style);
25199 
25200   verifyFormat("if (a) {\n"
25201                "  b;\n"
25202                "} else if (c) {\n"
25203                "  d;\n"
25204                "} else {\n"
25205                "  e;\n"
25206                "  g;\n"
25207                "}",
25208                Style);
25209 
25210   verifyFormat("if (a) {\n"
25211                "  b;\n"
25212                "} else if (c) {\n"
25213                "  d;\n"
25214                "} else {\n"
25215                "  e;\n"
25216                "} // comment",
25217                Style);
25218 
25219   verifyFormat("int abs = [](int i) {\n"
25220                "  if (i >= 0)\n"
25221                "    return i;\n"
25222                "  return -i;\n"
25223                "};",
25224                "int abs = [](int i) {\n"
25225                "  if (i >= 0) {\n"
25226                "    return i;\n"
25227                "  }\n"
25228                "  return -i;\n"
25229                "};",
25230                Style);
25231 
25232   verifyFormat("if (a)\n"
25233                "  foo();\n"
25234                "else\n"
25235                "  bar();",
25236                "if (a)\n"
25237                "{\n"
25238                "  foo();\n"
25239                "}\n"
25240                "else\n"
25241                "{\n"
25242                "  bar();\n"
25243                "}",
25244                Style);
25245 
25246   verifyFormat("if (a) {\n"
25247                "Label:\n"
25248                "}",
25249                Style);
25250 
25251   verifyFormat("if (a) {\n"
25252                "Label:\n"
25253                "  f();\n"
25254                "}",
25255                Style);
25256 
25257   verifyFormat("if (a) {\n"
25258                "  f();\n"
25259                "Label:\n"
25260                "}",
25261                Style);
25262 
25263   // FIXME: See https://github.com/llvm/llvm-project/issues/53543.
25264 #if 0
25265   Style.ColumnLimit = 65;
25266 
25267   verifyFormat("if (condition) {\n"
25268                "  ff(Indices,\n"
25269                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25270                "} else {\n"
25271                "  ff(Indices,\n"
25272                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25273                "}",
25274                Style);
25275 
25276   Style.ColumnLimit = 20;
25277 
25278   verifyFormat("if (a) {\n"
25279                "  b = c + // 1 -\n"
25280                "      d;\n"
25281                "}",
25282                Style);
25283 
25284   verifyFormat("if (a) {\n"
25285                "  b = c >= 0 ? d\n"
25286                "             : e;\n"
25287                "}",
25288                "if (a) {\n"
25289                "  b = c >= 0 ? d : e;\n"
25290                "}",
25291                Style);
25292 #endif
25293 
25294   Style.ColumnLimit = 20;
25295 
25296   verifyFormat("if (a)\n"
25297                "  b = c > 0 ? d : e;",
25298                "if (a) {\n"
25299                "  b = c > 0 ? d : e;\n"
25300                "}",
25301                Style);
25302 
25303   Style.ColumnLimit = 0;
25304 
25305   verifyFormat("if (a)\n"
25306                "  b234567890223456789032345678904234567890 = "
25307                "c234567890223456789032345678904234567890;",
25308                "if (a) {\n"
25309                "  b234567890223456789032345678904234567890 = "
25310                "c234567890223456789032345678904234567890;\n"
25311                "}",
25312                Style);
25313 }
25314 
25315 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
25316   auto Style = getLLVMStyle();
25317 
25318   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
25319                     "void functionDecl(int a, int b, int c);";
25320 
25321   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25322                      "paramF, paramG, paramH, paramI);\n"
25323                      "void functionDecl(int argumentA, int argumentB, int "
25324                      "argumentC, int argumentD, int argumentE);";
25325 
25326   verifyFormat(Short, Style);
25327 
25328   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
25329                       "paramF, paramG, paramH,\n"
25330                       "             paramI);\n"
25331                       "void functionDecl(int argumentA, int argumentB, int "
25332                       "argumentC, int argumentD,\n"
25333                       "                  int argumentE);";
25334 
25335   verifyFormat(NoBreak, Medium, Style);
25336   verifyFormat(NoBreak,
25337                "functionCall(\n"
25338                "    paramA,\n"
25339                "    paramB,\n"
25340                "    paramC,\n"
25341                "    paramD,\n"
25342                "    paramE,\n"
25343                "    paramF,\n"
25344                "    paramG,\n"
25345                "    paramH,\n"
25346                "    paramI\n"
25347                ");\n"
25348                "void functionDecl(\n"
25349                "    int argumentA,\n"
25350                "    int argumentB,\n"
25351                "    int argumentC,\n"
25352                "    int argumentD,\n"
25353                "    int argumentE\n"
25354                ");",
25355                Style);
25356 
25357   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
25358                "                  nestedLongFunctionCall(argument1, "
25359                "argument2, argument3,\n"
25360                "                                         argument4, "
25361                "argument5));",
25362                Style);
25363 
25364   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25365 
25366   verifyFormat(Short, Style);
25367   verifyFormat(
25368       "functionCall(\n"
25369       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25370       "paramI\n"
25371       ");\n"
25372       "void functionDecl(\n"
25373       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25374       "argumentE\n"
25375       ");",
25376       Medium, Style);
25377 
25378   Style.AllowAllArgumentsOnNextLine = false;
25379   Style.AllowAllParametersOfDeclarationOnNextLine = false;
25380 
25381   verifyFormat(Short, Style);
25382   verifyFormat(
25383       "functionCall(\n"
25384       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
25385       "paramI\n"
25386       ");\n"
25387       "void functionDecl(\n"
25388       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
25389       "argumentE\n"
25390       ");",
25391       Medium, Style);
25392 
25393   Style.BinPackArguments = false;
25394   Style.BinPackParameters = false;
25395 
25396   verifyFormat(Short, Style);
25397 
25398   verifyFormat("functionCall(\n"
25399                "    paramA,\n"
25400                "    paramB,\n"
25401                "    paramC,\n"
25402                "    paramD,\n"
25403                "    paramE,\n"
25404                "    paramF,\n"
25405                "    paramG,\n"
25406                "    paramH,\n"
25407                "    paramI\n"
25408                ");\n"
25409                "void functionDecl(\n"
25410                "    int argumentA,\n"
25411                "    int argumentB,\n"
25412                "    int argumentC,\n"
25413                "    int argumentD,\n"
25414                "    int argumentE\n"
25415                ");",
25416                Medium, Style);
25417 
25418   verifyFormat("outerFunctionCall(\n"
25419                "    nestedFunctionCall(argument1),\n"
25420                "    nestedLongFunctionCall(\n"
25421                "        argument1,\n"
25422                "        argument2,\n"
25423                "        argument3,\n"
25424                "        argument4,\n"
25425                "        argument5\n"
25426                "    )\n"
25427                ");",
25428                Style);
25429 
25430   verifyFormat("int a = (int)b;", Style);
25431   verifyFormat("int a = (int)b;",
25432                "int a = (\n"
25433                "    int\n"
25434                ") b;",
25435                Style);
25436 
25437   verifyFormat("return (true);", Style);
25438   verifyFormat("return (true);",
25439                "return (\n"
25440                "    true\n"
25441                ");",
25442                Style);
25443 
25444   verifyFormat("void foo();", Style);
25445   verifyFormat("void foo();",
25446                "void foo(\n"
25447                ");",
25448                Style);
25449 
25450   verifyFormat("void foo() {}", Style);
25451   verifyFormat("void foo() {}",
25452                "void foo(\n"
25453                ") {\n"
25454                "}",
25455                Style);
25456 
25457   verifyFormat("auto string = std::string();", Style);
25458   verifyFormat("auto string = std::string();",
25459                "auto string = std::string(\n"
25460                ");",
25461                Style);
25462 
25463   verifyFormat("void (*functionPointer)() = nullptr;", Style);
25464   verifyFormat("void (*functionPointer)() = nullptr;",
25465                "void (\n"
25466                "    *functionPointer\n"
25467                ")\n"
25468                "(\n"
25469                ") = nullptr;",
25470                Style);
25471 }
25472 
25473 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
25474   auto Style = getLLVMStyle();
25475 
25476   verifyFormat("if (foo()) {\n"
25477                "  return;\n"
25478                "}",
25479                Style);
25480 
25481   verifyFormat("if (quitelongarg !=\n"
25482                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25483                "comment\n"
25484                "  return;\n"
25485                "}",
25486                Style);
25487 
25488   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25489 
25490   verifyFormat("if (foo()) {\n"
25491                "  return;\n"
25492                "}",
25493                Style);
25494 
25495   verifyFormat("if (quitelongarg !=\n"
25496                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25497                "comment\n"
25498                "  return;\n"
25499                "}",
25500                Style);
25501 }
25502 
25503 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
25504   auto Style = getLLVMStyle();
25505 
25506   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25507                "  doSomething();\n"
25508                "}",
25509                Style);
25510 
25511   verifyFormat("for (int myReallyLongCountVariable = 0; "
25512                "myReallyLongCountVariable < count;\n"
25513                "     myReallyLongCountVariable++) {\n"
25514                "  doSomething();\n"
25515                "}",
25516                Style);
25517 
25518   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25519 
25520   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25521                "  doSomething();\n"
25522                "}",
25523                Style);
25524 
25525   verifyFormat("for (int myReallyLongCountVariable = 0; "
25526                "myReallyLongCountVariable < count;\n"
25527                "     myReallyLongCountVariable++) {\n"
25528                "  doSomething();\n"
25529                "}",
25530                Style);
25531 }
25532 
25533 TEST_F(FormatTest, UnderstandsDigraphs) {
25534   verifyFormat("int arr<:5:> = {};");
25535   verifyFormat("int arr[5] = <%%>;");
25536   verifyFormat("int arr<:::qualified_variable:> = {};");
25537   verifyFormat("int arr[::qualified_variable] = <%%>;");
25538   verifyFormat("%:include <header>");
25539   verifyFormat("%:define A x##y");
25540   verifyFormat("#define A x%:%:y");
25541 }
25542 
25543 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
25544   auto Style = getLLVMStyle();
25545   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
25546   Style.AlignConsecutiveAssignments.Enabled = true;
25547   Style.AlignConsecutiveDeclarations.Enabled = true;
25548 
25549   // The AlignArray code is incorrect for non square Arrays and can cause
25550   // crashes, these tests assert that the array is not changed but will
25551   // also act as regression tests for when it is properly fixed
25552   verifyFormat("struct test demo[] = {\n"
25553                "    {1, 2},\n"
25554                "    {3, 4, 5},\n"
25555                "    {6, 7, 8}\n"
25556                "};",
25557                Style);
25558   verifyFormat("struct test demo[] = {\n"
25559                "    {1, 2, 3, 4, 5},\n"
25560                "    {3, 4, 5},\n"
25561                "    {6, 7, 8}\n"
25562                "};",
25563                Style);
25564   verifyFormat("struct test demo[] = {\n"
25565                "    {1, 2, 3, 4, 5},\n"
25566                "    {3, 4, 5},\n"
25567                "    {6, 7, 8, 9, 10, 11, 12}\n"
25568                "};",
25569                Style);
25570   verifyFormat("struct test demo[] = {\n"
25571                "    {1, 2, 3},\n"
25572                "    {3, 4, 5},\n"
25573                "    {6, 7, 8, 9, 10, 11, 12}\n"
25574                "};",
25575                Style);
25576 
25577   verifyFormat("S{\n"
25578                "    {},\n"
25579                "    {},\n"
25580                "    {a, b}\n"
25581                "};",
25582                Style);
25583   verifyFormat("S{\n"
25584                "    {},\n"
25585                "    {},\n"
25586                "    {a, b},\n"
25587                "};",
25588                Style);
25589   verifyFormat("void foo() {\n"
25590                "  auto thing = test{\n"
25591                "      {\n"
25592                "       {13}, {something}, // A\n"
25593                "      }\n"
25594                "  };\n"
25595                "}",
25596                "void foo() {\n"
25597                "  auto thing = test{\n"
25598                "      {\n"
25599                "       {13},\n"
25600                "       {something}, // A\n"
25601                "      }\n"
25602                "  };\n"
25603                "}",
25604                Style);
25605 }
25606 
25607 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
25608   auto Style = getLLVMStyle();
25609   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
25610   Style.AlignConsecutiveAssignments.Enabled = true;
25611   Style.AlignConsecutiveDeclarations.Enabled = true;
25612 
25613   // The AlignArray code is incorrect for non square Arrays and can cause
25614   // crashes, these tests assert that the array is not changed but will
25615   // also act as regression tests for when it is properly fixed
25616   verifyFormat("struct test demo[] = {\n"
25617                "    {1, 2},\n"
25618                "    {3, 4, 5},\n"
25619                "    {6, 7, 8}\n"
25620                "};",
25621                Style);
25622   verifyFormat("struct test demo[] = {\n"
25623                "    {1, 2, 3, 4, 5},\n"
25624                "    {3, 4, 5},\n"
25625                "    {6, 7, 8}\n"
25626                "};",
25627                Style);
25628   verifyFormat("struct test demo[] = {\n"
25629                "    {1, 2, 3, 4, 5},\n"
25630                "    {3, 4, 5},\n"
25631                "    {6, 7, 8, 9, 10, 11, 12}\n"
25632                "};",
25633                Style);
25634   verifyFormat("struct test demo[] = {\n"
25635                "    {1, 2, 3},\n"
25636                "    {3, 4, 5},\n"
25637                "    {6, 7, 8, 9, 10, 11, 12}\n"
25638                "};",
25639                Style);
25640 
25641   verifyFormat("S{\n"
25642                "    {},\n"
25643                "    {},\n"
25644                "    {a, b}\n"
25645                "};",
25646                Style);
25647   verifyFormat("S{\n"
25648                "    {},\n"
25649                "    {},\n"
25650                "    {a, b},\n"
25651                "};",
25652                Style);
25653   verifyFormat("void foo() {\n"
25654                "  auto thing = test{\n"
25655                "      {\n"
25656                "       {13}, {something}, // A\n"
25657                "      }\n"
25658                "  };\n"
25659                "}",
25660                "void foo() {\n"
25661                "  auto thing = test{\n"
25662                "      {\n"
25663                "       {13},\n"
25664                "       {something}, // A\n"
25665                "      }\n"
25666                "  };\n"
25667                "}",
25668                Style);
25669 }
25670 
25671 TEST_F(FormatTest, FormatsVariableTemplates) {
25672   verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
25673   verifyFormat("template <typename T> "
25674                "inline bool var = is_integral_v<T> && is_signed_v<T>;");
25675 }
25676 
25677 } // namespace
25678 } // namespace format
25679 } // namespace clang
25680