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 (a)\n"
587                "  g();");
588   verifyFormat("if (a) {\n"
589                "  g()\n"
590                "};");
591   verifyFormat("if (a)\n"
592                "  g();\n"
593                "else\n"
594                "  g();");
595   verifyFormat("if (a) {\n"
596                "  g();\n"
597                "} else\n"
598                "  g();");
599   verifyFormat("if (a)\n"
600                "  g();\n"
601                "else {\n"
602                "  g();\n"
603                "}");
604   verifyFormat("if (a) {\n"
605                "  g();\n"
606                "} else {\n"
607                "  g();\n"
608                "}");
609   verifyFormat("if (a)\n"
610                "  g();\n"
611                "else if (b)\n"
612                "  g();\n"
613                "else\n"
614                "  g();");
615   verifyFormat("if (a) {\n"
616                "  g();\n"
617                "} else if (b)\n"
618                "  g();\n"
619                "else\n"
620                "  g();");
621   verifyFormat("if (a)\n"
622                "  g();\n"
623                "else if (b) {\n"
624                "  g();\n"
625                "} else\n"
626                "  g();");
627   verifyFormat("if (a)\n"
628                "  g();\n"
629                "else if (b)\n"
630                "  g();\n"
631                "else {\n"
632                "  g();\n"
633                "}");
634   verifyFormat("if (a)\n"
635                "  g();\n"
636                "else if (b) {\n"
637                "  g();\n"
638                "} else {\n"
639                "  g();\n"
640                "}");
641   verifyFormat("if (a) {\n"
642                "  g();\n"
643                "} else if (b) {\n"
644                "  g();\n"
645                "} else {\n"
646                "  g();\n"
647                "}");
648 
649   FormatStyle AllowsMergedIf = getLLVMStyle();
650   AllowsMergedIf.IfMacros.push_back("MYIF");
651   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
652   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
653       FormatStyle::SIS_WithoutElse;
654   verifyFormat("if (a)\n"
655                "  // comment\n"
656                "  f();",
657                AllowsMergedIf);
658   verifyFormat("{\n"
659                "  if (a)\n"
660                "  label:\n"
661                "    f();\n"
662                "}",
663                AllowsMergedIf);
664   verifyFormat("#define A \\\n"
665                "  if (a)  \\\n"
666                "  label:  \\\n"
667                "    f()",
668                AllowsMergedIf);
669   verifyFormat("if (a)\n"
670                "  ;",
671                AllowsMergedIf);
672   verifyFormat("if (a)\n"
673                "  if (b) return;",
674                AllowsMergedIf);
675 
676   verifyFormat("if (a) // Can't merge this\n"
677                "  f();\n",
678                AllowsMergedIf);
679   verifyFormat("if (a) /* still don't merge */\n"
680                "  f();",
681                AllowsMergedIf);
682   verifyFormat("if (a) { // Never merge this\n"
683                "  f();\n"
684                "}",
685                AllowsMergedIf);
686   verifyFormat("if (a) { /* Never merge this */\n"
687                "  f();\n"
688                "}",
689                AllowsMergedIf);
690   verifyFormat("MYIF (a)\n"
691                "  // comment\n"
692                "  f();",
693                AllowsMergedIf);
694   verifyFormat("{\n"
695                "  MYIF (a)\n"
696                "  label:\n"
697                "    f();\n"
698                "}",
699                AllowsMergedIf);
700   verifyFormat("#define A  \\\n"
701                "  MYIF (a) \\\n"
702                "  label:   \\\n"
703                "    f()",
704                AllowsMergedIf);
705   verifyFormat("MYIF (a)\n"
706                "  ;",
707                AllowsMergedIf);
708   verifyFormat("MYIF (a)\n"
709                "  MYIF (b) return;",
710                AllowsMergedIf);
711 
712   verifyFormat("MYIF (a) // Can't merge this\n"
713                "  f();\n",
714                AllowsMergedIf);
715   verifyFormat("MYIF (a) /* still don't merge */\n"
716                "  f();",
717                AllowsMergedIf);
718   verifyFormat("MYIF (a) { // Never merge this\n"
719                "  f();\n"
720                "}",
721                AllowsMergedIf);
722   verifyFormat("MYIF (a) { /* Never merge this */\n"
723                "  f();\n"
724                "}",
725                AllowsMergedIf);
726 
727   AllowsMergedIf.ColumnLimit = 14;
728   // Where line-lengths matter, a 2-letter synonym that maintains line length.
729   // Not IF to avoid any confusion that IF is somehow special.
730   AllowsMergedIf.IfMacros.push_back("FI");
731   verifyFormat("if (a) return;", AllowsMergedIf);
732   verifyFormat("if (aaaaaaaaa)\n"
733                "  return;",
734                AllowsMergedIf);
735   verifyFormat("FI (a) return;", AllowsMergedIf);
736   verifyFormat("FI (aaaaaaaaa)\n"
737                "  return;",
738                AllowsMergedIf);
739 
740   AllowsMergedIf.ColumnLimit = 13;
741   verifyFormat("if (a)\n  return;", AllowsMergedIf);
742   verifyFormat("FI (a)\n  return;", AllowsMergedIf);
743 
744   FormatStyle AllowsMergedIfElse = getLLVMStyle();
745   AllowsMergedIfElse.IfMacros.push_back("MYIF");
746   AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
747       FormatStyle::SIS_AllIfsAndElse;
748   verifyFormat("if (a)\n"
749                "  // comment\n"
750                "  f();\n"
751                "else\n"
752                "  // comment\n"
753                "  f();",
754                AllowsMergedIfElse);
755   verifyFormat("{\n"
756                "  if (a)\n"
757                "  label:\n"
758                "    f();\n"
759                "  else\n"
760                "  label:\n"
761                "    f();\n"
762                "}",
763                AllowsMergedIfElse);
764   verifyFormat("if (a)\n"
765                "  ;\n"
766                "else\n"
767                "  ;",
768                AllowsMergedIfElse);
769   verifyFormat("if (a) {\n"
770                "} else {\n"
771                "}",
772                AllowsMergedIfElse);
773   verifyFormat("if (a) return;\n"
774                "else if (b) return;\n"
775                "else return;",
776                AllowsMergedIfElse);
777   verifyFormat("if (a) {\n"
778                "} else return;",
779                AllowsMergedIfElse);
780   verifyFormat("if (a) {\n"
781                "} else if (b) return;\n"
782                "else return;",
783                AllowsMergedIfElse);
784   verifyFormat("if (a) return;\n"
785                "else if (b) {\n"
786                "} else return;",
787                AllowsMergedIfElse);
788   verifyFormat("if (a)\n"
789                "  if (b) return;\n"
790                "  else return;",
791                AllowsMergedIfElse);
792   verifyFormat("if constexpr (a)\n"
793                "  if constexpr (b) return;\n"
794                "  else if constexpr (c) return;\n"
795                "  else return;",
796                AllowsMergedIfElse);
797   verifyFormat("MYIF (a)\n"
798                "  // comment\n"
799                "  f();\n"
800                "else\n"
801                "  // comment\n"
802                "  f();",
803                AllowsMergedIfElse);
804   verifyFormat("{\n"
805                "  MYIF (a)\n"
806                "  label:\n"
807                "    f();\n"
808                "  else\n"
809                "  label:\n"
810                "    f();\n"
811                "}",
812                AllowsMergedIfElse);
813   verifyFormat("MYIF (a)\n"
814                "  ;\n"
815                "else\n"
816                "  ;",
817                AllowsMergedIfElse);
818   verifyFormat("MYIF (a) {\n"
819                "} else {\n"
820                "}",
821                AllowsMergedIfElse);
822   verifyFormat("MYIF (a) return;\n"
823                "else MYIF (b) return;\n"
824                "else return;",
825                AllowsMergedIfElse);
826   verifyFormat("MYIF (a) {\n"
827                "} else return;",
828                AllowsMergedIfElse);
829   verifyFormat("MYIF (a) {\n"
830                "} else MYIF (b) return;\n"
831                "else return;",
832                AllowsMergedIfElse);
833   verifyFormat("MYIF (a) return;\n"
834                "else MYIF (b) {\n"
835                "} else return;",
836                AllowsMergedIfElse);
837   verifyFormat("MYIF (a)\n"
838                "  MYIF (b) return;\n"
839                "  else return;",
840                AllowsMergedIfElse);
841   verifyFormat("MYIF constexpr (a)\n"
842                "  MYIF constexpr (b) return;\n"
843                "  else MYIF constexpr (c) return;\n"
844                "  else return;",
845                AllowsMergedIfElse);
846 }
847 
848 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
849   FormatStyle AllowsMergedIf = getLLVMStyle();
850   AllowsMergedIf.IfMacros.push_back("MYIF");
851   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
852   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
853       FormatStyle::SIS_WithoutElse;
854   verifyFormat("if (a)\n"
855                "  f();\n"
856                "else {\n"
857                "  g();\n"
858                "}",
859                AllowsMergedIf);
860   verifyFormat("if (a)\n"
861                "  f();\n"
862                "else\n"
863                "  g();\n",
864                AllowsMergedIf);
865 
866   verifyFormat("if (a) g();", AllowsMergedIf);
867   verifyFormat("if (a) {\n"
868                "  g()\n"
869                "};",
870                AllowsMergedIf);
871   verifyFormat("if (a)\n"
872                "  g();\n"
873                "else\n"
874                "  g();",
875                AllowsMergedIf);
876   verifyFormat("if (a) {\n"
877                "  g();\n"
878                "} else\n"
879                "  g();",
880                AllowsMergedIf);
881   verifyFormat("if (a)\n"
882                "  g();\n"
883                "else {\n"
884                "  g();\n"
885                "}",
886                AllowsMergedIf);
887   verifyFormat("if (a) {\n"
888                "  g();\n"
889                "} else {\n"
890                "  g();\n"
891                "}",
892                AllowsMergedIf);
893   verifyFormat("if (a)\n"
894                "  g();\n"
895                "else if (b)\n"
896                "  g();\n"
897                "else\n"
898                "  g();",
899                AllowsMergedIf);
900   verifyFormat("if (a) {\n"
901                "  g();\n"
902                "} else if (b)\n"
903                "  g();\n"
904                "else\n"
905                "  g();",
906                AllowsMergedIf);
907   verifyFormat("if (a)\n"
908                "  g();\n"
909                "else if (b) {\n"
910                "  g();\n"
911                "} else\n"
912                "  g();",
913                AllowsMergedIf);
914   verifyFormat("if (a)\n"
915                "  g();\n"
916                "else if (b)\n"
917                "  g();\n"
918                "else {\n"
919                "  g();\n"
920                "}",
921                AllowsMergedIf);
922   verifyFormat("if (a)\n"
923                "  g();\n"
924                "else if (b) {\n"
925                "  g();\n"
926                "} else {\n"
927                "  g();\n"
928                "}",
929                AllowsMergedIf);
930   verifyFormat("if (a) {\n"
931                "  g();\n"
932                "} else if (b) {\n"
933                "  g();\n"
934                "} else {\n"
935                "  g();\n"
936                "}",
937                AllowsMergedIf);
938   verifyFormat("MYIF (a)\n"
939                "  f();\n"
940                "else {\n"
941                "  g();\n"
942                "}",
943                AllowsMergedIf);
944   verifyFormat("MYIF (a)\n"
945                "  f();\n"
946                "else\n"
947                "  g();\n",
948                AllowsMergedIf);
949 
950   verifyFormat("MYIF (a) g();", AllowsMergedIf);
951   verifyFormat("MYIF (a) {\n"
952                "  g()\n"
953                "};",
954                AllowsMergedIf);
955   verifyFormat("MYIF (a)\n"
956                "  g();\n"
957                "else\n"
958                "  g();",
959                AllowsMergedIf);
960   verifyFormat("MYIF (a) {\n"
961                "  g();\n"
962                "} else\n"
963                "  g();",
964                AllowsMergedIf);
965   verifyFormat("MYIF (a)\n"
966                "  g();\n"
967                "else {\n"
968                "  g();\n"
969                "}",
970                AllowsMergedIf);
971   verifyFormat("MYIF (a) {\n"
972                "  g();\n"
973                "} else {\n"
974                "  g();\n"
975                "}",
976                AllowsMergedIf);
977   verifyFormat("MYIF (a)\n"
978                "  g();\n"
979                "else MYIF (b)\n"
980                "  g();\n"
981                "else\n"
982                "  g();",
983                AllowsMergedIf);
984   verifyFormat("MYIF (a)\n"
985                "  g();\n"
986                "else if (b)\n"
987                "  g();\n"
988                "else\n"
989                "  g();",
990                AllowsMergedIf);
991   verifyFormat("MYIF (a) {\n"
992                "  g();\n"
993                "} else MYIF (b)\n"
994                "  g();\n"
995                "else\n"
996                "  g();",
997                AllowsMergedIf);
998   verifyFormat("MYIF (a) {\n"
999                "  g();\n"
1000                "} else if (b)\n"
1001                "  g();\n"
1002                "else\n"
1003                "  g();",
1004                AllowsMergedIf);
1005   verifyFormat("MYIF (a)\n"
1006                "  g();\n"
1007                "else MYIF (b) {\n"
1008                "  g();\n"
1009                "} else\n"
1010                "  g();",
1011                AllowsMergedIf);
1012   verifyFormat("MYIF (a)\n"
1013                "  g();\n"
1014                "else if (b) {\n"
1015                "  g();\n"
1016                "} else\n"
1017                "  g();",
1018                AllowsMergedIf);
1019   verifyFormat("MYIF (a)\n"
1020                "  g();\n"
1021                "else MYIF (b)\n"
1022                "  g();\n"
1023                "else {\n"
1024                "  g();\n"
1025                "}",
1026                AllowsMergedIf);
1027   verifyFormat("MYIF (a)\n"
1028                "  g();\n"
1029                "else if (b)\n"
1030                "  g();\n"
1031                "else {\n"
1032                "  g();\n"
1033                "}",
1034                AllowsMergedIf);
1035   verifyFormat("MYIF (a)\n"
1036                "  g();\n"
1037                "else MYIF (b) {\n"
1038                "  g();\n"
1039                "} else {\n"
1040                "  g();\n"
1041                "}",
1042                AllowsMergedIf);
1043   verifyFormat("MYIF (a)\n"
1044                "  g();\n"
1045                "else if (b) {\n"
1046                "  g();\n"
1047                "} else {\n"
1048                "  g();\n"
1049                "}",
1050                AllowsMergedIf);
1051   verifyFormat("MYIF (a) {\n"
1052                "  g();\n"
1053                "} else MYIF (b) {\n"
1054                "  g();\n"
1055                "} else {\n"
1056                "  g();\n"
1057                "}",
1058                AllowsMergedIf);
1059   verifyFormat("MYIF (a) {\n"
1060                "  g();\n"
1061                "} else if (b) {\n"
1062                "  g();\n"
1063                "} else {\n"
1064                "  g();\n"
1065                "}",
1066                AllowsMergedIf);
1067 
1068   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1069       FormatStyle::SIS_OnlyFirstIf;
1070 
1071   verifyFormat("if (a) f();\n"
1072                "else {\n"
1073                "  g();\n"
1074                "}",
1075                AllowsMergedIf);
1076   verifyFormat("if (a) f();\n"
1077                "else {\n"
1078                "  if (a) f();\n"
1079                "  else {\n"
1080                "    g();\n"
1081                "  }\n"
1082                "  g();\n"
1083                "}",
1084                AllowsMergedIf);
1085 
1086   verifyFormat("if (a) g();", AllowsMergedIf);
1087   verifyFormat("if (a) {\n"
1088                "  g()\n"
1089                "};",
1090                AllowsMergedIf);
1091   verifyFormat("if (a) g();\n"
1092                "else\n"
1093                "  g();",
1094                AllowsMergedIf);
1095   verifyFormat("if (a) {\n"
1096                "  g();\n"
1097                "} else\n"
1098                "  g();",
1099                AllowsMergedIf);
1100   verifyFormat("if (a) g();\n"
1101                "else {\n"
1102                "  g();\n"
1103                "}",
1104                AllowsMergedIf);
1105   verifyFormat("if (a) {\n"
1106                "  g();\n"
1107                "} else {\n"
1108                "  g();\n"
1109                "}",
1110                AllowsMergedIf);
1111   verifyFormat("if (a) g();\n"
1112                "else if (b)\n"
1113                "  g();\n"
1114                "else\n"
1115                "  g();",
1116                AllowsMergedIf);
1117   verifyFormat("if (a) {\n"
1118                "  g();\n"
1119                "} else if (b)\n"
1120                "  g();\n"
1121                "else\n"
1122                "  g();",
1123                AllowsMergedIf);
1124   verifyFormat("if (a) g();\n"
1125                "else if (b) {\n"
1126                "  g();\n"
1127                "} else\n"
1128                "  g();",
1129                AllowsMergedIf);
1130   verifyFormat("if (a) g();\n"
1131                "else if (b)\n"
1132                "  g();\n"
1133                "else {\n"
1134                "  g();\n"
1135                "}",
1136                AllowsMergedIf);
1137   verifyFormat("if (a) g();\n"
1138                "else if (b) {\n"
1139                "  g();\n"
1140                "} else {\n"
1141                "  g();\n"
1142                "}",
1143                AllowsMergedIf);
1144   verifyFormat("if (a) {\n"
1145                "  g();\n"
1146                "} else if (b) {\n"
1147                "  g();\n"
1148                "} else {\n"
1149                "  g();\n"
1150                "}",
1151                AllowsMergedIf);
1152   verifyFormat("MYIF (a) f();\n"
1153                "else {\n"
1154                "  g();\n"
1155                "}",
1156                AllowsMergedIf);
1157   verifyFormat("MYIF (a) f();\n"
1158                "else {\n"
1159                "  if (a) f();\n"
1160                "  else {\n"
1161                "    g();\n"
1162                "  }\n"
1163                "  g();\n"
1164                "}",
1165                AllowsMergedIf);
1166 
1167   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1168   verifyFormat("MYIF (a) {\n"
1169                "  g()\n"
1170                "};",
1171                AllowsMergedIf);
1172   verifyFormat("MYIF (a) g();\n"
1173                "else\n"
1174                "  g();",
1175                AllowsMergedIf);
1176   verifyFormat("MYIF (a) {\n"
1177                "  g();\n"
1178                "} else\n"
1179                "  g();",
1180                AllowsMergedIf);
1181   verifyFormat("MYIF (a) g();\n"
1182                "else {\n"
1183                "  g();\n"
1184                "}",
1185                AllowsMergedIf);
1186   verifyFormat("MYIF (a) {\n"
1187                "  g();\n"
1188                "} else {\n"
1189                "  g();\n"
1190                "}",
1191                AllowsMergedIf);
1192   verifyFormat("MYIF (a) g();\n"
1193                "else MYIF (b)\n"
1194                "  g();\n"
1195                "else\n"
1196                "  g();",
1197                AllowsMergedIf);
1198   verifyFormat("MYIF (a) g();\n"
1199                "else if (b)\n"
1200                "  g();\n"
1201                "else\n"
1202                "  g();",
1203                AllowsMergedIf);
1204   verifyFormat("MYIF (a) {\n"
1205                "  g();\n"
1206                "} else MYIF (b)\n"
1207                "  g();\n"
1208                "else\n"
1209                "  g();",
1210                AllowsMergedIf);
1211   verifyFormat("MYIF (a) {\n"
1212                "  g();\n"
1213                "} else if (b)\n"
1214                "  g();\n"
1215                "else\n"
1216                "  g();",
1217                AllowsMergedIf);
1218   verifyFormat("MYIF (a) g();\n"
1219                "else MYIF (b) {\n"
1220                "  g();\n"
1221                "} else\n"
1222                "  g();",
1223                AllowsMergedIf);
1224   verifyFormat("MYIF (a) g();\n"
1225                "else if (b) {\n"
1226                "  g();\n"
1227                "} else\n"
1228                "  g();",
1229                AllowsMergedIf);
1230   verifyFormat("MYIF (a) g();\n"
1231                "else MYIF (b)\n"
1232                "  g();\n"
1233                "else {\n"
1234                "  g();\n"
1235                "}",
1236                AllowsMergedIf);
1237   verifyFormat("MYIF (a) g();\n"
1238                "else if (b)\n"
1239                "  g();\n"
1240                "else {\n"
1241                "  g();\n"
1242                "}",
1243                AllowsMergedIf);
1244   verifyFormat("MYIF (a) g();\n"
1245                "else MYIF (b) {\n"
1246                "  g();\n"
1247                "} else {\n"
1248                "  g();\n"
1249                "}",
1250                AllowsMergedIf);
1251   verifyFormat("MYIF (a) g();\n"
1252                "else if (b) {\n"
1253                "  g();\n"
1254                "} else {\n"
1255                "  g();\n"
1256                "}",
1257                AllowsMergedIf);
1258   verifyFormat("MYIF (a) {\n"
1259                "  g();\n"
1260                "} else MYIF (b) {\n"
1261                "  g();\n"
1262                "} else {\n"
1263                "  g();\n"
1264                "}",
1265                AllowsMergedIf);
1266   verifyFormat("MYIF (a) {\n"
1267                "  g();\n"
1268                "} else if (b) {\n"
1269                "  g();\n"
1270                "} else {\n"
1271                "  g();\n"
1272                "}",
1273                AllowsMergedIf);
1274 
1275   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1276       FormatStyle::SIS_AllIfsAndElse;
1277 
1278   verifyFormat("if (a) f();\n"
1279                "else {\n"
1280                "  g();\n"
1281                "}",
1282                AllowsMergedIf);
1283   verifyFormat("if (a) f();\n"
1284                "else {\n"
1285                "  if (a) f();\n"
1286                "  else {\n"
1287                "    g();\n"
1288                "  }\n"
1289                "  g();\n"
1290                "}",
1291                AllowsMergedIf);
1292 
1293   verifyFormat("if (a) g();", AllowsMergedIf);
1294   verifyFormat("if (a) {\n"
1295                "  g()\n"
1296                "};",
1297                AllowsMergedIf);
1298   verifyFormat("if (a) g();\n"
1299                "else g();",
1300                AllowsMergedIf);
1301   verifyFormat("if (a) {\n"
1302                "  g();\n"
1303                "} else g();",
1304                AllowsMergedIf);
1305   verifyFormat("if (a) g();\n"
1306                "else {\n"
1307                "  g();\n"
1308                "}",
1309                AllowsMergedIf);
1310   verifyFormat("if (a) {\n"
1311                "  g();\n"
1312                "} else {\n"
1313                "  g();\n"
1314                "}",
1315                AllowsMergedIf);
1316   verifyFormat("if (a) g();\n"
1317                "else if (b) g();\n"
1318                "else g();",
1319                AllowsMergedIf);
1320   verifyFormat("if (a) {\n"
1321                "  g();\n"
1322                "} else if (b) g();\n"
1323                "else g();",
1324                AllowsMergedIf);
1325   verifyFormat("if (a) g();\n"
1326                "else if (b) {\n"
1327                "  g();\n"
1328                "} else g();",
1329                AllowsMergedIf);
1330   verifyFormat("if (a) g();\n"
1331                "else if (b) g();\n"
1332                "else {\n"
1333                "  g();\n"
1334                "}",
1335                AllowsMergedIf);
1336   verifyFormat("if (a) g();\n"
1337                "else if (b) {\n"
1338                "  g();\n"
1339                "} else {\n"
1340                "  g();\n"
1341                "}",
1342                AllowsMergedIf);
1343   verifyFormat("if (a) {\n"
1344                "  g();\n"
1345                "} else if (b) {\n"
1346                "  g();\n"
1347                "} else {\n"
1348                "  g();\n"
1349                "}",
1350                AllowsMergedIf);
1351   verifyFormat("MYIF (a) f();\n"
1352                "else {\n"
1353                "  g();\n"
1354                "}",
1355                AllowsMergedIf);
1356   verifyFormat("MYIF (a) f();\n"
1357                "else {\n"
1358                "  if (a) f();\n"
1359                "  else {\n"
1360                "    g();\n"
1361                "  }\n"
1362                "  g();\n"
1363                "}",
1364                AllowsMergedIf);
1365 
1366   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1367   verifyFormat("MYIF (a) {\n"
1368                "  g()\n"
1369                "};",
1370                AllowsMergedIf);
1371   verifyFormat("MYIF (a) g();\n"
1372                "else g();",
1373                AllowsMergedIf);
1374   verifyFormat("MYIF (a) {\n"
1375                "  g();\n"
1376                "} else g();",
1377                AllowsMergedIf);
1378   verifyFormat("MYIF (a) g();\n"
1379                "else {\n"
1380                "  g();\n"
1381                "}",
1382                AllowsMergedIf);
1383   verifyFormat("MYIF (a) {\n"
1384                "  g();\n"
1385                "} else {\n"
1386                "  g();\n"
1387                "}",
1388                AllowsMergedIf);
1389   verifyFormat("MYIF (a) g();\n"
1390                "else MYIF (b) g();\n"
1391                "else g();",
1392                AllowsMergedIf);
1393   verifyFormat("MYIF (a) g();\n"
1394                "else if (b) g();\n"
1395                "else g();",
1396                AllowsMergedIf);
1397   verifyFormat("MYIF (a) {\n"
1398                "  g();\n"
1399                "} else MYIF (b) g();\n"
1400                "else g();",
1401                AllowsMergedIf);
1402   verifyFormat("MYIF (a) {\n"
1403                "  g();\n"
1404                "} else if (b) g();\n"
1405                "else g();",
1406                AllowsMergedIf);
1407   verifyFormat("MYIF (a) g();\n"
1408                "else MYIF (b) {\n"
1409                "  g();\n"
1410                "} else g();",
1411                AllowsMergedIf);
1412   verifyFormat("MYIF (a) g();\n"
1413                "else if (b) {\n"
1414                "  g();\n"
1415                "} else g();",
1416                AllowsMergedIf);
1417   verifyFormat("MYIF (a) g();\n"
1418                "else MYIF (b) g();\n"
1419                "else {\n"
1420                "  g();\n"
1421                "}",
1422                AllowsMergedIf);
1423   verifyFormat("MYIF (a) g();\n"
1424                "else if (b) g();\n"
1425                "else {\n"
1426                "  g();\n"
1427                "}",
1428                AllowsMergedIf);
1429   verifyFormat("MYIF (a) g();\n"
1430                "else MYIF (b) {\n"
1431                "  g();\n"
1432                "} else {\n"
1433                "  g();\n"
1434                "}",
1435                AllowsMergedIf);
1436   verifyFormat("MYIF (a) g();\n"
1437                "else if (b) {\n"
1438                "  g();\n"
1439                "} else {\n"
1440                "  g();\n"
1441                "}",
1442                AllowsMergedIf);
1443   verifyFormat("MYIF (a) {\n"
1444                "  g();\n"
1445                "} else MYIF (b) {\n"
1446                "  g();\n"
1447                "} else {\n"
1448                "  g();\n"
1449                "}",
1450                AllowsMergedIf);
1451   verifyFormat("MYIF (a) {\n"
1452                "  g();\n"
1453                "} else if (b) {\n"
1454                "  g();\n"
1455                "} else {\n"
1456                "  g();\n"
1457                "}",
1458                AllowsMergedIf);
1459 }
1460 
1461 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
1462   FormatStyle AllowsMergedLoops = getLLVMStyle();
1463   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
1464   verifyFormat("while (true) continue;", AllowsMergedLoops);
1465   verifyFormat("for (;;) continue;", AllowsMergedLoops);
1466   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
1467   verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
1468   verifyFormat("while (true)\n"
1469                "  ;",
1470                AllowsMergedLoops);
1471   verifyFormat("for (;;)\n"
1472                "  ;",
1473                AllowsMergedLoops);
1474   verifyFormat("for (;;)\n"
1475                "  for (;;) continue;",
1476                AllowsMergedLoops);
1477   verifyFormat("for (;;)\n"
1478                "  while (true) continue;",
1479                AllowsMergedLoops);
1480   verifyFormat("while (true)\n"
1481                "  for (;;) continue;",
1482                AllowsMergedLoops);
1483   verifyFormat("BOOST_FOREACH (int &v, vec)\n"
1484                "  for (;;) continue;",
1485                AllowsMergedLoops);
1486   verifyFormat("for (;;)\n"
1487                "  BOOST_FOREACH (int &v, vec) continue;",
1488                AllowsMergedLoops);
1489   verifyFormat("for (;;) // Can't merge this\n"
1490                "  continue;",
1491                AllowsMergedLoops);
1492   verifyFormat("for (;;) /* still don't merge */\n"
1493                "  continue;",
1494                AllowsMergedLoops);
1495   verifyFormat("do a++;\n"
1496                "while (true);",
1497                AllowsMergedLoops);
1498   verifyFormat("do /* Don't merge */\n"
1499                "  a++;\n"
1500                "while (true);",
1501                AllowsMergedLoops);
1502   verifyFormat("do // Don't merge\n"
1503                "  a++;\n"
1504                "while (true);",
1505                AllowsMergedLoops);
1506   verifyFormat("do\n"
1507                "  // Don't merge\n"
1508                "  a++;\n"
1509                "while (true);",
1510                AllowsMergedLoops);
1511   // Without braces labels are interpreted differently.
1512   verifyFormat("{\n"
1513                "  do\n"
1514                "  label:\n"
1515                "    a++;\n"
1516                "  while (true);\n"
1517                "}",
1518                AllowsMergedLoops);
1519 }
1520 
1521 TEST_F(FormatTest, FormatShortBracedStatements) {
1522   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
1523   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false);
1524   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine,
1525             FormatStyle::SIS_Never);
1526   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false);
1527   EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false);
1528   verifyFormat("for (;;) {\n"
1529                "  f();\n"
1530                "}");
1531   verifyFormat("/*comment*/ for (;;) {\n"
1532                "  f();\n"
1533                "}");
1534   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1535                "  f();\n"
1536                "}");
1537   verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n"
1538                "  f();\n"
1539                "}");
1540   verifyFormat("while (true) {\n"
1541                "  f();\n"
1542                "}");
1543   verifyFormat("/*comment*/ while (true) {\n"
1544                "  f();\n"
1545                "}");
1546   verifyFormat("if (true) {\n"
1547                "  f();\n"
1548                "}");
1549   verifyFormat("/*comment*/ if (true) {\n"
1550                "  f();\n"
1551                "}");
1552 
1553   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1554   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1555   // Not IF to avoid any confusion that IF is somehow special.
1556   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1557   AllowSimpleBracedStatements.ColumnLimit = 40;
1558   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1559       FormatStyle::SBS_Always;
1560 
1561   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1562       FormatStyle::SIS_WithoutElse;
1563   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1564 
1565   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1566   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1567   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1568 
1569   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1570   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1571   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1572   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1573   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1574   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1575   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1576   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1577   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1578   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1579   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1580   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1581   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1582   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1583   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1584   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1585   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1586                AllowSimpleBracedStatements);
1587   verifyFormat("if (true) {\n"
1588                "  ffffffffffffffffffffffff();\n"
1589                "}",
1590                AllowSimpleBracedStatements);
1591   verifyFormat("if (true) {\n"
1592                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1593                "}",
1594                AllowSimpleBracedStatements);
1595   verifyFormat("if (true) { //\n"
1596                "  f();\n"
1597                "}",
1598                AllowSimpleBracedStatements);
1599   verifyFormat("if (true) {\n"
1600                "  f();\n"
1601                "  f();\n"
1602                "}",
1603                AllowSimpleBracedStatements);
1604   verifyFormat("if (true) {\n"
1605                "  f();\n"
1606                "} else {\n"
1607                "  f();\n"
1608                "}",
1609                AllowSimpleBracedStatements);
1610   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1611                AllowSimpleBracedStatements);
1612   verifyFormat("MYIF (true) {\n"
1613                "  ffffffffffffffffffffffff();\n"
1614                "}",
1615                AllowSimpleBracedStatements);
1616   verifyFormat("MYIF (true) {\n"
1617                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1618                "}",
1619                AllowSimpleBracedStatements);
1620   verifyFormat("MYIF (true) { //\n"
1621                "  f();\n"
1622                "}",
1623                AllowSimpleBracedStatements);
1624   verifyFormat("MYIF (true) {\n"
1625                "  f();\n"
1626                "  f();\n"
1627                "}",
1628                AllowSimpleBracedStatements);
1629   verifyFormat("MYIF (true) {\n"
1630                "  f();\n"
1631                "} else {\n"
1632                "  f();\n"
1633                "}",
1634                AllowSimpleBracedStatements);
1635 
1636   verifyFormat("struct A2 {\n"
1637                "  int X;\n"
1638                "};",
1639                AllowSimpleBracedStatements);
1640   verifyFormat("typedef struct A2 {\n"
1641                "  int X;\n"
1642                "} A2_t;",
1643                AllowSimpleBracedStatements);
1644   verifyFormat("template <int> struct A2 {\n"
1645                "  struct B {};\n"
1646                "};",
1647                AllowSimpleBracedStatements);
1648 
1649   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1650       FormatStyle::SIS_Never;
1651   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1652   verifyFormat("if (true) {\n"
1653                "  f();\n"
1654                "}",
1655                AllowSimpleBracedStatements);
1656   verifyFormat("if (true) {\n"
1657                "  f();\n"
1658                "} else {\n"
1659                "  f();\n"
1660                "}",
1661                AllowSimpleBracedStatements);
1662   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1663   verifyFormat("MYIF (true) {\n"
1664                "  f();\n"
1665                "}",
1666                AllowSimpleBracedStatements);
1667   verifyFormat("MYIF (true) {\n"
1668                "  f();\n"
1669                "} else {\n"
1670                "  f();\n"
1671                "}",
1672                AllowSimpleBracedStatements);
1673 
1674   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1675   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1676   verifyFormat("while (true) {\n"
1677                "  f();\n"
1678                "}",
1679                AllowSimpleBracedStatements);
1680   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1681   verifyFormat("for (;;) {\n"
1682                "  f();\n"
1683                "}",
1684                AllowSimpleBracedStatements);
1685   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1686   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1687                "  f();\n"
1688                "}",
1689                AllowSimpleBracedStatements);
1690 
1691   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1692       FormatStyle::SIS_WithoutElse;
1693   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1694   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1695       FormatStyle::BWACS_Always;
1696 
1697   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1698   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1699   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1700   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1701   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1702   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1703   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1704   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1705   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1706   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1707   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1708   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1709   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1710   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1711   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1712   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1713   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1714                AllowSimpleBracedStatements);
1715   verifyFormat("if (true)\n"
1716                "{\n"
1717                "  ffffffffffffffffffffffff();\n"
1718                "}",
1719                AllowSimpleBracedStatements);
1720   verifyFormat("if (true)\n"
1721                "{\n"
1722                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1723                "}",
1724                AllowSimpleBracedStatements);
1725   verifyFormat("if (true)\n"
1726                "{ //\n"
1727                "  f();\n"
1728                "}",
1729                AllowSimpleBracedStatements);
1730   verifyFormat("if (true)\n"
1731                "{\n"
1732                "  f();\n"
1733                "  f();\n"
1734                "}",
1735                AllowSimpleBracedStatements);
1736   verifyFormat("if (true)\n"
1737                "{\n"
1738                "  f();\n"
1739                "} else\n"
1740                "{\n"
1741                "  f();\n"
1742                "}",
1743                AllowSimpleBracedStatements);
1744   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1745                AllowSimpleBracedStatements);
1746   verifyFormat("MYIF (true)\n"
1747                "{\n"
1748                "  ffffffffffffffffffffffff();\n"
1749                "}",
1750                AllowSimpleBracedStatements);
1751   verifyFormat("MYIF (true)\n"
1752                "{\n"
1753                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1754                "}",
1755                AllowSimpleBracedStatements);
1756   verifyFormat("MYIF (true)\n"
1757                "{ //\n"
1758                "  f();\n"
1759                "}",
1760                AllowSimpleBracedStatements);
1761   verifyFormat("MYIF (true)\n"
1762                "{\n"
1763                "  f();\n"
1764                "  f();\n"
1765                "}",
1766                AllowSimpleBracedStatements);
1767   verifyFormat("MYIF (true)\n"
1768                "{\n"
1769                "  f();\n"
1770                "} else\n"
1771                "{\n"
1772                "  f();\n"
1773                "}",
1774                AllowSimpleBracedStatements);
1775 
1776   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1777       FormatStyle::SIS_Never;
1778   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1779   verifyFormat("if (true)\n"
1780                "{\n"
1781                "  f();\n"
1782                "}",
1783                AllowSimpleBracedStatements);
1784   verifyFormat("if (true)\n"
1785                "{\n"
1786                "  f();\n"
1787                "} else\n"
1788                "{\n"
1789                "  f();\n"
1790                "}",
1791                AllowSimpleBracedStatements);
1792   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1793   verifyFormat("MYIF (true)\n"
1794                "{\n"
1795                "  f();\n"
1796                "}",
1797                AllowSimpleBracedStatements);
1798   verifyFormat("MYIF (true)\n"
1799                "{\n"
1800                "  f();\n"
1801                "} else\n"
1802                "{\n"
1803                "  f();\n"
1804                "}",
1805                AllowSimpleBracedStatements);
1806 
1807   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1808   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1809   verifyFormat("while (true)\n"
1810                "{\n"
1811                "  f();\n"
1812                "}",
1813                AllowSimpleBracedStatements);
1814   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1815   verifyFormat("for (;;)\n"
1816                "{\n"
1817                "  f();\n"
1818                "}",
1819                AllowSimpleBracedStatements);
1820   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1821   verifyFormat("BOOST_FOREACH (int v, vec)\n"
1822                "{\n"
1823                "  f();\n"
1824                "}",
1825                AllowSimpleBracedStatements);
1826 }
1827 
1828 TEST_F(FormatTest, UnderstandsMacros) {
1829   verifyFormat("#define A (parentheses)");
1830   verifyFormat("/* comment */ #define A (parentheses)");
1831   verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
1832   // Even the partial code should never be merged.
1833   EXPECT_EQ("/* comment */ #define A (parentheses)\n"
1834             "#",
1835             format("/* comment */ #define A (parentheses)\n"
1836                    "#"));
1837   verifyFormat("/* comment */ #define A (parentheses)\n"
1838                "#\n");
1839   verifyFormat("/* comment */ #define A (parentheses)\n"
1840                "#define B (parentheses)");
1841   verifyFormat("#define true ((int)1)");
1842   verifyFormat("#define and(x)");
1843   verifyFormat("#define if(x) x");
1844   verifyFormat("#define return(x) (x)");
1845   verifyFormat("#define while(x) for (; x;)");
1846   verifyFormat("#define xor(x) (^(x))");
1847   verifyFormat("#define __except(x)");
1848   verifyFormat("#define __try(x)");
1849 
1850   FormatStyle Style = getLLVMStyle();
1851   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1852   Style.BraceWrapping.AfterFunction = true;
1853   // Test that a macro definition never gets merged with the following
1854   // definition.
1855   // FIXME: The AAA macro definition probably should not be split into 3 lines.
1856   verifyFormat("#define AAA                                                    "
1857                "                \\\n"
1858                "  N                                                            "
1859                "                \\\n"
1860                "  {\n"
1861                "#define BBB }\n",
1862                Style);
1863   // verifyFormat("#define AAA N { //\n", Style);
1864 
1865   verifyFormat("MACRO(return)");
1866   verifyFormat("MACRO(co_await)");
1867   verifyFormat("MACRO(co_return)");
1868   verifyFormat("MACRO(co_yield)");
1869   verifyFormat("MACRO(return, something)");
1870   verifyFormat("MACRO(co_return, something)");
1871   verifyFormat("MACRO(something##something)");
1872   verifyFormat("MACRO(return##something)");
1873   verifyFormat("MACRO(co_return##something)");
1874 }
1875 
1876 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1877   FormatStyle Style = getLLVMStyleWithColumns(60);
1878   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1879   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1880   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1881   EXPECT_EQ("#define A                                                  \\\n"
1882             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1883             "  {                                                        \\\n"
1884             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1885             "  }\n"
1886             "X;",
1887             format("#define A \\\n"
1888                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1889                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1890                    "   }\n"
1891                    "X;",
1892                    Style));
1893 }
1894 
1895 TEST_F(FormatTest, ParseIfElse) {
1896   verifyFormat("if (true)\n"
1897                "  if (true)\n"
1898                "    if (true)\n"
1899                "      f();\n"
1900                "    else\n"
1901                "      g();\n"
1902                "  else\n"
1903                "    h();\n"
1904                "else\n"
1905                "  i();");
1906   verifyFormat("if (true)\n"
1907                "  if (true)\n"
1908                "    if (true) {\n"
1909                "      if (true)\n"
1910                "        f();\n"
1911                "    } else {\n"
1912                "      g();\n"
1913                "    }\n"
1914                "  else\n"
1915                "    h();\n"
1916                "else {\n"
1917                "  i();\n"
1918                "}");
1919   verifyFormat("if (true)\n"
1920                "  if constexpr (true)\n"
1921                "    if (true) {\n"
1922                "      if constexpr (true)\n"
1923                "        f();\n"
1924                "    } else {\n"
1925                "      g();\n"
1926                "    }\n"
1927                "  else\n"
1928                "    h();\n"
1929                "else {\n"
1930                "  i();\n"
1931                "}");
1932   verifyFormat("if (true)\n"
1933                "  if CONSTEXPR (true)\n"
1934                "    if (true) {\n"
1935                "      if CONSTEXPR (true)\n"
1936                "        f();\n"
1937                "    } else {\n"
1938                "      g();\n"
1939                "    }\n"
1940                "  else\n"
1941                "    h();\n"
1942                "else {\n"
1943                "  i();\n"
1944                "}");
1945   verifyFormat("void f() {\n"
1946                "  if (a) {\n"
1947                "  } else {\n"
1948                "  }\n"
1949                "}");
1950 }
1951 
1952 TEST_F(FormatTest, ElseIf) {
1953   verifyFormat("if (a) {\n} else if (b) {\n}");
1954   verifyFormat("if (a)\n"
1955                "  f();\n"
1956                "else if (b)\n"
1957                "  g();\n"
1958                "else\n"
1959                "  h();");
1960   verifyFormat("if (a)\n"
1961                "  f();\n"
1962                "else // comment\n"
1963                "  if (b) {\n"
1964                "    g();\n"
1965                "    h();\n"
1966                "  }");
1967   verifyFormat("if constexpr (a)\n"
1968                "  f();\n"
1969                "else if constexpr (b)\n"
1970                "  g();\n"
1971                "else\n"
1972                "  h();");
1973   verifyFormat("if CONSTEXPR (a)\n"
1974                "  f();\n"
1975                "else if CONSTEXPR (b)\n"
1976                "  g();\n"
1977                "else\n"
1978                "  h();");
1979   verifyFormat("if (a) {\n"
1980                "  f();\n"
1981                "}\n"
1982                "// or else ..\n"
1983                "else {\n"
1984                "  g()\n"
1985                "}");
1986 
1987   verifyFormat("if (a) {\n"
1988                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1989                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1990                "}");
1991   verifyFormat("if (a) {\n"
1992                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1993                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1994                "}");
1995   verifyFormat("if (a) {\n"
1996                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1997                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1998                "}");
1999   verifyFormat("if (a) {\n"
2000                "} else if (\n"
2001                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2002                "}",
2003                getLLVMStyleWithColumns(62));
2004   verifyFormat("if (a) {\n"
2005                "} else if constexpr (\n"
2006                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2007                "}",
2008                getLLVMStyleWithColumns(62));
2009   verifyFormat("if (a) {\n"
2010                "} else if CONSTEXPR (\n"
2011                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2012                "}",
2013                getLLVMStyleWithColumns(62));
2014 }
2015 
2016 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
2017   FormatStyle Style = getLLVMStyle();
2018   EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
2019   EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer);
2020   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
2021   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
2022   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
2023   verifyFormat("int *f1(int &a) const &;", Style);
2024   verifyFormat("int *f1(int &a) const & = 0;", Style);
2025   verifyFormat("int *a = f1();", Style);
2026   verifyFormat("int &b = f2();", Style);
2027   verifyFormat("int &&c = f3();", Style);
2028   verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2029   verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2030   verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2031   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2032   verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2033   verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2034   verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2035   verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
2036   verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
2037   verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
2038   verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
2039   verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
2040   verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
2041   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
2042   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
2043   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
2044   verifyFormat(
2045       "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n"
2046       "                     res2 = [](int &a) { return 0000000000000; };",
2047       Style);
2048 
2049   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2050   verifyFormat("Const unsigned int *c;\n"
2051                "const unsigned int *d;\n"
2052                "Const unsigned int &e;\n"
2053                "const unsigned int &f;\n"
2054                "const unsigned    &&g;\n"
2055                "Const unsigned      h;",
2056                Style);
2057 
2058   Style.PointerAlignment = FormatStyle::PAS_Left;
2059   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2060   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
2061   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
2062   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
2063   verifyFormat("int* f1(int& a) const& = 0;", Style);
2064   verifyFormat("int* a = f1();", Style);
2065   verifyFormat("int& b = f2();", Style);
2066   verifyFormat("int&& c = f3();", Style);
2067   verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2068   verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2069   verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2070   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2071   verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2072   verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2073   verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2074   verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2075   verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
2076   verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
2077   verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
2078   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2079   verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
2080   verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
2081   verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
2082   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
2083   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
2084   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
2085   verifyFormat(
2086       "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n"
2087       "                    res2 = [](int& a) { return 0000000000000; };",
2088       Style);
2089 
2090   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2091   verifyFormat("Const unsigned int* c;\n"
2092                "const unsigned int* d;\n"
2093                "Const unsigned int& e;\n"
2094                "const unsigned int& f;\n"
2095                "const unsigned&&    g;\n"
2096                "Const unsigned      h;",
2097                Style);
2098 
2099   Style.PointerAlignment = FormatStyle::PAS_Right;
2100   Style.ReferenceAlignment = FormatStyle::RAS_Left;
2101   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
2102   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
2103   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
2104   verifyFormat("int *a = f1();", Style);
2105   verifyFormat("int& b = f2();", Style);
2106   verifyFormat("int&& c = f3();", 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 Foo *c : {1, 2, 3})", Style);
2109   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
2110 
2111   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2112   verifyFormat("Const unsigned int *c;\n"
2113                "const unsigned int *d;\n"
2114                "Const unsigned int& e;\n"
2115                "const unsigned int& f;\n"
2116                "const unsigned      g;\n"
2117                "Const unsigned      h;",
2118                Style);
2119 
2120   Style.PointerAlignment = FormatStyle::PAS_Left;
2121   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
2122   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
2123   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
2124   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
2125   verifyFormat("int* a = f1();", Style);
2126   verifyFormat("int & b = f2();", Style);
2127   verifyFormat("int && c = f3();", Style);
2128   verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
2129   verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
2130   verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
2131   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2132   verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
2133   verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
2134   verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
2135   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2136   verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
2137   verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
2138   verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
2139   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
2140   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
2141   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
2142   verifyFormat(
2143       "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n"
2144       "                     res2 = [](int & a) { return 0000000000000; };",
2145       Style);
2146 
2147   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2148   verifyFormat("Const unsigned int*  c;\n"
2149                "const unsigned int*  d;\n"
2150                "Const unsigned int & e;\n"
2151                "const unsigned int & f;\n"
2152                "const unsigned &&    g;\n"
2153                "Const unsigned       h;",
2154                Style);
2155 
2156   Style.PointerAlignment = FormatStyle::PAS_Middle;
2157   Style.ReferenceAlignment = FormatStyle::RAS_Right;
2158   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
2159   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
2160   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
2161   verifyFormat("int * a = f1();", Style);
2162   verifyFormat("int &b = f2();", Style);
2163   verifyFormat("int &&c = f3();", Style);
2164   verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2165   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2166   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
2167 
2168   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2169   // specifically handled
2170   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2171 }
2172 
2173 TEST_F(FormatTest, FormatsForLoop) {
2174   verifyFormat(
2175       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2176       "     ++VeryVeryLongLoopVariable)\n"
2177       "  ;");
2178   verifyFormat("for (;;)\n"
2179                "  f();");
2180   verifyFormat("for (;;) {\n}");
2181   verifyFormat("for (;;) {\n"
2182                "  f();\n"
2183                "}");
2184   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2185 
2186   verifyFormat(
2187       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2188       "                                          E = UnwrappedLines.end();\n"
2189       "     I != E; ++I) {\n}");
2190 
2191   verifyFormat(
2192       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2193       "     ++IIIII) {\n}");
2194   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2195                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2196                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2197   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2198                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2199                "         E = FD->getDeclsInPrototypeScope().end();\n"
2200                "     I != E; ++I) {\n}");
2201   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2202                "         I = Container.begin(),\n"
2203                "         E = Container.end();\n"
2204                "     I != E; ++I) {\n}",
2205                getLLVMStyleWithColumns(76));
2206 
2207   verifyFormat(
2208       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2209       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2210       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2211       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2212       "     ++aaaaaaaaaaa) {\n}");
2213   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2214                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2215                "     ++i) {\n}");
2216   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2217                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2218                "}");
2219   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2220                "         aaaaaaaaaa);\n"
2221                "     iter; ++iter) {\n"
2222                "}");
2223   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2224                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2225                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2226                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2227 
2228   // These should not be formatted as Objective-C for-in loops.
2229   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2230   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2231   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2232   verifyFormat(
2233       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2234 
2235   FormatStyle NoBinPacking = getLLVMStyle();
2236   NoBinPacking.BinPackParameters = false;
2237   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2238                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2239                "                                           aaaaaaaaaaaaaaaa,\n"
2240                "                                           aaaaaaaaaaaaaaaa,\n"
2241                "                                           aaaaaaaaaaaaaaaa);\n"
2242                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2243                "}",
2244                NoBinPacking);
2245   verifyFormat(
2246       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2247       "                                          E = UnwrappedLines.end();\n"
2248       "     I != E;\n"
2249       "     ++I) {\n}",
2250       NoBinPacking);
2251 
2252   FormatStyle AlignLeft = getLLVMStyle();
2253   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2254   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2255 }
2256 
2257 TEST_F(FormatTest, RangeBasedForLoops) {
2258   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2259                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2260   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2261                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2262   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2263                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2264   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2265                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2266 }
2267 
2268 TEST_F(FormatTest, ForEachLoops) {
2269   FormatStyle Style = getLLVMStyle();
2270   EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2271   EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
2272   verifyFormat("void f() {\n"
2273                "  for (;;) {\n"
2274                "  }\n"
2275                "  foreach (Item *item, itemlist) {\n"
2276                "  }\n"
2277                "  Q_FOREACH (Item *item, itemlist) {\n"
2278                "  }\n"
2279                "  BOOST_FOREACH (Item *item, itemlist) {\n"
2280                "  }\n"
2281                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2282                "}",
2283                Style);
2284   verifyFormat("void f() {\n"
2285                "  for (;;)\n"
2286                "    int j = 1;\n"
2287                "  Q_FOREACH (int v, vec)\n"
2288                "    v *= 2;\n"
2289                "  for (;;) {\n"
2290                "    int j = 1;\n"
2291                "  }\n"
2292                "  Q_FOREACH (int v, vec) {\n"
2293                "    v *= 2;\n"
2294                "  }\n"
2295                "}",
2296                Style);
2297 
2298   FormatStyle ShortBlocks = getLLVMStyle();
2299   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2300   EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
2301   verifyFormat("void f() {\n"
2302                "  for (;;)\n"
2303                "    int j = 1;\n"
2304                "  Q_FOREACH (int &v, vec)\n"
2305                "    v *= 2;\n"
2306                "  for (;;) {\n"
2307                "    int j = 1;\n"
2308                "  }\n"
2309                "  Q_FOREACH (int &v, vec) {\n"
2310                "    int j = 1;\n"
2311                "  }\n"
2312                "}",
2313                ShortBlocks);
2314 
2315   FormatStyle ShortLoops = getLLVMStyle();
2316   ShortLoops.AllowShortLoopsOnASingleLine = true;
2317   EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2318   verifyFormat("void f() {\n"
2319                "  for (;;) int j = 1;\n"
2320                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2321                "  for (;;) {\n"
2322                "    int j = 1;\n"
2323                "  }\n"
2324                "  Q_FOREACH (int &v, vec) {\n"
2325                "    int j = 1;\n"
2326                "  }\n"
2327                "}",
2328                ShortLoops);
2329 
2330   FormatStyle ShortBlocksAndLoops = getLLVMStyle();
2331   ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2332   ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true;
2333   verifyFormat("void f() {\n"
2334                "  for (;;) int j = 1;\n"
2335                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2336                "  for (;;) { int j = 1; }\n"
2337                "  Q_FOREACH (int &v, vec) { int j = 1; }\n"
2338                "}",
2339                ShortBlocksAndLoops);
2340 
2341   Style.SpaceBeforeParens =
2342       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2343   verifyFormat("void f() {\n"
2344                "  for (;;) {\n"
2345                "  }\n"
2346                "  foreach(Item *item, itemlist) {\n"
2347                "  }\n"
2348                "  Q_FOREACH(Item *item, itemlist) {\n"
2349                "  }\n"
2350                "  BOOST_FOREACH(Item *item, itemlist) {\n"
2351                "  }\n"
2352                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2353                "}",
2354                Style);
2355 
2356   // As function-like macros.
2357   verifyFormat("#define foreach(x, y)\n"
2358                "#define Q_FOREACH(x, y)\n"
2359                "#define BOOST_FOREACH(x, y)\n"
2360                "#define UNKNOWN_FOREACH(x, y)\n");
2361 
2362   // Not as function-like macros.
2363   verifyFormat("#define foreach (x, y)\n"
2364                "#define Q_FOREACH (x, y)\n"
2365                "#define BOOST_FOREACH (x, y)\n"
2366                "#define UNKNOWN_FOREACH (x, y)\n");
2367 
2368   // handle microsoft non standard extension
2369   verifyFormat("for each (char c in x->MyStringProperty)");
2370 }
2371 
2372 TEST_F(FormatTest, FormatsWhileLoop) {
2373   verifyFormat("while (true) {\n}");
2374   verifyFormat("while (true)\n"
2375                "  f();");
2376   verifyFormat("while () {\n}");
2377   verifyFormat("while () {\n"
2378                "  f();\n"
2379                "}");
2380 }
2381 
2382 TEST_F(FormatTest, FormatsDoWhile) {
2383   verifyFormat("do {\n"
2384                "  do_something();\n"
2385                "} while (something());");
2386   verifyFormat("do\n"
2387                "  do_something();\n"
2388                "while (something());");
2389 }
2390 
2391 TEST_F(FormatTest, FormatsSwitchStatement) {
2392   verifyFormat("switch (x) {\n"
2393                "case 1:\n"
2394                "  f();\n"
2395                "  break;\n"
2396                "case kFoo:\n"
2397                "case ns::kBar:\n"
2398                "case kBaz:\n"
2399                "  break;\n"
2400                "default:\n"
2401                "  g();\n"
2402                "  break;\n"
2403                "}");
2404   verifyFormat("switch (x) {\n"
2405                "case 1: {\n"
2406                "  f();\n"
2407                "  break;\n"
2408                "}\n"
2409                "case 2: {\n"
2410                "  break;\n"
2411                "}\n"
2412                "}");
2413   verifyFormat("switch (x) {\n"
2414                "case 1: {\n"
2415                "  f();\n"
2416                "  {\n"
2417                "    g();\n"
2418                "    h();\n"
2419                "  }\n"
2420                "  break;\n"
2421                "}\n"
2422                "}");
2423   verifyFormat("switch (x) {\n"
2424                "case 1: {\n"
2425                "  f();\n"
2426                "  if (foo) {\n"
2427                "    g();\n"
2428                "    h();\n"
2429                "  }\n"
2430                "  break;\n"
2431                "}\n"
2432                "}");
2433   verifyFormat("switch (x) {\n"
2434                "case 1: {\n"
2435                "  f();\n"
2436                "  g();\n"
2437                "} break;\n"
2438                "}");
2439   verifyFormat("switch (test)\n"
2440                "  ;");
2441   verifyFormat("switch (x) {\n"
2442                "default: {\n"
2443                "  // Do nothing.\n"
2444                "}\n"
2445                "}");
2446   verifyFormat("switch (x) {\n"
2447                "// comment\n"
2448                "// if 1, do f()\n"
2449                "case 1:\n"
2450                "  f();\n"
2451                "}");
2452   verifyFormat("switch (x) {\n"
2453                "case 1:\n"
2454                "  // Do amazing stuff\n"
2455                "  {\n"
2456                "    f();\n"
2457                "    g();\n"
2458                "  }\n"
2459                "  break;\n"
2460                "}");
2461   verifyFormat("#define A          \\\n"
2462                "  switch (x) {     \\\n"
2463                "  case a:          \\\n"
2464                "    foo = b;       \\\n"
2465                "  }",
2466                getLLVMStyleWithColumns(20));
2467   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2468                "  case OP_name:                        \\\n"
2469                "    return operations::Operation##name\n",
2470                getLLVMStyleWithColumns(40));
2471   verifyFormat("switch (x) {\n"
2472                "case 1:;\n"
2473                "default:;\n"
2474                "  int i;\n"
2475                "}");
2476 
2477   verifyGoogleFormat("switch (x) {\n"
2478                      "  case 1:\n"
2479                      "    f();\n"
2480                      "    break;\n"
2481                      "  case kFoo:\n"
2482                      "  case ns::kBar:\n"
2483                      "  case kBaz:\n"
2484                      "    break;\n"
2485                      "  default:\n"
2486                      "    g();\n"
2487                      "    break;\n"
2488                      "}");
2489   verifyGoogleFormat("switch (x) {\n"
2490                      "  case 1: {\n"
2491                      "    f();\n"
2492                      "    break;\n"
2493                      "  }\n"
2494                      "}");
2495   verifyGoogleFormat("switch (test)\n"
2496                      "  ;");
2497 
2498   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2499                      "  case OP_name:              \\\n"
2500                      "    return operations::Operation##name\n");
2501   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2502                      "  // Get the correction operation class.\n"
2503                      "  switch (OpCode) {\n"
2504                      "    CASE(Add);\n"
2505                      "    CASE(Subtract);\n"
2506                      "    default:\n"
2507                      "      return operations::Unknown;\n"
2508                      "  }\n"
2509                      "#undef OPERATION_CASE\n"
2510                      "}");
2511   verifyFormat("DEBUG({\n"
2512                "  switch (x) {\n"
2513                "  case A:\n"
2514                "    f();\n"
2515                "    break;\n"
2516                "    // fallthrough\n"
2517                "  case B:\n"
2518                "    g();\n"
2519                "    break;\n"
2520                "  }\n"
2521                "});");
2522   EXPECT_EQ("DEBUG({\n"
2523             "  switch (x) {\n"
2524             "  case A:\n"
2525             "    f();\n"
2526             "    break;\n"
2527             "  // On B:\n"
2528             "  case B:\n"
2529             "    g();\n"
2530             "    break;\n"
2531             "  }\n"
2532             "});",
2533             format("DEBUG({\n"
2534                    "  switch (x) {\n"
2535                    "  case A:\n"
2536                    "    f();\n"
2537                    "    break;\n"
2538                    "  // On B:\n"
2539                    "  case B:\n"
2540                    "    g();\n"
2541                    "    break;\n"
2542                    "  }\n"
2543                    "});",
2544                    getLLVMStyle()));
2545   EXPECT_EQ("switch (n) {\n"
2546             "case 0: {\n"
2547             "  return false;\n"
2548             "}\n"
2549             "default: {\n"
2550             "  return true;\n"
2551             "}\n"
2552             "}",
2553             format("switch (n)\n"
2554                    "{\n"
2555                    "case 0: {\n"
2556                    "  return false;\n"
2557                    "}\n"
2558                    "default: {\n"
2559                    "  return true;\n"
2560                    "}\n"
2561                    "}",
2562                    getLLVMStyle()));
2563   verifyFormat("switch (a) {\n"
2564                "case (b):\n"
2565                "  return;\n"
2566                "}");
2567 
2568   verifyFormat("switch (a) {\n"
2569                "case some_namespace::\n"
2570                "    some_constant:\n"
2571                "  return;\n"
2572                "}",
2573                getLLVMStyleWithColumns(34));
2574 
2575   FormatStyle Style = getLLVMStyle();
2576   Style.IndentCaseLabels = true;
2577   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2578   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2579   Style.BraceWrapping.AfterCaseLabel = true;
2580   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2581   EXPECT_EQ("switch (n)\n"
2582             "{\n"
2583             "  case 0:\n"
2584             "  {\n"
2585             "    return false;\n"
2586             "  }\n"
2587             "  default:\n"
2588             "  {\n"
2589             "    return true;\n"
2590             "  }\n"
2591             "}",
2592             format("switch (n) {\n"
2593                    "  case 0: {\n"
2594                    "    return false;\n"
2595                    "  }\n"
2596                    "  default: {\n"
2597                    "    return true;\n"
2598                    "  }\n"
2599                    "}",
2600                    Style));
2601   Style.BraceWrapping.AfterCaseLabel = false;
2602   EXPECT_EQ("switch (n)\n"
2603             "{\n"
2604             "  case 0: {\n"
2605             "    return false;\n"
2606             "  }\n"
2607             "  default: {\n"
2608             "    return true;\n"
2609             "  }\n"
2610             "}",
2611             format("switch (n) {\n"
2612                    "  case 0:\n"
2613                    "  {\n"
2614                    "    return false;\n"
2615                    "  }\n"
2616                    "  default:\n"
2617                    "  {\n"
2618                    "    return true;\n"
2619                    "  }\n"
2620                    "}",
2621                    Style));
2622   Style.IndentCaseLabels = false;
2623   Style.IndentCaseBlocks = true;
2624   EXPECT_EQ("switch (n)\n"
2625             "{\n"
2626             "case 0:\n"
2627             "  {\n"
2628             "    return false;\n"
2629             "  }\n"
2630             "case 1:\n"
2631             "  break;\n"
2632             "default:\n"
2633             "  {\n"
2634             "    return true;\n"
2635             "  }\n"
2636             "}",
2637             format("switch (n) {\n"
2638                    "case 0: {\n"
2639                    "  return false;\n"
2640                    "}\n"
2641                    "case 1:\n"
2642                    "  break;\n"
2643                    "default: {\n"
2644                    "  return true;\n"
2645                    "}\n"
2646                    "}",
2647                    Style));
2648   Style.IndentCaseLabels = true;
2649   Style.IndentCaseBlocks = true;
2650   EXPECT_EQ("switch (n)\n"
2651             "{\n"
2652             "  case 0:\n"
2653             "    {\n"
2654             "      return false;\n"
2655             "    }\n"
2656             "  case 1:\n"
2657             "    break;\n"
2658             "  default:\n"
2659             "    {\n"
2660             "      return true;\n"
2661             "    }\n"
2662             "}",
2663             format("switch (n) {\n"
2664                    "case 0: {\n"
2665                    "  return false;\n"
2666                    "}\n"
2667                    "case 1:\n"
2668                    "  break;\n"
2669                    "default: {\n"
2670                    "  return true;\n"
2671                    "}\n"
2672                    "}",
2673                    Style));
2674 }
2675 
2676 TEST_F(FormatTest, CaseRanges) {
2677   verifyFormat("switch (x) {\n"
2678                "case 'A' ... 'Z':\n"
2679                "case 1 ... 5:\n"
2680                "case a ... b:\n"
2681                "  break;\n"
2682                "}");
2683 }
2684 
2685 TEST_F(FormatTest, ShortEnums) {
2686   FormatStyle Style = getLLVMStyle();
2687   Style.AllowShortEnumsOnASingleLine = true;
2688   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2689   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2690   Style.AllowShortEnumsOnASingleLine = false;
2691   verifyFormat("enum {\n"
2692                "  A,\n"
2693                "  B,\n"
2694                "  C\n"
2695                "} ShortEnum1, ShortEnum2;",
2696                Style);
2697   verifyFormat("typedef enum {\n"
2698                "  A,\n"
2699                "  B,\n"
2700                "  C\n"
2701                "} ShortEnum1, ShortEnum2;",
2702                Style);
2703   verifyFormat("enum {\n"
2704                "  A,\n"
2705                "} ShortEnum1, ShortEnum2;",
2706                Style);
2707   verifyFormat("typedef enum {\n"
2708                "  A,\n"
2709                "} ShortEnum1, ShortEnum2;",
2710                Style);
2711   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2712   Style.BraceWrapping.AfterEnum = true;
2713   verifyFormat("enum\n"
2714                "{\n"
2715                "  A,\n"
2716                "  B,\n"
2717                "  C\n"
2718                "} ShortEnum1, ShortEnum2;",
2719                Style);
2720   verifyFormat("typedef enum\n"
2721                "{\n"
2722                "  A,\n"
2723                "  B,\n"
2724                "  C\n"
2725                "} ShortEnum1, ShortEnum2;",
2726                Style);
2727 }
2728 
2729 TEST_F(FormatTest, ShortCaseLabels) {
2730   FormatStyle Style = getLLVMStyle();
2731   Style.AllowShortCaseLabelsOnASingleLine = true;
2732   verifyFormat("switch (a) {\n"
2733                "case 1: x = 1; break;\n"
2734                "case 2: return;\n"
2735                "case 3:\n"
2736                "case 4:\n"
2737                "case 5: return;\n"
2738                "case 6: // comment\n"
2739                "  return;\n"
2740                "case 7:\n"
2741                "  // comment\n"
2742                "  return;\n"
2743                "case 8:\n"
2744                "  x = 8; // comment\n"
2745                "  break;\n"
2746                "default: y = 1; break;\n"
2747                "}",
2748                Style);
2749   verifyFormat("switch (a) {\n"
2750                "case 0: return; // comment\n"
2751                "case 1: break;  // comment\n"
2752                "case 2: return;\n"
2753                "// comment\n"
2754                "case 3: return;\n"
2755                "// comment 1\n"
2756                "// comment 2\n"
2757                "// comment 3\n"
2758                "case 4: break; /* comment */\n"
2759                "case 5:\n"
2760                "  // comment\n"
2761                "  break;\n"
2762                "case 6: /* comment */ x = 1; break;\n"
2763                "case 7: x = /* comment */ 1; break;\n"
2764                "case 8:\n"
2765                "  x = 1; /* comment */\n"
2766                "  break;\n"
2767                "case 9:\n"
2768                "  break; // comment line 1\n"
2769                "         // comment line 2\n"
2770                "}",
2771                Style);
2772   EXPECT_EQ("switch (a) {\n"
2773             "case 1:\n"
2774             "  x = 8;\n"
2775             "  // fall through\n"
2776             "case 2: x = 8;\n"
2777             "// comment\n"
2778             "case 3:\n"
2779             "  return; /* comment line 1\n"
2780             "           * comment line 2 */\n"
2781             "case 4: i = 8;\n"
2782             "// something else\n"
2783             "#if FOO\n"
2784             "case 5: break;\n"
2785             "#endif\n"
2786             "}",
2787             format("switch (a) {\n"
2788                    "case 1: x = 8;\n"
2789                    "  // fall through\n"
2790                    "case 2:\n"
2791                    "  x = 8;\n"
2792                    "// comment\n"
2793                    "case 3:\n"
2794                    "  return; /* comment line 1\n"
2795                    "           * comment line 2 */\n"
2796                    "case 4:\n"
2797                    "  i = 8;\n"
2798                    "// something else\n"
2799                    "#if FOO\n"
2800                    "case 5: break;\n"
2801                    "#endif\n"
2802                    "}",
2803                    Style));
2804   EXPECT_EQ("switch (a) {\n"
2805             "case 0:\n"
2806             "  return; // long long long long long long long long long long "
2807             "long long comment\n"
2808             "          // line\n"
2809             "}",
2810             format("switch (a) {\n"
2811                    "case 0: return; // long long long long long long long long "
2812                    "long long long long comment line\n"
2813                    "}",
2814                    Style));
2815   EXPECT_EQ("switch (a) {\n"
2816             "case 0:\n"
2817             "  return; /* long long long long long long long long long long "
2818             "long long comment\n"
2819             "             line */\n"
2820             "}",
2821             format("switch (a) {\n"
2822                    "case 0: return; /* long long long long long long long long "
2823                    "long long long long comment line */\n"
2824                    "}",
2825                    Style));
2826   verifyFormat("switch (a) {\n"
2827                "#if FOO\n"
2828                "case 0: return 0;\n"
2829                "#endif\n"
2830                "}",
2831                Style);
2832   verifyFormat("switch (a) {\n"
2833                "case 1: {\n"
2834                "}\n"
2835                "case 2: {\n"
2836                "  return;\n"
2837                "}\n"
2838                "case 3: {\n"
2839                "  x = 1;\n"
2840                "  return;\n"
2841                "}\n"
2842                "case 4:\n"
2843                "  if (x)\n"
2844                "    return;\n"
2845                "}",
2846                Style);
2847   Style.ColumnLimit = 21;
2848   verifyFormat("switch (a) {\n"
2849                "case 1: x = 1; break;\n"
2850                "case 2: return;\n"
2851                "case 3:\n"
2852                "case 4:\n"
2853                "case 5: return;\n"
2854                "default:\n"
2855                "  y = 1;\n"
2856                "  break;\n"
2857                "}",
2858                Style);
2859   Style.ColumnLimit = 80;
2860   Style.AllowShortCaseLabelsOnASingleLine = false;
2861   Style.IndentCaseLabels = true;
2862   EXPECT_EQ("switch (n) {\n"
2863             "  default /*comments*/:\n"
2864             "    return true;\n"
2865             "  case 0:\n"
2866             "    return false;\n"
2867             "}",
2868             format("switch (n) {\n"
2869                    "default/*comments*/:\n"
2870                    "  return true;\n"
2871                    "case 0:\n"
2872                    "  return false;\n"
2873                    "}",
2874                    Style));
2875   Style.AllowShortCaseLabelsOnASingleLine = true;
2876   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2877   Style.BraceWrapping.AfterCaseLabel = true;
2878   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2879   EXPECT_EQ("switch (n)\n"
2880             "{\n"
2881             "  case 0:\n"
2882             "  {\n"
2883             "    return false;\n"
2884             "  }\n"
2885             "  default:\n"
2886             "  {\n"
2887             "    return true;\n"
2888             "  }\n"
2889             "}",
2890             format("switch (n) {\n"
2891                    "  case 0: {\n"
2892                    "    return false;\n"
2893                    "  }\n"
2894                    "  default:\n"
2895                    "  {\n"
2896                    "    return true;\n"
2897                    "  }\n"
2898                    "}",
2899                    Style));
2900 }
2901 
2902 TEST_F(FormatTest, FormatsLabels) {
2903   verifyFormat("void f() {\n"
2904                "  some_code();\n"
2905                "test_label:\n"
2906                "  some_other_code();\n"
2907                "  {\n"
2908                "    some_more_code();\n"
2909                "  another_label:\n"
2910                "    some_more_code();\n"
2911                "  }\n"
2912                "}");
2913   verifyFormat("{\n"
2914                "  some_code();\n"
2915                "test_label:\n"
2916                "  some_other_code();\n"
2917                "}");
2918   verifyFormat("{\n"
2919                "  some_code();\n"
2920                "test_label:;\n"
2921                "  int i = 0;\n"
2922                "}");
2923   FormatStyle Style = getLLVMStyle();
2924   Style.IndentGotoLabels = false;
2925   verifyFormat("void f() {\n"
2926                "  some_code();\n"
2927                "test_label:\n"
2928                "  some_other_code();\n"
2929                "  {\n"
2930                "    some_more_code();\n"
2931                "another_label:\n"
2932                "    some_more_code();\n"
2933                "  }\n"
2934                "}",
2935                Style);
2936   verifyFormat("{\n"
2937                "  some_code();\n"
2938                "test_label:\n"
2939                "  some_other_code();\n"
2940                "}",
2941                Style);
2942   verifyFormat("{\n"
2943                "  some_code();\n"
2944                "test_label:;\n"
2945                "  int i = 0;\n"
2946                "}");
2947 }
2948 
2949 TEST_F(FormatTest, MultiLineControlStatements) {
2950   FormatStyle Style = getLLVMStyleWithColumns(20);
2951   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2952   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2953   // Short lines should keep opening brace on same line.
2954   EXPECT_EQ("if (foo) {\n"
2955             "  bar();\n"
2956             "}",
2957             format("if(foo){bar();}", Style));
2958   EXPECT_EQ("if (foo) {\n"
2959             "  bar();\n"
2960             "} else {\n"
2961             "  baz();\n"
2962             "}",
2963             format("if(foo){bar();}else{baz();}", Style));
2964   EXPECT_EQ("if (foo && bar) {\n"
2965             "  baz();\n"
2966             "}",
2967             format("if(foo&&bar){baz();}", Style));
2968   EXPECT_EQ("if (foo) {\n"
2969             "  bar();\n"
2970             "} else if (baz) {\n"
2971             "  quux();\n"
2972             "}",
2973             format("if(foo){bar();}else if(baz){quux();}", Style));
2974   EXPECT_EQ(
2975       "if (foo) {\n"
2976       "  bar();\n"
2977       "} else if (baz) {\n"
2978       "  quux();\n"
2979       "} else {\n"
2980       "  foobar();\n"
2981       "}",
2982       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
2983   EXPECT_EQ("for (;;) {\n"
2984             "  foo();\n"
2985             "}",
2986             format("for(;;){foo();}"));
2987   EXPECT_EQ("while (1) {\n"
2988             "  foo();\n"
2989             "}",
2990             format("while(1){foo();}", Style));
2991   EXPECT_EQ("switch (foo) {\n"
2992             "case bar:\n"
2993             "  return;\n"
2994             "}",
2995             format("switch(foo){case bar:return;}", Style));
2996   EXPECT_EQ("try {\n"
2997             "  foo();\n"
2998             "} catch (...) {\n"
2999             "  bar();\n"
3000             "}",
3001             format("try{foo();}catch(...){bar();}", Style));
3002   EXPECT_EQ("do {\n"
3003             "  foo();\n"
3004             "} while (bar &&\n"
3005             "         baz);",
3006             format("do{foo();}while(bar&&baz);", Style));
3007   // Long lines should put opening brace on new line.
3008   EXPECT_EQ("if (foo && bar &&\n"
3009             "    baz)\n"
3010             "{\n"
3011             "  quux();\n"
3012             "}",
3013             format("if(foo&&bar&&baz){quux();}", Style));
3014   EXPECT_EQ("if (foo && bar &&\n"
3015             "    baz)\n"
3016             "{\n"
3017             "  quux();\n"
3018             "}",
3019             format("if (foo && bar &&\n"
3020                    "    baz) {\n"
3021                    "  quux();\n"
3022                    "}",
3023                    Style));
3024   EXPECT_EQ("if (foo) {\n"
3025             "  bar();\n"
3026             "} else if (baz ||\n"
3027             "           quux)\n"
3028             "{\n"
3029             "  foobar();\n"
3030             "}",
3031             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
3032   EXPECT_EQ(
3033       "if (foo) {\n"
3034       "  bar();\n"
3035       "} else if (baz ||\n"
3036       "           quux)\n"
3037       "{\n"
3038       "  foobar();\n"
3039       "} else {\n"
3040       "  barbaz();\n"
3041       "}",
3042       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3043              Style));
3044   EXPECT_EQ("for (int i = 0;\n"
3045             "     i < 10; ++i)\n"
3046             "{\n"
3047             "  foo();\n"
3048             "}",
3049             format("for(int i=0;i<10;++i){foo();}", Style));
3050   EXPECT_EQ("foreach (int i,\n"
3051             "         list)\n"
3052             "{\n"
3053             "  foo();\n"
3054             "}",
3055             format("foreach(int i, list){foo();}", Style));
3056   Style.ColumnLimit =
3057       40; // to concentrate at brace wrapping, not line wrap due to column limit
3058   EXPECT_EQ("foreach (int i, list) {\n"
3059             "  foo();\n"
3060             "}",
3061             format("foreach(int i, list){foo();}", Style));
3062   Style.ColumnLimit =
3063       20; // to concentrate at brace wrapping, not line wrap due to column limit
3064   EXPECT_EQ("while (foo || bar ||\n"
3065             "       baz)\n"
3066             "{\n"
3067             "  quux();\n"
3068             "}",
3069             format("while(foo||bar||baz){quux();}", Style));
3070   EXPECT_EQ("switch (\n"
3071             "    foo = barbaz)\n"
3072             "{\n"
3073             "case quux:\n"
3074             "  return;\n"
3075             "}",
3076             format("switch(foo=barbaz){case quux:return;}", Style));
3077   EXPECT_EQ("try {\n"
3078             "  foo();\n"
3079             "} catch (\n"
3080             "    Exception &bar)\n"
3081             "{\n"
3082             "  baz();\n"
3083             "}",
3084             format("try{foo();}catch(Exception&bar){baz();}", Style));
3085   Style.ColumnLimit =
3086       40; // to concentrate at brace wrapping, not line wrap due to column limit
3087   EXPECT_EQ("try {\n"
3088             "  foo();\n"
3089             "} catch (Exception &bar) {\n"
3090             "  baz();\n"
3091             "}",
3092             format("try{foo();}catch(Exception&bar){baz();}", Style));
3093   Style.ColumnLimit =
3094       20; // to concentrate at brace wrapping, not line wrap due to column limit
3095 
3096   Style.BraceWrapping.BeforeElse = true;
3097   EXPECT_EQ(
3098       "if (foo) {\n"
3099       "  bar();\n"
3100       "}\n"
3101       "else if (baz ||\n"
3102       "         quux)\n"
3103       "{\n"
3104       "  foobar();\n"
3105       "}\n"
3106       "else {\n"
3107       "  barbaz();\n"
3108       "}",
3109       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3110              Style));
3111 
3112   Style.BraceWrapping.BeforeCatch = true;
3113   EXPECT_EQ("try {\n"
3114             "  foo();\n"
3115             "}\n"
3116             "catch (...) {\n"
3117             "  baz();\n"
3118             "}",
3119             format("try{foo();}catch(...){baz();}", Style));
3120 
3121   Style.BraceWrapping.AfterFunction = true;
3122   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3123   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
3124   Style.ColumnLimit = 80;
3125   verifyFormat("void shortfunction() { bar(); }", Style);
3126 
3127   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
3128   verifyFormat("void shortfunction()\n"
3129                "{\n"
3130                "  bar();\n"
3131                "}",
3132                Style);
3133 }
3134 
3135 TEST_F(FormatTest, BeforeWhile) {
3136   FormatStyle Style = getLLVMStyle();
3137   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3138 
3139   verifyFormat("do {\n"
3140                "  foo();\n"
3141                "} while (1);",
3142                Style);
3143   Style.BraceWrapping.BeforeWhile = true;
3144   verifyFormat("do {\n"
3145                "  foo();\n"
3146                "}\n"
3147                "while (1);",
3148                Style);
3149 }
3150 
3151 //===----------------------------------------------------------------------===//
3152 // Tests for classes, namespaces, etc.
3153 //===----------------------------------------------------------------------===//
3154 
3155 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3156   verifyFormat("class A {};");
3157 }
3158 
3159 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
3160   verifyFormat("class A {\n"
3161                "public:\n"
3162                "public: // comment\n"
3163                "protected:\n"
3164                "private:\n"
3165                "  void f() {}\n"
3166                "};");
3167   verifyFormat("export class A {\n"
3168                "public:\n"
3169                "public: // comment\n"
3170                "protected:\n"
3171                "private:\n"
3172                "  void f() {}\n"
3173                "};");
3174   verifyGoogleFormat("class A {\n"
3175                      " public:\n"
3176                      " protected:\n"
3177                      " private:\n"
3178                      "  void f() {}\n"
3179                      "};");
3180   verifyGoogleFormat("export class A {\n"
3181                      " public:\n"
3182                      " protected:\n"
3183                      " private:\n"
3184                      "  void f() {}\n"
3185                      "};");
3186   verifyFormat("class A {\n"
3187                "public slots:\n"
3188                "  void f1() {}\n"
3189                "public Q_SLOTS:\n"
3190                "  void f2() {}\n"
3191                "protected slots:\n"
3192                "  void f3() {}\n"
3193                "protected Q_SLOTS:\n"
3194                "  void f4() {}\n"
3195                "private slots:\n"
3196                "  void f5() {}\n"
3197                "private Q_SLOTS:\n"
3198                "  void f6() {}\n"
3199                "signals:\n"
3200                "  void g1();\n"
3201                "Q_SIGNALS:\n"
3202                "  void g2();\n"
3203                "};");
3204 
3205   // Don't interpret 'signals' the wrong way.
3206   verifyFormat("signals.set();");
3207   verifyFormat("for (Signals signals : f()) {\n}");
3208   verifyFormat("{\n"
3209                "  signals.set(); // This needs indentation.\n"
3210                "}");
3211   verifyFormat("void f() {\n"
3212                "label:\n"
3213                "  signals.baz();\n"
3214                "}");
3215   verifyFormat("private[1];");
3216   verifyFormat("testArray[public] = 1;");
3217   verifyFormat("public();");
3218   verifyFormat("myFunc(public);");
3219   verifyFormat("std::vector<int> testVec = {private};");
3220   verifyFormat("private.p = 1;");
3221   verifyFormat("void function(private...){};");
3222   verifyFormat("if (private && public)\n");
3223   verifyFormat("private &= true;");
3224   verifyFormat("int x = private * public;");
3225   verifyFormat("public *= private;");
3226   verifyFormat("int x = public + private;");
3227   verifyFormat("private++;");
3228   verifyFormat("++private;");
3229   verifyFormat("public += private;");
3230   verifyFormat("public = public - private;");
3231   verifyFormat("public->foo();");
3232   verifyFormat("private--;");
3233   verifyFormat("--private;");
3234   verifyFormat("public -= 1;");
3235   verifyFormat("if (!private && !public)\n");
3236   verifyFormat("public != private;");
3237   verifyFormat("int x = public / private;");
3238   verifyFormat("public /= 2;");
3239   verifyFormat("public = public % 2;");
3240   verifyFormat("public %= 2;");
3241   verifyFormat("if (public < private)\n");
3242   verifyFormat("public << private;");
3243   verifyFormat("public <<= private;");
3244   verifyFormat("if (public > private)\n");
3245   verifyFormat("public >> private;");
3246   verifyFormat("public >>= private;");
3247   verifyFormat("public ^ private;");
3248   verifyFormat("public ^= private;");
3249   verifyFormat("public | private;");
3250   verifyFormat("public |= private;");
3251   verifyFormat("auto x = private ? 1 : 2;");
3252   verifyFormat("if (public == private)\n");
3253   verifyFormat("void foo(public, private)");
3254   verifyFormat("public::foo();");
3255 }
3256 
3257 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3258   EXPECT_EQ("class A {\n"
3259             "public:\n"
3260             "  void f();\n"
3261             "\n"
3262             "private:\n"
3263             "  void g() {}\n"
3264             "  // test\n"
3265             "protected:\n"
3266             "  int h;\n"
3267             "};",
3268             format("class A {\n"
3269                    "public:\n"
3270                    "void f();\n"
3271                    "private:\n"
3272                    "void g() {}\n"
3273                    "// test\n"
3274                    "protected:\n"
3275                    "int h;\n"
3276                    "};"));
3277   EXPECT_EQ("class A {\n"
3278             "protected:\n"
3279             "public:\n"
3280             "  void f();\n"
3281             "};",
3282             format("class A {\n"
3283                    "protected:\n"
3284                    "\n"
3285                    "public:\n"
3286                    "\n"
3287                    "  void f();\n"
3288                    "};"));
3289 
3290   // Even ensure proper spacing inside macros.
3291   EXPECT_EQ("#define B     \\\n"
3292             "  class A {   \\\n"
3293             "   protected: \\\n"
3294             "   public:    \\\n"
3295             "    void f(); \\\n"
3296             "  };",
3297             format("#define B     \\\n"
3298                    "  class A {   \\\n"
3299                    "   protected: \\\n"
3300                    "              \\\n"
3301                    "   public:    \\\n"
3302                    "              \\\n"
3303                    "    void f(); \\\n"
3304                    "  };",
3305                    getGoogleStyle()));
3306   // But don't remove empty lines after macros ending in access specifiers.
3307   EXPECT_EQ("#define A private:\n"
3308             "\n"
3309             "int i;",
3310             format("#define A         private:\n"
3311                    "\n"
3312                    "int              i;"));
3313 }
3314 
3315 TEST_F(FormatTest, FormatsClasses) {
3316   verifyFormat("class A : public B {};");
3317   verifyFormat("class A : public ::B {};");
3318 
3319   verifyFormat(
3320       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3321       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3322   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3323                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3324                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3325   verifyFormat(
3326       "class A : public B, public C, public D, public E, public F {};");
3327   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3328                "                     public C,\n"
3329                "                     public D,\n"
3330                "                     public E,\n"
3331                "                     public F,\n"
3332                "                     public G {};");
3333 
3334   verifyFormat("class\n"
3335                "    ReallyReallyLongClassName {\n"
3336                "  int i;\n"
3337                "};",
3338                getLLVMStyleWithColumns(32));
3339   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3340                "                           aaaaaaaaaaaaaaaa> {};");
3341   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3342                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3343                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3344   verifyFormat("template <class R, class C>\n"
3345                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3346                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3347   verifyFormat("class ::A::B {};");
3348 }
3349 
3350 TEST_F(FormatTest, BreakInheritanceStyle) {
3351   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3352   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3353       FormatStyle::BILS_BeforeComma;
3354   verifyFormat("class MyClass : public X {};",
3355                StyleWithInheritanceBreakBeforeComma);
3356   verifyFormat("class MyClass\n"
3357                "    : public X\n"
3358                "    , public Y {};",
3359                StyleWithInheritanceBreakBeforeComma);
3360   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3361                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3362                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3363                StyleWithInheritanceBreakBeforeComma);
3364   verifyFormat("struct aaaaaaaaaaaaa\n"
3365                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3366                "          aaaaaaaaaaaaaaaa> {};",
3367                StyleWithInheritanceBreakBeforeComma);
3368 
3369   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3370   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3371       FormatStyle::BILS_AfterColon;
3372   verifyFormat("class MyClass : public X {};",
3373                StyleWithInheritanceBreakAfterColon);
3374   verifyFormat("class MyClass : public X, public Y {};",
3375                StyleWithInheritanceBreakAfterColon);
3376   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3377                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3378                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3379                StyleWithInheritanceBreakAfterColon);
3380   verifyFormat("struct aaaaaaaaaaaaa :\n"
3381                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3382                "        aaaaaaaaaaaaaaaa> {};",
3383                StyleWithInheritanceBreakAfterColon);
3384 
3385   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3386   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3387       FormatStyle::BILS_AfterComma;
3388   verifyFormat("class MyClass : public X {};",
3389                StyleWithInheritanceBreakAfterComma);
3390   verifyFormat("class MyClass : public X,\n"
3391                "                public Y {};",
3392                StyleWithInheritanceBreakAfterComma);
3393   verifyFormat(
3394       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3395       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3396       "{};",
3397       StyleWithInheritanceBreakAfterComma);
3398   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3399                "                           aaaaaaaaaaaaaaaa> {};",
3400                StyleWithInheritanceBreakAfterComma);
3401   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3402                "    : public OnceBreak,\n"
3403                "      public AlwaysBreak,\n"
3404                "      EvenBasesFitInOneLine {};",
3405                StyleWithInheritanceBreakAfterComma);
3406 }
3407 
3408 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
3409   verifyFormat("class A {\n} a, b;");
3410   verifyFormat("struct A {\n} a, b;");
3411   verifyFormat("union A {\n} a, b;");
3412 
3413   verifyFormat("constexpr class A {\n} a, b;");
3414   verifyFormat("constexpr struct A {\n} a, b;");
3415   verifyFormat("constexpr union A {\n} a, b;");
3416 
3417   verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
3418   verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
3419   verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
3420 
3421   verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
3422   verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
3423   verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
3424 
3425   verifyFormat("namespace ns {\n"
3426                "class {\n"
3427                "} a, b;\n"
3428                "} // namespace ns");
3429   verifyFormat("namespace ns {\n"
3430                "const class {\n"
3431                "} a, b;\n"
3432                "} // namespace ns");
3433   verifyFormat("namespace ns {\n"
3434                "constexpr class C {\n"
3435                "} a, b;\n"
3436                "} // namespace ns");
3437   verifyFormat("namespace ns {\n"
3438                "class { /* comment */\n"
3439                "} a, b;\n"
3440                "} // namespace ns");
3441   verifyFormat("namespace ns {\n"
3442                "const class { /* comment */\n"
3443                "} a, b;\n"
3444                "} // namespace ns");
3445 }
3446 
3447 TEST_F(FormatTest, FormatsEnum) {
3448   verifyFormat("enum {\n"
3449                "  Zero,\n"
3450                "  One = 1,\n"
3451                "  Two = One + 1,\n"
3452                "  Three = (One + Two),\n"
3453                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3454                "  Five = (One, Two, Three, Four, 5)\n"
3455                "};");
3456   verifyGoogleFormat("enum {\n"
3457                      "  Zero,\n"
3458                      "  One = 1,\n"
3459                      "  Two = One + 1,\n"
3460                      "  Three = (One + Two),\n"
3461                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3462                      "  Five = (One, Two, Three, Four, 5)\n"
3463                      "};");
3464   verifyFormat("enum Enum {};");
3465   verifyFormat("enum {};");
3466   verifyFormat("enum X E {} d;");
3467   verifyFormat("enum __attribute__((...)) E {} d;");
3468   verifyFormat("enum __declspec__((...)) E {} d;");
3469   verifyFormat("enum {\n"
3470                "  Bar = Foo<int, int>::value\n"
3471                "};",
3472                getLLVMStyleWithColumns(30));
3473 
3474   verifyFormat("enum ShortEnum { A, B, C };");
3475   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3476 
3477   EXPECT_EQ("enum KeepEmptyLines {\n"
3478             "  ONE,\n"
3479             "\n"
3480             "  TWO,\n"
3481             "\n"
3482             "  THREE\n"
3483             "}",
3484             format("enum KeepEmptyLines {\n"
3485                    "  ONE,\n"
3486                    "\n"
3487                    "  TWO,\n"
3488                    "\n"
3489                    "\n"
3490                    "  THREE\n"
3491                    "}"));
3492   verifyFormat("enum E { // comment\n"
3493                "  ONE,\n"
3494                "  TWO\n"
3495                "};\n"
3496                "int i;");
3497 
3498   FormatStyle EightIndent = getLLVMStyle();
3499   EightIndent.IndentWidth = 8;
3500   verifyFormat("enum {\n"
3501                "        VOID,\n"
3502                "        CHAR,\n"
3503                "        SHORT,\n"
3504                "        INT,\n"
3505                "        LONG,\n"
3506                "        SIGNED,\n"
3507                "        UNSIGNED,\n"
3508                "        BOOL,\n"
3509                "        FLOAT,\n"
3510                "        DOUBLE,\n"
3511                "        COMPLEX\n"
3512                "};",
3513                EightIndent);
3514 
3515   // Not enums.
3516   verifyFormat("enum X f() {\n"
3517                "  a();\n"
3518                "  return 42;\n"
3519                "}");
3520   verifyFormat("enum X Type::f() {\n"
3521                "  a();\n"
3522                "  return 42;\n"
3523                "}");
3524   verifyFormat("enum ::X f() {\n"
3525                "  a();\n"
3526                "  return 42;\n"
3527                "}");
3528   verifyFormat("enum ns::X f() {\n"
3529                "  a();\n"
3530                "  return 42;\n"
3531                "}");
3532 }
3533 
3534 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3535   verifyFormat("enum Type {\n"
3536                "  One = 0; // These semicolons should be commas.\n"
3537                "  Two = 1;\n"
3538                "};");
3539   verifyFormat("namespace n {\n"
3540                "enum Type {\n"
3541                "  One,\n"
3542                "  Two, // missing };\n"
3543                "  int i;\n"
3544                "}\n"
3545                "void g() {}");
3546 }
3547 
3548 TEST_F(FormatTest, FormatsEnumStruct) {
3549   verifyFormat("enum struct {\n"
3550                "  Zero,\n"
3551                "  One = 1,\n"
3552                "  Two = One + 1,\n"
3553                "  Three = (One + Two),\n"
3554                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3555                "  Five = (One, Two, Three, Four, 5)\n"
3556                "};");
3557   verifyFormat("enum struct Enum {};");
3558   verifyFormat("enum struct {};");
3559   verifyFormat("enum struct X E {} d;");
3560   verifyFormat("enum struct __attribute__((...)) E {} d;");
3561   verifyFormat("enum struct __declspec__((...)) E {} d;");
3562   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3563 }
3564 
3565 TEST_F(FormatTest, FormatsEnumClass) {
3566   verifyFormat("enum class {\n"
3567                "  Zero,\n"
3568                "  One = 1,\n"
3569                "  Two = One + 1,\n"
3570                "  Three = (One + Two),\n"
3571                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3572                "  Five = (One, Two, Three, Four, 5)\n"
3573                "};");
3574   verifyFormat("enum class Enum {};");
3575   verifyFormat("enum class {};");
3576   verifyFormat("enum class X E {} d;");
3577   verifyFormat("enum class __attribute__((...)) E {} d;");
3578   verifyFormat("enum class __declspec__((...)) E {} d;");
3579   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3580 }
3581 
3582 TEST_F(FormatTest, FormatsEnumTypes) {
3583   verifyFormat("enum X : int {\n"
3584                "  A, // Force multiple lines.\n"
3585                "  B\n"
3586                "};");
3587   verifyFormat("enum X : int { A, B };");
3588   verifyFormat("enum X : std::uint32_t { A, B };");
3589 }
3590 
3591 TEST_F(FormatTest, FormatsTypedefEnum) {
3592   FormatStyle Style = getLLVMStyleWithColumns(40);
3593   verifyFormat("typedef enum {} EmptyEnum;");
3594   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3595   verifyFormat("typedef enum {\n"
3596                "  ZERO = 0,\n"
3597                "  ONE = 1,\n"
3598                "  TWO = 2,\n"
3599                "  THREE = 3\n"
3600                "} LongEnum;",
3601                Style);
3602   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3603   Style.BraceWrapping.AfterEnum = true;
3604   verifyFormat("typedef enum {} EmptyEnum;");
3605   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3606   verifyFormat("typedef enum\n"
3607                "{\n"
3608                "  ZERO = 0,\n"
3609                "  ONE = 1,\n"
3610                "  TWO = 2,\n"
3611                "  THREE = 3\n"
3612                "} LongEnum;",
3613                Style);
3614 }
3615 
3616 TEST_F(FormatTest, FormatsNSEnums) {
3617   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3618   verifyGoogleFormat(
3619       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3620   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3621                      "  // Information about someDecentlyLongValue.\n"
3622                      "  someDecentlyLongValue,\n"
3623                      "  // Information about anotherDecentlyLongValue.\n"
3624                      "  anotherDecentlyLongValue,\n"
3625                      "  // Information about aThirdDecentlyLongValue.\n"
3626                      "  aThirdDecentlyLongValue\n"
3627                      "};");
3628   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3629                      "  // Information about someDecentlyLongValue.\n"
3630                      "  someDecentlyLongValue,\n"
3631                      "  // Information about anotherDecentlyLongValue.\n"
3632                      "  anotherDecentlyLongValue,\n"
3633                      "  // Information about aThirdDecentlyLongValue.\n"
3634                      "  aThirdDecentlyLongValue\n"
3635                      "};");
3636   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3637                      "  a = 1,\n"
3638                      "  b = 2,\n"
3639                      "  c = 3,\n"
3640                      "};");
3641   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3642                      "  a = 1,\n"
3643                      "  b = 2,\n"
3644                      "  c = 3,\n"
3645                      "};");
3646   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3647                      "  a = 1,\n"
3648                      "  b = 2,\n"
3649                      "  c = 3,\n"
3650                      "};");
3651   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3652                      "  a = 1,\n"
3653                      "  b = 2,\n"
3654                      "  c = 3,\n"
3655                      "};");
3656 }
3657 
3658 TEST_F(FormatTest, FormatsBitfields) {
3659   verifyFormat("struct Bitfields {\n"
3660                "  unsigned sClass : 8;\n"
3661                "  unsigned ValueKind : 2;\n"
3662                "};");
3663   verifyFormat("struct A {\n"
3664                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3665                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3666                "};");
3667   verifyFormat("struct MyStruct {\n"
3668                "  uchar data;\n"
3669                "  uchar : 8;\n"
3670                "  uchar : 8;\n"
3671                "  uchar other;\n"
3672                "};");
3673   FormatStyle Style = getLLVMStyle();
3674   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3675   verifyFormat("struct Bitfields {\n"
3676                "  unsigned sClass:8;\n"
3677                "  unsigned ValueKind:2;\n"
3678                "  uchar other;\n"
3679                "};",
3680                Style);
3681   verifyFormat("struct A {\n"
3682                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3683                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3684                "};",
3685                Style);
3686   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3687   verifyFormat("struct Bitfields {\n"
3688                "  unsigned sClass :8;\n"
3689                "  unsigned ValueKind :2;\n"
3690                "  uchar other;\n"
3691                "};",
3692                Style);
3693   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3694   verifyFormat("struct Bitfields {\n"
3695                "  unsigned sClass: 8;\n"
3696                "  unsigned ValueKind: 2;\n"
3697                "  uchar other;\n"
3698                "};",
3699                Style);
3700 }
3701 
3702 TEST_F(FormatTest, FormatsNamespaces) {
3703   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3704   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3705 
3706   verifyFormat("namespace some_namespace {\n"
3707                "class A {};\n"
3708                "void f() { f(); }\n"
3709                "}",
3710                LLVMWithNoNamespaceFix);
3711   verifyFormat("namespace N::inline D {\n"
3712                "class A {};\n"
3713                "void f() { f(); }\n"
3714                "}",
3715                LLVMWithNoNamespaceFix);
3716   verifyFormat("namespace N::inline D::E {\n"
3717                "class A {};\n"
3718                "void f() { f(); }\n"
3719                "}",
3720                LLVMWithNoNamespaceFix);
3721   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3722                "class A {};\n"
3723                "void f() { f(); }\n"
3724                "}",
3725                LLVMWithNoNamespaceFix);
3726   verifyFormat("/* something */ namespace some_namespace {\n"
3727                "class A {};\n"
3728                "void f() { f(); }\n"
3729                "}",
3730                LLVMWithNoNamespaceFix);
3731   verifyFormat("namespace {\n"
3732                "class A {};\n"
3733                "void f() { f(); }\n"
3734                "}",
3735                LLVMWithNoNamespaceFix);
3736   verifyFormat("/* something */ namespace {\n"
3737                "class A {};\n"
3738                "void f() { f(); }\n"
3739                "}",
3740                LLVMWithNoNamespaceFix);
3741   verifyFormat("inline namespace X {\n"
3742                "class A {};\n"
3743                "void f() { f(); }\n"
3744                "}",
3745                LLVMWithNoNamespaceFix);
3746   verifyFormat("/* something */ inline namespace X {\n"
3747                "class A {};\n"
3748                "void f() { f(); }\n"
3749                "}",
3750                LLVMWithNoNamespaceFix);
3751   verifyFormat("export namespace X {\n"
3752                "class A {};\n"
3753                "void f() { f(); }\n"
3754                "}",
3755                LLVMWithNoNamespaceFix);
3756   verifyFormat("using namespace some_namespace;\n"
3757                "class A {};\n"
3758                "void f() { f(); }",
3759                LLVMWithNoNamespaceFix);
3760 
3761   // This code is more common than we thought; if we
3762   // layout this correctly the semicolon will go into
3763   // its own line, which is undesirable.
3764   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3765   verifyFormat("namespace {\n"
3766                "class A {};\n"
3767                "};",
3768                LLVMWithNoNamespaceFix);
3769 
3770   verifyFormat("namespace {\n"
3771                "int SomeVariable = 0; // comment\n"
3772                "} // namespace",
3773                LLVMWithNoNamespaceFix);
3774   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3775             "#define HEADER_GUARD\n"
3776             "namespace my_namespace {\n"
3777             "int i;\n"
3778             "} // my_namespace\n"
3779             "#endif // HEADER_GUARD",
3780             format("#ifndef HEADER_GUARD\n"
3781                    " #define HEADER_GUARD\n"
3782                    "   namespace my_namespace {\n"
3783                    "int i;\n"
3784                    "}    // my_namespace\n"
3785                    "#endif    // HEADER_GUARD",
3786                    LLVMWithNoNamespaceFix));
3787 
3788   EXPECT_EQ("namespace A::B {\n"
3789             "class C {};\n"
3790             "}",
3791             format("namespace A::B {\n"
3792                    "class C {};\n"
3793                    "}",
3794                    LLVMWithNoNamespaceFix));
3795 
3796   FormatStyle Style = getLLVMStyle();
3797   Style.NamespaceIndentation = FormatStyle::NI_All;
3798   EXPECT_EQ("namespace out {\n"
3799             "  int i;\n"
3800             "  namespace in {\n"
3801             "    int i;\n"
3802             "  } // namespace in\n"
3803             "} // namespace out",
3804             format("namespace out {\n"
3805                    "int i;\n"
3806                    "namespace in {\n"
3807                    "int i;\n"
3808                    "} // namespace in\n"
3809                    "} // namespace out",
3810                    Style));
3811 
3812   FormatStyle ShortInlineFunctions = getLLVMStyle();
3813   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3814   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3815       FormatStyle::SFS_Inline;
3816   verifyFormat("namespace {\n"
3817                "  void f() {\n"
3818                "    return;\n"
3819                "  }\n"
3820                "} // namespace\n",
3821                ShortInlineFunctions);
3822   verifyFormat("namespace { /* comment */\n"
3823                "  void f() {\n"
3824                "    return;\n"
3825                "  }\n"
3826                "} // namespace\n",
3827                ShortInlineFunctions);
3828   verifyFormat("namespace { // comment\n"
3829                "  void f() {\n"
3830                "    return;\n"
3831                "  }\n"
3832                "} // namespace\n",
3833                ShortInlineFunctions);
3834   verifyFormat("namespace {\n"
3835                "  int some_int;\n"
3836                "  void f() {\n"
3837                "    return;\n"
3838                "  }\n"
3839                "} // namespace\n",
3840                ShortInlineFunctions);
3841   verifyFormat("namespace interface {\n"
3842                "  void f() {\n"
3843                "    return;\n"
3844                "  }\n"
3845                "} // namespace interface\n",
3846                ShortInlineFunctions);
3847   verifyFormat("namespace {\n"
3848                "  class X {\n"
3849                "    void f() { return; }\n"
3850                "  };\n"
3851                "} // namespace\n",
3852                ShortInlineFunctions);
3853   verifyFormat("namespace {\n"
3854                "  class X { /* comment */\n"
3855                "    void f() { return; }\n"
3856                "  };\n"
3857                "} // namespace\n",
3858                ShortInlineFunctions);
3859   verifyFormat("namespace {\n"
3860                "  class X { // comment\n"
3861                "    void f() { return; }\n"
3862                "  };\n"
3863                "} // namespace\n",
3864                ShortInlineFunctions);
3865   verifyFormat("namespace {\n"
3866                "  struct X {\n"
3867                "    void f() { return; }\n"
3868                "  };\n"
3869                "} // namespace\n",
3870                ShortInlineFunctions);
3871   verifyFormat("namespace {\n"
3872                "  union X {\n"
3873                "    void f() { return; }\n"
3874                "  };\n"
3875                "} // namespace\n",
3876                ShortInlineFunctions);
3877   verifyFormat("extern \"C\" {\n"
3878                "void f() {\n"
3879                "  return;\n"
3880                "}\n"
3881                "} // namespace\n",
3882                ShortInlineFunctions);
3883   verifyFormat("namespace {\n"
3884                "  class X {\n"
3885                "    void f() { return; }\n"
3886                "  } x;\n"
3887                "} // namespace\n",
3888                ShortInlineFunctions);
3889   verifyFormat("namespace {\n"
3890                "  [[nodiscard]] class X {\n"
3891                "    void f() { return; }\n"
3892                "  };\n"
3893                "} // namespace\n",
3894                ShortInlineFunctions);
3895   verifyFormat("namespace {\n"
3896                "  static class X {\n"
3897                "    void f() { return; }\n"
3898                "  } x;\n"
3899                "} // namespace\n",
3900                ShortInlineFunctions);
3901   verifyFormat("namespace {\n"
3902                "  constexpr class X {\n"
3903                "    void f() { return; }\n"
3904                "  } x;\n"
3905                "} // namespace\n",
3906                ShortInlineFunctions);
3907 
3908   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
3909   verifyFormat("extern \"C\" {\n"
3910                "  void f() {\n"
3911                "    return;\n"
3912                "  }\n"
3913                "} // namespace\n",
3914                ShortInlineFunctions);
3915 
3916   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3917   EXPECT_EQ("namespace out {\n"
3918             "int i;\n"
3919             "namespace in {\n"
3920             "  int i;\n"
3921             "} // namespace in\n"
3922             "} // namespace out",
3923             format("namespace out {\n"
3924                    "int i;\n"
3925                    "namespace in {\n"
3926                    "int i;\n"
3927                    "} // namespace in\n"
3928                    "} // namespace out",
3929                    Style));
3930 
3931   Style.NamespaceIndentation = FormatStyle::NI_None;
3932   verifyFormat("template <class T>\n"
3933                "concept a_concept = X<>;\n"
3934                "namespace B {\n"
3935                "struct b_struct {};\n"
3936                "} // namespace B\n",
3937                Style);
3938   verifyFormat("template <int I>\n"
3939                "constexpr void foo()\n"
3940                "  requires(I == 42)\n"
3941                "{}\n"
3942                "namespace ns {\n"
3943                "void foo() {}\n"
3944                "} // namespace ns\n",
3945                Style);
3946 }
3947 
3948 TEST_F(FormatTest, NamespaceMacros) {
3949   FormatStyle Style = getLLVMStyle();
3950   Style.NamespaceMacros.push_back("TESTSUITE");
3951 
3952   verifyFormat("TESTSUITE(A) {\n"
3953                "int foo();\n"
3954                "} // TESTSUITE(A)",
3955                Style);
3956 
3957   verifyFormat("TESTSUITE(A, B) {\n"
3958                "int foo();\n"
3959                "} // TESTSUITE(A)",
3960                Style);
3961 
3962   // Properly indent according to NamespaceIndentation style
3963   Style.NamespaceIndentation = FormatStyle::NI_All;
3964   verifyFormat("TESTSUITE(A) {\n"
3965                "  int foo();\n"
3966                "} // TESTSUITE(A)",
3967                Style);
3968   verifyFormat("TESTSUITE(A) {\n"
3969                "  namespace B {\n"
3970                "    int foo();\n"
3971                "  } // namespace B\n"
3972                "} // TESTSUITE(A)",
3973                Style);
3974   verifyFormat("namespace A {\n"
3975                "  TESTSUITE(B) {\n"
3976                "    int foo();\n"
3977                "  } // TESTSUITE(B)\n"
3978                "} // namespace A",
3979                Style);
3980 
3981   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3982   verifyFormat("TESTSUITE(A) {\n"
3983                "TESTSUITE(B) {\n"
3984                "  int foo();\n"
3985                "} // TESTSUITE(B)\n"
3986                "} // TESTSUITE(A)",
3987                Style);
3988   verifyFormat("TESTSUITE(A) {\n"
3989                "namespace B {\n"
3990                "  int foo();\n"
3991                "} // namespace B\n"
3992                "} // TESTSUITE(A)",
3993                Style);
3994   verifyFormat("namespace A {\n"
3995                "TESTSUITE(B) {\n"
3996                "  int foo();\n"
3997                "} // TESTSUITE(B)\n"
3998                "} // namespace A",
3999                Style);
4000 
4001   // Properly merge namespace-macros blocks in CompactNamespaces mode
4002   Style.NamespaceIndentation = FormatStyle::NI_None;
4003   Style.CompactNamespaces = true;
4004   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
4005                "}} // TESTSUITE(A::B)",
4006                Style);
4007 
4008   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4009             "}} // TESTSUITE(out::in)",
4010             format("TESTSUITE(out) {\n"
4011                    "TESTSUITE(in) {\n"
4012                    "} // TESTSUITE(in)\n"
4013                    "} // TESTSUITE(out)",
4014                    Style));
4015 
4016   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4017             "}} // TESTSUITE(out::in)",
4018             format("TESTSUITE(out) {\n"
4019                    "TESTSUITE(in) {\n"
4020                    "} // TESTSUITE(in)\n"
4021                    "} // TESTSUITE(out)",
4022                    Style));
4023 
4024   // Do not merge different namespaces/macros
4025   EXPECT_EQ("namespace out {\n"
4026             "TESTSUITE(in) {\n"
4027             "} // TESTSUITE(in)\n"
4028             "} // namespace out",
4029             format("namespace out {\n"
4030                    "TESTSUITE(in) {\n"
4031                    "} // TESTSUITE(in)\n"
4032                    "} // namespace out",
4033                    Style));
4034   EXPECT_EQ("TESTSUITE(out) {\n"
4035             "namespace in {\n"
4036             "} // namespace in\n"
4037             "} // TESTSUITE(out)",
4038             format("TESTSUITE(out) {\n"
4039                    "namespace in {\n"
4040                    "} // namespace in\n"
4041                    "} // TESTSUITE(out)",
4042                    Style));
4043   Style.NamespaceMacros.push_back("FOOBAR");
4044   EXPECT_EQ("TESTSUITE(out) {\n"
4045             "FOOBAR(in) {\n"
4046             "} // FOOBAR(in)\n"
4047             "} // TESTSUITE(out)",
4048             format("TESTSUITE(out) {\n"
4049                    "FOOBAR(in) {\n"
4050                    "} // FOOBAR(in)\n"
4051                    "} // TESTSUITE(out)",
4052                    Style));
4053 }
4054 
4055 TEST_F(FormatTest, FormatsCompactNamespaces) {
4056   FormatStyle Style = getLLVMStyle();
4057   Style.CompactNamespaces = true;
4058   Style.NamespaceMacros.push_back("TESTSUITE");
4059 
4060   verifyFormat("namespace A { namespace B {\n"
4061                "}} // namespace A::B",
4062                Style);
4063 
4064   EXPECT_EQ("namespace out { namespace in {\n"
4065             "}} // namespace out::in",
4066             format("namespace out {\n"
4067                    "namespace in {\n"
4068                    "} // namespace in\n"
4069                    "} // namespace out",
4070                    Style));
4071 
4072   // Only namespaces which have both consecutive opening and end get compacted
4073   EXPECT_EQ("namespace out {\n"
4074             "namespace in1 {\n"
4075             "} // namespace in1\n"
4076             "namespace in2 {\n"
4077             "} // namespace in2\n"
4078             "} // namespace out",
4079             format("namespace out {\n"
4080                    "namespace in1 {\n"
4081                    "} // namespace in1\n"
4082                    "namespace in2 {\n"
4083                    "} // namespace in2\n"
4084                    "} // namespace out",
4085                    Style));
4086 
4087   EXPECT_EQ("namespace out {\n"
4088             "int i;\n"
4089             "namespace in {\n"
4090             "int j;\n"
4091             "} // namespace in\n"
4092             "int k;\n"
4093             "} // namespace out",
4094             format("namespace out { int i;\n"
4095                    "namespace in { int j; } // namespace in\n"
4096                    "int k; } // namespace out",
4097                    Style));
4098 
4099   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
4100             "}}} // namespace A::B::C\n",
4101             format("namespace A { namespace B {\n"
4102                    "namespace C {\n"
4103                    "}} // namespace B::C\n"
4104                    "} // namespace A\n",
4105                    Style));
4106 
4107   Style.ColumnLimit = 40;
4108   EXPECT_EQ("namespace aaaaaaaaaa {\n"
4109             "namespace bbbbbbbbbb {\n"
4110             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
4111             format("namespace aaaaaaaaaa {\n"
4112                    "namespace bbbbbbbbbb {\n"
4113                    "} // namespace bbbbbbbbbb\n"
4114                    "} // namespace aaaaaaaaaa",
4115                    Style));
4116 
4117   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
4118             "namespace cccccc {\n"
4119             "}}} // namespace aaaaaa::bbbbbb::cccccc",
4120             format("namespace aaaaaa {\n"
4121                    "namespace bbbbbb {\n"
4122                    "namespace cccccc {\n"
4123                    "} // namespace cccccc\n"
4124                    "} // namespace bbbbbb\n"
4125                    "} // namespace aaaaaa",
4126                    Style));
4127   Style.ColumnLimit = 80;
4128 
4129   // Extra semicolon after 'inner' closing brace prevents merging
4130   EXPECT_EQ("namespace out { namespace in {\n"
4131             "}; } // namespace out::in",
4132             format("namespace out {\n"
4133                    "namespace in {\n"
4134                    "}; // namespace in\n"
4135                    "} // namespace out",
4136                    Style));
4137 
4138   // Extra semicolon after 'outer' closing brace is conserved
4139   EXPECT_EQ("namespace out { namespace in {\n"
4140             "}}; // namespace out::in",
4141             format("namespace out {\n"
4142                    "namespace in {\n"
4143                    "} // namespace in\n"
4144                    "}; // namespace out",
4145                    Style));
4146 
4147   Style.NamespaceIndentation = FormatStyle::NI_All;
4148   EXPECT_EQ("namespace out { namespace in {\n"
4149             "  int i;\n"
4150             "}} // namespace out::in",
4151             format("namespace out {\n"
4152                    "namespace in {\n"
4153                    "int i;\n"
4154                    "} // namespace in\n"
4155                    "} // namespace out",
4156                    Style));
4157   EXPECT_EQ("namespace out { namespace mid {\n"
4158             "  namespace in {\n"
4159             "    int j;\n"
4160             "  } // namespace in\n"
4161             "  int k;\n"
4162             "}} // namespace out::mid",
4163             format("namespace out { namespace mid {\n"
4164                    "namespace in { int j; } // namespace in\n"
4165                    "int k; }} // namespace out::mid",
4166                    Style));
4167 
4168   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4169   EXPECT_EQ("namespace out { namespace in {\n"
4170             "  int i;\n"
4171             "}} // namespace out::in",
4172             format("namespace out {\n"
4173                    "namespace in {\n"
4174                    "int i;\n"
4175                    "} // namespace in\n"
4176                    "} // namespace out",
4177                    Style));
4178   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
4179             "  int i;\n"
4180             "}}} // namespace out::mid::in",
4181             format("namespace out {\n"
4182                    "namespace mid {\n"
4183                    "namespace in {\n"
4184                    "int i;\n"
4185                    "} // namespace in\n"
4186                    "} // namespace mid\n"
4187                    "} // namespace out",
4188                    Style));
4189 
4190   Style.CompactNamespaces = true;
4191   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4192   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4193   Style.BraceWrapping.BeforeLambdaBody = true;
4194   verifyFormat("namespace out { namespace in {\n"
4195                "}} // namespace out::in",
4196                Style);
4197   EXPECT_EQ("namespace out { namespace in {\n"
4198             "}} // namespace out::in",
4199             format("namespace out {\n"
4200                    "namespace in {\n"
4201                    "} // namespace in\n"
4202                    "} // namespace out",
4203                    Style));
4204 }
4205 
4206 TEST_F(FormatTest, FormatsExternC) {
4207   verifyFormat("extern \"C\" {\nint a;");
4208   verifyFormat("extern \"C\" {}");
4209   verifyFormat("extern \"C\" {\n"
4210                "int foo();\n"
4211                "}");
4212   verifyFormat("extern \"C\" int foo() {}");
4213   verifyFormat("extern \"C\" int foo();");
4214   verifyFormat("extern \"C\" int foo() {\n"
4215                "  int i = 42;\n"
4216                "  return i;\n"
4217                "}");
4218 
4219   FormatStyle Style = getLLVMStyle();
4220   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4221   Style.BraceWrapping.AfterFunction = true;
4222   verifyFormat("extern \"C\" int foo() {}", Style);
4223   verifyFormat("extern \"C\" int foo();", Style);
4224   verifyFormat("extern \"C\" int foo()\n"
4225                "{\n"
4226                "  int i = 42;\n"
4227                "  return i;\n"
4228                "}",
4229                Style);
4230 
4231   Style.BraceWrapping.AfterExternBlock = true;
4232   Style.BraceWrapping.SplitEmptyRecord = false;
4233   verifyFormat("extern \"C\"\n"
4234                "{}",
4235                Style);
4236   verifyFormat("extern \"C\"\n"
4237                "{\n"
4238                "  int foo();\n"
4239                "}",
4240                Style);
4241 }
4242 
4243 TEST_F(FormatTest, IndentExternBlockStyle) {
4244   FormatStyle Style = getLLVMStyle();
4245   Style.IndentWidth = 2;
4246 
4247   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4248   verifyFormat("extern \"C\" { /*9*/\n"
4249                "}",
4250                Style);
4251   verifyFormat("extern \"C\" {\n"
4252                "  int foo10();\n"
4253                "}",
4254                Style);
4255 
4256   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4257   verifyFormat("extern \"C\" { /*11*/\n"
4258                "}",
4259                Style);
4260   verifyFormat("extern \"C\" {\n"
4261                "int foo12();\n"
4262                "}",
4263                Style);
4264 
4265   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4266   Style.BraceWrapping.AfterExternBlock = true;
4267   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4268   verifyFormat("extern \"C\"\n"
4269                "{ /*13*/\n"
4270                "}",
4271                Style);
4272   verifyFormat("extern \"C\"\n{\n"
4273                "  int foo14();\n"
4274                "}",
4275                Style);
4276 
4277   Style.BraceWrapping.AfterExternBlock = false;
4278   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4279   verifyFormat("extern \"C\" { /*15*/\n"
4280                "}",
4281                Style);
4282   verifyFormat("extern \"C\" {\n"
4283                "int foo16();\n"
4284                "}",
4285                Style);
4286 
4287   Style.BraceWrapping.AfterExternBlock = true;
4288   verifyFormat("extern \"C\"\n"
4289                "{ /*13*/\n"
4290                "}",
4291                Style);
4292   verifyFormat("extern \"C\"\n"
4293                "{\n"
4294                "int foo14();\n"
4295                "}",
4296                Style);
4297 
4298   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4299   verifyFormat("extern \"C\"\n"
4300                "{ /*13*/\n"
4301                "}",
4302                Style);
4303   verifyFormat("extern \"C\"\n"
4304                "{\n"
4305                "  int foo14();\n"
4306                "}",
4307                Style);
4308 }
4309 
4310 TEST_F(FormatTest, FormatsInlineASM) {
4311   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4312   verifyFormat("asm(\"nop\" ::: \"memory\");");
4313   verifyFormat(
4314       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4315       "    \"cpuid\\n\\t\"\n"
4316       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4317       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4318       "    : \"a\"(value));");
4319   EXPECT_EQ(
4320       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4321       "  __asm {\n"
4322       "        mov     edx,[that] // vtable in edx\n"
4323       "        mov     eax,methodIndex\n"
4324       "        call    [edx][eax*4] // stdcall\n"
4325       "  }\n"
4326       "}",
4327       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4328              "    __asm {\n"
4329              "        mov     edx,[that] // vtable in edx\n"
4330              "        mov     eax,methodIndex\n"
4331              "        call    [edx][eax*4] // stdcall\n"
4332              "    }\n"
4333              "}"));
4334   EXPECT_EQ("_asm {\n"
4335             "  xor eax, eax;\n"
4336             "  cpuid;\n"
4337             "}",
4338             format("_asm {\n"
4339                    "  xor eax, eax;\n"
4340                    "  cpuid;\n"
4341                    "}"));
4342   verifyFormat("void function() {\n"
4343                "  // comment\n"
4344                "  asm(\"\");\n"
4345                "}");
4346   EXPECT_EQ("__asm {\n"
4347             "}\n"
4348             "int i;",
4349             format("__asm   {\n"
4350                    "}\n"
4351                    "int   i;"));
4352 }
4353 
4354 TEST_F(FormatTest, FormatTryCatch) {
4355   verifyFormat("try {\n"
4356                "  throw a * b;\n"
4357                "} catch (int a) {\n"
4358                "  // Do nothing.\n"
4359                "} catch (...) {\n"
4360                "  exit(42);\n"
4361                "}");
4362 
4363   // Function-level try statements.
4364   verifyFormat("int f() try { return 4; } catch (...) {\n"
4365                "  return 5;\n"
4366                "}");
4367   verifyFormat("class A {\n"
4368                "  int a;\n"
4369                "  A() try : a(0) {\n"
4370                "  } catch (...) {\n"
4371                "    throw;\n"
4372                "  }\n"
4373                "};\n");
4374   verifyFormat("class A {\n"
4375                "  int a;\n"
4376                "  A() try : a(0), b{1} {\n"
4377                "  } catch (...) {\n"
4378                "    throw;\n"
4379                "  }\n"
4380                "};\n");
4381   verifyFormat("class A {\n"
4382                "  int a;\n"
4383                "  A() try : a(0), b{1}, c{2} {\n"
4384                "  } catch (...) {\n"
4385                "    throw;\n"
4386                "  }\n"
4387                "};\n");
4388   verifyFormat("class A {\n"
4389                "  int a;\n"
4390                "  A() try : a(0), b{1}, c{2} {\n"
4391                "    { // New scope.\n"
4392                "    }\n"
4393                "  } catch (...) {\n"
4394                "    throw;\n"
4395                "  }\n"
4396                "};\n");
4397 
4398   // Incomplete try-catch blocks.
4399   verifyIncompleteFormat("try {} catch (");
4400 }
4401 
4402 TEST_F(FormatTest, FormatTryAsAVariable) {
4403   verifyFormat("int try;");
4404   verifyFormat("int try, size;");
4405   verifyFormat("try = foo();");
4406   verifyFormat("if (try < size) {\n  return true;\n}");
4407 
4408   verifyFormat("int catch;");
4409   verifyFormat("int catch, size;");
4410   verifyFormat("catch = foo();");
4411   verifyFormat("if (catch < size) {\n  return true;\n}");
4412 
4413   FormatStyle Style = getLLVMStyle();
4414   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4415   Style.BraceWrapping.AfterFunction = true;
4416   Style.BraceWrapping.BeforeCatch = true;
4417   verifyFormat("try {\n"
4418                "  int bar = 1;\n"
4419                "}\n"
4420                "catch (...) {\n"
4421                "  int bar = 1;\n"
4422                "}",
4423                Style);
4424   verifyFormat("#if NO_EX\n"
4425                "try\n"
4426                "#endif\n"
4427                "{\n"
4428                "}\n"
4429                "#if NO_EX\n"
4430                "catch (...) {\n"
4431                "}",
4432                Style);
4433   verifyFormat("try /* abc */ {\n"
4434                "  int bar = 1;\n"
4435                "}\n"
4436                "catch (...) {\n"
4437                "  int bar = 1;\n"
4438                "}",
4439                Style);
4440   verifyFormat("try\n"
4441                "// abc\n"
4442                "{\n"
4443                "  int bar = 1;\n"
4444                "}\n"
4445                "catch (...) {\n"
4446                "  int bar = 1;\n"
4447                "}",
4448                Style);
4449 }
4450 
4451 TEST_F(FormatTest, FormatSEHTryCatch) {
4452   verifyFormat("__try {\n"
4453                "  int a = b * c;\n"
4454                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4455                "  // Do nothing.\n"
4456                "}");
4457 
4458   verifyFormat("__try {\n"
4459                "  int a = b * c;\n"
4460                "} __finally {\n"
4461                "  // Do nothing.\n"
4462                "}");
4463 
4464   verifyFormat("DEBUG({\n"
4465                "  __try {\n"
4466                "  } __finally {\n"
4467                "  }\n"
4468                "});\n");
4469 }
4470 
4471 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4472   verifyFormat("try {\n"
4473                "  f();\n"
4474                "} catch {\n"
4475                "  g();\n"
4476                "}");
4477   verifyFormat("try {\n"
4478                "  f();\n"
4479                "} catch (A a) MACRO(x) {\n"
4480                "  g();\n"
4481                "} catch (B b) MACRO(x) {\n"
4482                "  g();\n"
4483                "}");
4484 }
4485 
4486 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4487   FormatStyle Style = getLLVMStyle();
4488   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4489                           FormatStyle::BS_WebKit}) {
4490     Style.BreakBeforeBraces = BraceStyle;
4491     verifyFormat("try {\n"
4492                  "  // something\n"
4493                  "} catch (...) {\n"
4494                  "  // something\n"
4495                  "}",
4496                  Style);
4497   }
4498   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4499   verifyFormat("try {\n"
4500                "  // something\n"
4501                "}\n"
4502                "catch (...) {\n"
4503                "  // something\n"
4504                "}",
4505                Style);
4506   verifyFormat("__try {\n"
4507                "  // something\n"
4508                "}\n"
4509                "__finally {\n"
4510                "  // something\n"
4511                "}",
4512                Style);
4513   verifyFormat("@try {\n"
4514                "  // something\n"
4515                "}\n"
4516                "@finally {\n"
4517                "  // something\n"
4518                "}",
4519                Style);
4520   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4521   verifyFormat("try\n"
4522                "{\n"
4523                "  // something\n"
4524                "}\n"
4525                "catch (...)\n"
4526                "{\n"
4527                "  // something\n"
4528                "}",
4529                Style);
4530   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4531   verifyFormat("try\n"
4532                "  {\n"
4533                "  // something white\n"
4534                "  }\n"
4535                "catch (...)\n"
4536                "  {\n"
4537                "  // something white\n"
4538                "  }",
4539                Style);
4540   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4541   verifyFormat("try\n"
4542                "  {\n"
4543                "    // something\n"
4544                "  }\n"
4545                "catch (...)\n"
4546                "  {\n"
4547                "    // something\n"
4548                "  }",
4549                Style);
4550   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4551   Style.BraceWrapping.BeforeCatch = true;
4552   verifyFormat("try {\n"
4553                "  // something\n"
4554                "}\n"
4555                "catch (...) {\n"
4556                "  // something\n"
4557                "}",
4558                Style);
4559 }
4560 
4561 TEST_F(FormatTest, StaticInitializers) {
4562   verifyFormat("static SomeClass SC = {1, 'a'};");
4563 
4564   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4565                "    100000000, "
4566                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4567 
4568   // Here, everything other than the "}" would fit on a line.
4569   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4570                "    10000000000000000000000000};");
4571   EXPECT_EQ("S s = {a,\n"
4572             "\n"
4573             "       b};",
4574             format("S s = {\n"
4575                    "  a,\n"
4576                    "\n"
4577                    "  b\n"
4578                    "};"));
4579 
4580   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4581   // line. However, the formatting looks a bit off and this probably doesn't
4582   // happen often in practice.
4583   verifyFormat("static int Variable[1] = {\n"
4584                "    {1000000000000000000000000000000000000}};",
4585                getLLVMStyleWithColumns(40));
4586 }
4587 
4588 TEST_F(FormatTest, DesignatedInitializers) {
4589   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4590   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4591                "                    .bbbbbbbbbb = 2,\n"
4592                "                    .cccccccccc = 3,\n"
4593                "                    .dddddddddd = 4,\n"
4594                "                    .eeeeeeeeee = 5};");
4595   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4596                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4597                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4598                "    .ccccccccccccccccccccccccccc = 3,\n"
4599                "    .ddddddddddddddddddddddddddd = 4,\n"
4600                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4601 
4602   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4603 
4604   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4605   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4606                "                    [2] = bbbbbbbbbb,\n"
4607                "                    [3] = cccccccccc,\n"
4608                "                    [4] = dddddddddd,\n"
4609                "                    [5] = eeeeeeeeee};");
4610   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4611                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4612                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4613                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4614                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4615                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4616 }
4617 
4618 TEST_F(FormatTest, NestedStaticInitializers) {
4619   verifyFormat("static A x = {{{}}};\n");
4620   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4621                "               {init1, init2, init3, init4}}};",
4622                getLLVMStyleWithColumns(50));
4623 
4624   verifyFormat("somes Status::global_reps[3] = {\n"
4625                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4626                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4627                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4628                getLLVMStyleWithColumns(60));
4629   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4630                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4631                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4632                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4633   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4634                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4635                "rect.fTop}};");
4636 
4637   verifyFormat(
4638       "SomeArrayOfSomeType a = {\n"
4639       "    {{1, 2, 3},\n"
4640       "     {1, 2, 3},\n"
4641       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4642       "      333333333333333333333333333333},\n"
4643       "     {1, 2, 3},\n"
4644       "     {1, 2, 3}}};");
4645   verifyFormat(
4646       "SomeArrayOfSomeType a = {\n"
4647       "    {{1, 2, 3}},\n"
4648       "    {{1, 2, 3}},\n"
4649       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4650       "      333333333333333333333333333333}},\n"
4651       "    {{1, 2, 3}},\n"
4652       "    {{1, 2, 3}}};");
4653 
4654   verifyFormat("struct {\n"
4655                "  unsigned bit;\n"
4656                "  const char *const name;\n"
4657                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4658                "                 {kOsWin, \"Windows\"},\n"
4659                "                 {kOsLinux, \"Linux\"},\n"
4660                "                 {kOsCrOS, \"Chrome OS\"}};");
4661   verifyFormat("struct {\n"
4662                "  unsigned bit;\n"
4663                "  const char *const name;\n"
4664                "} kBitsToOs[] = {\n"
4665                "    {kOsMac, \"Mac\"},\n"
4666                "    {kOsWin, \"Windows\"},\n"
4667                "    {kOsLinux, \"Linux\"},\n"
4668                "    {kOsCrOS, \"Chrome OS\"},\n"
4669                "};");
4670 }
4671 
4672 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4673   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4674                "                      \\\n"
4675                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4676 }
4677 
4678 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4679   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4680                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4681 
4682   // Do break defaulted and deleted functions.
4683   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4684                "    default;",
4685                getLLVMStyleWithColumns(40));
4686   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4687                "    delete;",
4688                getLLVMStyleWithColumns(40));
4689 }
4690 
4691 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4692   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4693                getLLVMStyleWithColumns(40));
4694   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4695                getLLVMStyleWithColumns(40));
4696   EXPECT_EQ("#define Q                              \\\n"
4697             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4698             "  \"aaaaaaaa.cpp\"",
4699             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4700                    getLLVMStyleWithColumns(40)));
4701 }
4702 
4703 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4704   EXPECT_EQ("# 123 \"A string literal\"",
4705             format("   #     123    \"A string literal\""));
4706 }
4707 
4708 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4709   EXPECT_EQ("#;", format("#;"));
4710   verifyFormat("#\n;\n;\n;");
4711 }
4712 
4713 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4714   EXPECT_EQ("#line 42 \"test\"\n",
4715             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4716   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4717                                     getLLVMStyleWithColumns(12)));
4718 }
4719 
4720 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4721   EXPECT_EQ("#line 42 \"test\"",
4722             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4723   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4724 }
4725 
4726 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4727   verifyFormat("#define A \\x20");
4728   verifyFormat("#define A \\ x20");
4729   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4730   verifyFormat("#define A ''");
4731   verifyFormat("#define A ''qqq");
4732   verifyFormat("#define A `qqq");
4733   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4734   EXPECT_EQ("const char *c = STRINGIFY(\n"
4735             "\\na : b);",
4736             format("const char * c = STRINGIFY(\n"
4737                    "\\na : b);"));
4738 
4739   verifyFormat("a\r\\");
4740   verifyFormat("a\v\\");
4741   verifyFormat("a\f\\");
4742 }
4743 
4744 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4745   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4746   style.IndentWidth = 4;
4747   style.PPIndentWidth = 1;
4748 
4749   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4750   verifyFormat("#ifdef __linux__\n"
4751                "void foo() {\n"
4752                "    int x = 0;\n"
4753                "}\n"
4754                "#define FOO\n"
4755                "#endif\n"
4756                "void bar() {\n"
4757                "    int y = 0;\n"
4758                "}\n",
4759                style);
4760 
4761   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4762   verifyFormat("#ifdef __linux__\n"
4763                "void foo() {\n"
4764                "    int x = 0;\n"
4765                "}\n"
4766                "# define FOO foo\n"
4767                "#endif\n"
4768                "void bar() {\n"
4769                "    int y = 0;\n"
4770                "}\n",
4771                style);
4772 
4773   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4774   verifyFormat("#ifdef __linux__\n"
4775                "void foo() {\n"
4776                "    int x = 0;\n"
4777                "}\n"
4778                " #define FOO foo\n"
4779                "#endif\n"
4780                "void bar() {\n"
4781                "    int y = 0;\n"
4782                "}\n",
4783                style);
4784 }
4785 
4786 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4787   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4788   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4789   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4790   // FIXME: We never break before the macro name.
4791   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4792 
4793   verifyFormat("#define A A\n#define A A");
4794   verifyFormat("#define A(X) A\n#define A A");
4795 
4796   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4797   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4798 }
4799 
4800 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4801   EXPECT_EQ("// somecomment\n"
4802             "#include \"a.h\"\n"
4803             "#define A(  \\\n"
4804             "    A, B)\n"
4805             "#include \"b.h\"\n"
4806             "// somecomment\n",
4807             format("  // somecomment\n"
4808                    "  #include \"a.h\"\n"
4809                    "#define A(A,\\\n"
4810                    "    B)\n"
4811                    "    #include \"b.h\"\n"
4812                    " // somecomment\n",
4813                    getLLVMStyleWithColumns(13)));
4814 }
4815 
4816 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4817 
4818 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4819   EXPECT_EQ("#define A    \\\n"
4820             "  c;         \\\n"
4821             "  e;\n"
4822             "f;",
4823             format("#define A c; e;\n"
4824                    "f;",
4825                    getLLVMStyleWithColumns(14)));
4826 }
4827 
4828 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4829 
4830 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4831   EXPECT_EQ("int x,\n"
4832             "#define A\n"
4833             "    y;",
4834             format("int x,\n#define A\ny;"));
4835 }
4836 
4837 TEST_F(FormatTest, HashInMacroDefinition) {
4838   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4839   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4840   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4841   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4842   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4843   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4844   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4845   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4846   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4847   verifyFormat("#define A  \\\n"
4848                "  {        \\\n"
4849                "    f(#c); \\\n"
4850                "  }",
4851                getLLVMStyleWithColumns(11));
4852 
4853   verifyFormat("#define A(X)         \\\n"
4854                "  void function##X()",
4855                getLLVMStyleWithColumns(22));
4856 
4857   verifyFormat("#define A(a, b, c)   \\\n"
4858                "  void a##b##c()",
4859                getLLVMStyleWithColumns(22));
4860 
4861   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4862 }
4863 
4864 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4865   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4866   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4867 
4868   FormatStyle Style = getLLVMStyle();
4869   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4870   verifyFormat("#define true ((foo)1)", Style);
4871   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4872   verifyFormat("#define false((foo)0)", Style);
4873 }
4874 
4875 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4876   EXPECT_EQ("#define A b;", format("#define A \\\n"
4877                                    "          \\\n"
4878                                    "  b;",
4879                                    getLLVMStyleWithColumns(25)));
4880   EXPECT_EQ("#define A \\\n"
4881             "          \\\n"
4882             "  a;      \\\n"
4883             "  b;",
4884             format("#define A \\\n"
4885                    "          \\\n"
4886                    "  a;      \\\n"
4887                    "  b;",
4888                    getLLVMStyleWithColumns(11)));
4889   EXPECT_EQ("#define A \\\n"
4890             "  a;      \\\n"
4891             "          \\\n"
4892             "  b;",
4893             format("#define A \\\n"
4894                    "  a;      \\\n"
4895                    "          \\\n"
4896                    "  b;",
4897                    getLLVMStyleWithColumns(11)));
4898 }
4899 
4900 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
4901   verifyIncompleteFormat("#define A :");
4902   verifyFormat("#define SOMECASES  \\\n"
4903                "  case 1:          \\\n"
4904                "  case 2\n",
4905                getLLVMStyleWithColumns(20));
4906   verifyFormat("#define MACRO(a) \\\n"
4907                "  if (a)         \\\n"
4908                "    f();         \\\n"
4909                "  else           \\\n"
4910                "    g()",
4911                getLLVMStyleWithColumns(18));
4912   verifyFormat("#define A template <typename T>");
4913   verifyIncompleteFormat("#define STR(x) #x\n"
4914                          "f(STR(this_is_a_string_literal{));");
4915   verifyFormat("#pragma omp threadprivate( \\\n"
4916                "    y)), // expected-warning",
4917                getLLVMStyleWithColumns(28));
4918   verifyFormat("#d, = };");
4919   verifyFormat("#if \"a");
4920   verifyIncompleteFormat("({\n"
4921                          "#define b     \\\n"
4922                          "  }           \\\n"
4923                          "  a\n"
4924                          "a",
4925                          getLLVMStyleWithColumns(15));
4926   verifyFormat("#define A     \\\n"
4927                "  {           \\\n"
4928                "    {\n"
4929                "#define B     \\\n"
4930                "  }           \\\n"
4931                "  }",
4932                getLLVMStyleWithColumns(15));
4933   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
4934   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
4935   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
4936   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
4937 }
4938 
4939 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
4940   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
4941   EXPECT_EQ("class A : public QObject {\n"
4942             "  Q_OBJECT\n"
4943             "\n"
4944             "  A() {}\n"
4945             "};",
4946             format("class A  :  public QObject {\n"
4947                    "     Q_OBJECT\n"
4948                    "\n"
4949                    "  A() {\n}\n"
4950                    "}  ;"));
4951   EXPECT_EQ("MACRO\n"
4952             "/*static*/ int i;",
4953             format("MACRO\n"
4954                    " /*static*/ int   i;"));
4955   EXPECT_EQ("SOME_MACRO\n"
4956             "namespace {\n"
4957             "void f();\n"
4958             "} // namespace",
4959             format("SOME_MACRO\n"
4960                    "  namespace    {\n"
4961                    "void   f(  );\n"
4962                    "} // namespace"));
4963   // Only if the identifier contains at least 5 characters.
4964   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
4965   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
4966   // Only if everything is upper case.
4967   EXPECT_EQ("class A : public QObject {\n"
4968             "  Q_Object A() {}\n"
4969             "};",
4970             format("class A  :  public QObject {\n"
4971                    "     Q_Object\n"
4972                    "  A() {\n}\n"
4973                    "}  ;"));
4974 
4975   // Only if the next line can actually start an unwrapped line.
4976   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
4977             format("SOME_WEIRD_LOG_MACRO\n"
4978                    "<< SomeThing;"));
4979 
4980   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
4981                "(n, buffers))\n",
4982                getChromiumStyle(FormatStyle::LK_Cpp));
4983 
4984   // See PR41483
4985   EXPECT_EQ("/**/ FOO(a)\n"
4986             "FOO(b)",
4987             format("/**/ FOO(a)\n"
4988                    "FOO(b)"));
4989 }
4990 
4991 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
4992   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4993             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4994             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4995             "class X {};\n"
4996             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4997             "int *createScopDetectionPass() { return 0; }",
4998             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4999                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5000                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5001                    "  class X {};\n"
5002                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5003                    "  int *createScopDetectionPass() { return 0; }"));
5004   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
5005   // braces, so that inner block is indented one level more.
5006   EXPECT_EQ("int q() {\n"
5007             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5008             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5009             "  IPC_END_MESSAGE_MAP()\n"
5010             "}",
5011             format("int q() {\n"
5012                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5013                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5014                    "  IPC_END_MESSAGE_MAP()\n"
5015                    "}"));
5016 
5017   // Same inside macros.
5018   EXPECT_EQ("#define LIST(L) \\\n"
5019             "  L(A)          \\\n"
5020             "  L(B)          \\\n"
5021             "  L(C)",
5022             format("#define LIST(L) \\\n"
5023                    "  L(A) \\\n"
5024                    "  L(B) \\\n"
5025                    "  L(C)",
5026                    getGoogleStyle()));
5027 
5028   // These must not be recognized as macros.
5029   EXPECT_EQ("int q() {\n"
5030             "  f(x);\n"
5031             "  f(x) {}\n"
5032             "  f(x)->g();\n"
5033             "  f(x)->*g();\n"
5034             "  f(x).g();\n"
5035             "  f(x) = x;\n"
5036             "  f(x) += x;\n"
5037             "  f(x) -= x;\n"
5038             "  f(x) *= x;\n"
5039             "  f(x) /= x;\n"
5040             "  f(x) %= x;\n"
5041             "  f(x) &= x;\n"
5042             "  f(x) |= x;\n"
5043             "  f(x) ^= x;\n"
5044             "  f(x) >>= x;\n"
5045             "  f(x) <<= x;\n"
5046             "  f(x)[y].z();\n"
5047             "  LOG(INFO) << x;\n"
5048             "  ifstream(x) >> x;\n"
5049             "}\n",
5050             format("int q() {\n"
5051                    "  f(x)\n;\n"
5052                    "  f(x)\n {}\n"
5053                    "  f(x)\n->g();\n"
5054                    "  f(x)\n->*g();\n"
5055                    "  f(x)\n.g();\n"
5056                    "  f(x)\n = x;\n"
5057                    "  f(x)\n += x;\n"
5058                    "  f(x)\n -= x;\n"
5059                    "  f(x)\n *= x;\n"
5060                    "  f(x)\n /= x;\n"
5061                    "  f(x)\n %= x;\n"
5062                    "  f(x)\n &= x;\n"
5063                    "  f(x)\n |= x;\n"
5064                    "  f(x)\n ^= x;\n"
5065                    "  f(x)\n >>= x;\n"
5066                    "  f(x)\n <<= x;\n"
5067                    "  f(x)\n[y].z();\n"
5068                    "  LOG(INFO)\n << x;\n"
5069                    "  ifstream(x)\n >> x;\n"
5070                    "}\n"));
5071   EXPECT_EQ("int q() {\n"
5072             "  F(x)\n"
5073             "  if (1) {\n"
5074             "  }\n"
5075             "  F(x)\n"
5076             "  while (1) {\n"
5077             "  }\n"
5078             "  F(x)\n"
5079             "  G(x);\n"
5080             "  F(x)\n"
5081             "  try {\n"
5082             "    Q();\n"
5083             "  } catch (...) {\n"
5084             "  }\n"
5085             "}\n",
5086             format("int q() {\n"
5087                    "F(x)\n"
5088                    "if (1) {}\n"
5089                    "F(x)\n"
5090                    "while (1) {}\n"
5091                    "F(x)\n"
5092                    "G(x);\n"
5093                    "F(x)\n"
5094                    "try { Q(); } catch (...) {}\n"
5095                    "}\n"));
5096   EXPECT_EQ("class A {\n"
5097             "  A() : t(0) {}\n"
5098             "  A(int i) noexcept() : {}\n"
5099             "  A(X x)\n" // FIXME: function-level try blocks are broken.
5100             "  try : t(0) {\n"
5101             "  } catch (...) {\n"
5102             "  }\n"
5103             "};",
5104             format("class A {\n"
5105                    "  A()\n : t(0) {}\n"
5106                    "  A(int i)\n noexcept() : {}\n"
5107                    "  A(X x)\n"
5108                    "  try : t(0) {} catch (...) {}\n"
5109                    "};"));
5110   FormatStyle Style = getLLVMStyle();
5111   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5112   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5113   Style.BraceWrapping.AfterFunction = true;
5114   EXPECT_EQ("void f()\n"
5115             "try\n"
5116             "{\n"
5117             "}",
5118             format("void f() try {\n"
5119                    "}",
5120                    Style));
5121   EXPECT_EQ("class SomeClass {\n"
5122             "public:\n"
5123             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5124             "};",
5125             format("class SomeClass {\n"
5126                    "public:\n"
5127                    "  SomeClass()\n"
5128                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5129                    "};"));
5130   EXPECT_EQ("class SomeClass {\n"
5131             "public:\n"
5132             "  SomeClass()\n"
5133             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5134             "};",
5135             format("class SomeClass {\n"
5136                    "public:\n"
5137                    "  SomeClass()\n"
5138                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5139                    "};",
5140                    getLLVMStyleWithColumns(40)));
5141 
5142   verifyFormat("MACRO(>)");
5143 
5144   // Some macros contain an implicit semicolon.
5145   Style = getLLVMStyle();
5146   Style.StatementMacros.push_back("FOO");
5147   verifyFormat("FOO(a) int b = 0;");
5148   verifyFormat("FOO(a)\n"
5149                "int b = 0;",
5150                Style);
5151   verifyFormat("FOO(a);\n"
5152                "int b = 0;",
5153                Style);
5154   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
5155                "int b = 0;",
5156                Style);
5157   verifyFormat("FOO()\n"
5158                "int b = 0;",
5159                Style);
5160   verifyFormat("FOO\n"
5161                "int b = 0;",
5162                Style);
5163   verifyFormat("void f() {\n"
5164                "  FOO(a)\n"
5165                "  return a;\n"
5166                "}",
5167                Style);
5168   verifyFormat("FOO(a)\n"
5169                "FOO(b)",
5170                Style);
5171   verifyFormat("int a = 0;\n"
5172                "FOO(b)\n"
5173                "int c = 0;",
5174                Style);
5175   verifyFormat("int a = 0;\n"
5176                "int x = FOO(a)\n"
5177                "int b = 0;",
5178                Style);
5179   verifyFormat("void foo(int a) { FOO(a) }\n"
5180                "uint32_t bar() {}",
5181                Style);
5182 }
5183 
5184 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
5185   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
5186 
5187   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
5188                ZeroColumn);
5189 }
5190 
5191 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5192   verifyFormat("#define A \\\n"
5193                "  f({     \\\n"
5194                "    g();  \\\n"
5195                "  });",
5196                getLLVMStyleWithColumns(11));
5197 }
5198 
5199 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5200   FormatStyle Style = getLLVMStyleWithColumns(40);
5201   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5202   verifyFormat("#ifdef _WIN32\n"
5203                "#define A 0\n"
5204                "#ifdef VAR2\n"
5205                "#define B 1\n"
5206                "#include <someheader.h>\n"
5207                "#define MACRO                          \\\n"
5208                "  some_very_long_func_aaaaaaaaaa();\n"
5209                "#endif\n"
5210                "#else\n"
5211                "#define A 1\n"
5212                "#endif",
5213                Style);
5214   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5215   verifyFormat("#ifdef _WIN32\n"
5216                "#  define A 0\n"
5217                "#  ifdef VAR2\n"
5218                "#    define B 1\n"
5219                "#    include <someheader.h>\n"
5220                "#    define MACRO                      \\\n"
5221                "      some_very_long_func_aaaaaaaaaa();\n"
5222                "#  endif\n"
5223                "#else\n"
5224                "#  define A 1\n"
5225                "#endif",
5226                Style);
5227   verifyFormat("#if A\n"
5228                "#  define MACRO                        \\\n"
5229                "    void a(int x) {                    \\\n"
5230                "      b();                             \\\n"
5231                "      c();                             \\\n"
5232                "      d();                             \\\n"
5233                "      e();                             \\\n"
5234                "      f();                             \\\n"
5235                "    }\n"
5236                "#endif",
5237                Style);
5238   // Comments before include guard.
5239   verifyFormat("// file comment\n"
5240                "// file comment\n"
5241                "#ifndef HEADER_H\n"
5242                "#define HEADER_H\n"
5243                "code();\n"
5244                "#endif",
5245                Style);
5246   // Test with include guards.
5247   verifyFormat("#ifndef HEADER_H\n"
5248                "#define HEADER_H\n"
5249                "code();\n"
5250                "#endif",
5251                Style);
5252   // Include guards must have a #define with the same variable immediately
5253   // after #ifndef.
5254   verifyFormat("#ifndef NOT_GUARD\n"
5255                "#  define FOO\n"
5256                "code();\n"
5257                "#endif",
5258                Style);
5259 
5260   // Include guards must cover the entire file.
5261   verifyFormat("code();\n"
5262                "code();\n"
5263                "#ifndef NOT_GUARD\n"
5264                "#  define NOT_GUARD\n"
5265                "code();\n"
5266                "#endif",
5267                Style);
5268   verifyFormat("#ifndef NOT_GUARD\n"
5269                "#  define NOT_GUARD\n"
5270                "code();\n"
5271                "#endif\n"
5272                "code();",
5273                Style);
5274   // Test with trailing blank lines.
5275   verifyFormat("#ifndef HEADER_H\n"
5276                "#define HEADER_H\n"
5277                "code();\n"
5278                "#endif\n",
5279                Style);
5280   // Include guards don't have #else.
5281   verifyFormat("#ifndef NOT_GUARD\n"
5282                "#  define NOT_GUARD\n"
5283                "code();\n"
5284                "#else\n"
5285                "#endif",
5286                Style);
5287   verifyFormat("#ifndef NOT_GUARD\n"
5288                "#  define NOT_GUARD\n"
5289                "code();\n"
5290                "#elif FOO\n"
5291                "#endif",
5292                Style);
5293   // Non-identifier #define after potential include guard.
5294   verifyFormat("#ifndef FOO\n"
5295                "#  define 1\n"
5296                "#endif\n",
5297                Style);
5298   // #if closes past last non-preprocessor line.
5299   verifyFormat("#ifndef FOO\n"
5300                "#define FOO\n"
5301                "#if 1\n"
5302                "int i;\n"
5303                "#  define A 0\n"
5304                "#endif\n"
5305                "#endif\n",
5306                Style);
5307   // Don't crash if there is an #elif directive without a condition.
5308   verifyFormat("#if 1\n"
5309                "int x;\n"
5310                "#elif\n"
5311                "int y;\n"
5312                "#else\n"
5313                "int z;\n"
5314                "#endif",
5315                Style);
5316   // FIXME: This doesn't handle the case where there's code between the
5317   // #ifndef and #define but all other conditions hold. This is because when
5318   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5319   // previous code line yet, so we can't detect it.
5320   EXPECT_EQ("#ifndef NOT_GUARD\n"
5321             "code();\n"
5322             "#define NOT_GUARD\n"
5323             "code();\n"
5324             "#endif",
5325             format("#ifndef NOT_GUARD\n"
5326                    "code();\n"
5327                    "#  define NOT_GUARD\n"
5328                    "code();\n"
5329                    "#endif",
5330                    Style));
5331   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5332   // be outside an include guard. Examples are #pragma once and
5333   // #pragma GCC diagnostic, or anything else that does not change the meaning
5334   // of the file if it's included multiple times.
5335   EXPECT_EQ("#ifdef WIN32\n"
5336             "#  pragma once\n"
5337             "#endif\n"
5338             "#ifndef HEADER_H\n"
5339             "#  define HEADER_H\n"
5340             "code();\n"
5341             "#endif",
5342             format("#ifdef WIN32\n"
5343                    "#  pragma once\n"
5344                    "#endif\n"
5345                    "#ifndef HEADER_H\n"
5346                    "#define HEADER_H\n"
5347                    "code();\n"
5348                    "#endif",
5349                    Style));
5350   // FIXME: This does not detect when there is a single non-preprocessor line
5351   // in front of an include-guard-like structure where other conditions hold
5352   // because ScopedLineState hides the line.
5353   EXPECT_EQ("code();\n"
5354             "#ifndef HEADER_H\n"
5355             "#define HEADER_H\n"
5356             "code();\n"
5357             "#endif",
5358             format("code();\n"
5359                    "#ifndef HEADER_H\n"
5360                    "#  define HEADER_H\n"
5361                    "code();\n"
5362                    "#endif",
5363                    Style));
5364   // Keep comments aligned with #, otherwise indent comments normally. These
5365   // tests cannot use verifyFormat because messUp manipulates leading
5366   // whitespace.
5367   {
5368     const char *Expected = ""
5369                            "void f() {\n"
5370                            "#if 1\n"
5371                            "// Preprocessor aligned.\n"
5372                            "#  define A 0\n"
5373                            "  // Code. Separated by blank line.\n"
5374                            "\n"
5375                            "#  define B 0\n"
5376                            "  // Code. Not aligned with #\n"
5377                            "#  define C 0\n"
5378                            "#endif";
5379     const char *ToFormat = ""
5380                            "void f() {\n"
5381                            "#if 1\n"
5382                            "// Preprocessor aligned.\n"
5383                            "#  define A 0\n"
5384                            "// Code. Separated by blank line.\n"
5385                            "\n"
5386                            "#  define B 0\n"
5387                            "   // Code. Not aligned with #\n"
5388                            "#  define C 0\n"
5389                            "#endif";
5390     EXPECT_EQ(Expected, format(ToFormat, Style));
5391     EXPECT_EQ(Expected, format(Expected, Style));
5392   }
5393   // Keep block quotes aligned.
5394   {
5395     const char *Expected = ""
5396                            "void f() {\n"
5397                            "#if 1\n"
5398                            "/* Preprocessor aligned. */\n"
5399                            "#  define A 0\n"
5400                            "  /* Code. Separated by blank line. */\n"
5401                            "\n"
5402                            "#  define B 0\n"
5403                            "  /* Code. Not aligned with # */\n"
5404                            "#  define C 0\n"
5405                            "#endif";
5406     const char *ToFormat = ""
5407                            "void f() {\n"
5408                            "#if 1\n"
5409                            "/* Preprocessor aligned. */\n"
5410                            "#  define A 0\n"
5411                            "/* Code. Separated by blank line. */\n"
5412                            "\n"
5413                            "#  define B 0\n"
5414                            "   /* Code. Not aligned with # */\n"
5415                            "#  define C 0\n"
5416                            "#endif";
5417     EXPECT_EQ(Expected, format(ToFormat, Style));
5418     EXPECT_EQ(Expected, format(Expected, Style));
5419   }
5420   // Keep comments aligned with un-indented directives.
5421   {
5422     const char *Expected = ""
5423                            "void f() {\n"
5424                            "// Preprocessor aligned.\n"
5425                            "#define A 0\n"
5426                            "  // Code. Separated by blank line.\n"
5427                            "\n"
5428                            "#define B 0\n"
5429                            "  // Code. Not aligned with #\n"
5430                            "#define C 0\n";
5431     const char *ToFormat = ""
5432                            "void f() {\n"
5433                            "// Preprocessor aligned.\n"
5434                            "#define A 0\n"
5435                            "// Code. Separated by blank line.\n"
5436                            "\n"
5437                            "#define B 0\n"
5438                            "   // Code. Not aligned with #\n"
5439                            "#define C 0\n";
5440     EXPECT_EQ(Expected, format(ToFormat, Style));
5441     EXPECT_EQ(Expected, format(Expected, Style));
5442   }
5443   // Test AfterHash with tabs.
5444   {
5445     FormatStyle Tabbed = Style;
5446     Tabbed.UseTab = FormatStyle::UT_Always;
5447     Tabbed.IndentWidth = 8;
5448     Tabbed.TabWidth = 8;
5449     verifyFormat("#ifdef _WIN32\n"
5450                  "#\tdefine A 0\n"
5451                  "#\tifdef VAR2\n"
5452                  "#\t\tdefine B 1\n"
5453                  "#\t\tinclude <someheader.h>\n"
5454                  "#\t\tdefine MACRO          \\\n"
5455                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5456                  "#\tendif\n"
5457                  "#else\n"
5458                  "#\tdefine A 1\n"
5459                  "#endif",
5460                  Tabbed);
5461   }
5462 
5463   // Regression test: Multiline-macro inside include guards.
5464   verifyFormat("#ifndef HEADER_H\n"
5465                "#define HEADER_H\n"
5466                "#define A()        \\\n"
5467                "  int i;           \\\n"
5468                "  int j;\n"
5469                "#endif // HEADER_H",
5470                getLLVMStyleWithColumns(20));
5471 
5472   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5473   // Basic before hash indent tests
5474   verifyFormat("#ifdef _WIN32\n"
5475                "  #define A 0\n"
5476                "  #ifdef VAR2\n"
5477                "    #define B 1\n"
5478                "    #include <someheader.h>\n"
5479                "    #define MACRO                      \\\n"
5480                "      some_very_long_func_aaaaaaaaaa();\n"
5481                "  #endif\n"
5482                "#else\n"
5483                "  #define A 1\n"
5484                "#endif",
5485                Style);
5486   verifyFormat("#if A\n"
5487                "  #define MACRO                        \\\n"
5488                "    void a(int x) {                    \\\n"
5489                "      b();                             \\\n"
5490                "      c();                             \\\n"
5491                "      d();                             \\\n"
5492                "      e();                             \\\n"
5493                "      f();                             \\\n"
5494                "    }\n"
5495                "#endif",
5496                Style);
5497   // Keep comments aligned with indented directives. These
5498   // tests cannot use verifyFormat because messUp manipulates leading
5499   // whitespace.
5500   {
5501     const char *Expected = "void f() {\n"
5502                            "// Aligned to preprocessor.\n"
5503                            "#if 1\n"
5504                            "  // Aligned to code.\n"
5505                            "  int a;\n"
5506                            "  #if 1\n"
5507                            "    // Aligned to preprocessor.\n"
5508                            "    #define A 0\n"
5509                            "  // Aligned to code.\n"
5510                            "  int b;\n"
5511                            "  #endif\n"
5512                            "#endif\n"
5513                            "}";
5514     const char *ToFormat = "void f() {\n"
5515                            "// Aligned to preprocessor.\n"
5516                            "#if 1\n"
5517                            "// Aligned to code.\n"
5518                            "int a;\n"
5519                            "#if 1\n"
5520                            "// Aligned to preprocessor.\n"
5521                            "#define A 0\n"
5522                            "// Aligned to code.\n"
5523                            "int b;\n"
5524                            "#endif\n"
5525                            "#endif\n"
5526                            "}";
5527     EXPECT_EQ(Expected, format(ToFormat, Style));
5528     EXPECT_EQ(Expected, format(Expected, Style));
5529   }
5530   {
5531     const char *Expected = "void f() {\n"
5532                            "/* Aligned to preprocessor. */\n"
5533                            "#if 1\n"
5534                            "  /* Aligned to code. */\n"
5535                            "  int a;\n"
5536                            "  #if 1\n"
5537                            "    /* Aligned to preprocessor. */\n"
5538                            "    #define A 0\n"
5539                            "  /* Aligned to code. */\n"
5540                            "  int b;\n"
5541                            "  #endif\n"
5542                            "#endif\n"
5543                            "}";
5544     const char *ToFormat = "void f() {\n"
5545                            "/* Aligned to preprocessor. */\n"
5546                            "#if 1\n"
5547                            "/* Aligned to code. */\n"
5548                            "int a;\n"
5549                            "#if 1\n"
5550                            "/* Aligned to preprocessor. */\n"
5551                            "#define A 0\n"
5552                            "/* Aligned to code. */\n"
5553                            "int b;\n"
5554                            "#endif\n"
5555                            "#endif\n"
5556                            "}";
5557     EXPECT_EQ(Expected, format(ToFormat, Style));
5558     EXPECT_EQ(Expected, format(Expected, Style));
5559   }
5560 
5561   // Test single comment before preprocessor
5562   verifyFormat("// Comment\n"
5563                "\n"
5564                "#if 1\n"
5565                "#endif",
5566                Style);
5567 }
5568 
5569 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5570   verifyFormat("{\n  { a #c; }\n}");
5571 }
5572 
5573 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5574   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5575             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5576   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5577             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5578 }
5579 
5580 TEST_F(FormatTest, EscapedNewlines) {
5581   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5582   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5583             format("#define A \\\nint i;\\\n  int j;", Narrow));
5584   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5585   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5586   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5587   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5588 
5589   FormatStyle AlignLeft = getLLVMStyle();
5590   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5591   EXPECT_EQ("#define MACRO(x) \\\n"
5592             "private:         \\\n"
5593             "  int x(int a);\n",
5594             format("#define MACRO(x) \\\n"
5595                    "private:         \\\n"
5596                    "  int x(int a);\n",
5597                    AlignLeft));
5598 
5599   // CRLF line endings
5600   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5601             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5602   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5603   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5604   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5605   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5606   EXPECT_EQ("#define MACRO(x) \\\r\n"
5607             "private:         \\\r\n"
5608             "  int x(int a);\r\n",
5609             format("#define MACRO(x) \\\r\n"
5610                    "private:         \\\r\n"
5611                    "  int x(int a);\r\n",
5612                    AlignLeft));
5613 
5614   FormatStyle DontAlign = getLLVMStyle();
5615   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5616   DontAlign.MaxEmptyLinesToKeep = 3;
5617   // FIXME: can't use verifyFormat here because the newline before
5618   // "public:" is not inserted the first time it's reformatted
5619   EXPECT_EQ("#define A \\\n"
5620             "  class Foo { \\\n"
5621             "    void bar(); \\\n"
5622             "\\\n"
5623             "\\\n"
5624             "\\\n"
5625             "  public: \\\n"
5626             "    void baz(); \\\n"
5627             "  };",
5628             format("#define A \\\n"
5629                    "  class Foo { \\\n"
5630                    "    void bar(); \\\n"
5631                    "\\\n"
5632                    "\\\n"
5633                    "\\\n"
5634                    "  public: \\\n"
5635                    "    void baz(); \\\n"
5636                    "  };",
5637                    DontAlign));
5638 }
5639 
5640 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5641   verifyFormat("#define A \\\n"
5642                "  int v(  \\\n"
5643                "      a); \\\n"
5644                "  int i;",
5645                getLLVMStyleWithColumns(11));
5646 }
5647 
5648 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5649   EXPECT_EQ(
5650       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5651       "                      \\\n"
5652       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5653       "\n"
5654       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5655       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5656       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5657              "\\\n"
5658              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5659              "  \n"
5660              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5661              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5662 }
5663 
5664 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5665   EXPECT_EQ("int\n"
5666             "#define A\n"
5667             "    a;",
5668             format("int\n#define A\na;"));
5669   verifyFormat("functionCallTo(\n"
5670                "    someOtherFunction(\n"
5671                "        withSomeParameters, whichInSequence,\n"
5672                "        areLongerThanALine(andAnotherCall,\n"
5673                "#define A B\n"
5674                "                           withMoreParamters,\n"
5675                "                           whichStronglyInfluenceTheLayout),\n"
5676                "        andMoreParameters),\n"
5677                "    trailing);",
5678                getLLVMStyleWithColumns(69));
5679   verifyFormat("Foo::Foo()\n"
5680                "#ifdef BAR\n"
5681                "    : baz(0)\n"
5682                "#endif\n"
5683                "{\n"
5684                "}");
5685   verifyFormat("void f() {\n"
5686                "  if (true)\n"
5687                "#ifdef A\n"
5688                "    f(42);\n"
5689                "  x();\n"
5690                "#else\n"
5691                "    g();\n"
5692                "  x();\n"
5693                "#endif\n"
5694                "}");
5695   verifyFormat("void f(param1, param2,\n"
5696                "       param3,\n"
5697                "#ifdef A\n"
5698                "       param4(param5,\n"
5699                "#ifdef A1\n"
5700                "              param6,\n"
5701                "#ifdef A2\n"
5702                "              param7),\n"
5703                "#else\n"
5704                "              param8),\n"
5705                "       param9,\n"
5706                "#endif\n"
5707                "       param10,\n"
5708                "#endif\n"
5709                "       param11)\n"
5710                "#else\n"
5711                "       param12)\n"
5712                "#endif\n"
5713                "{\n"
5714                "  x();\n"
5715                "}",
5716                getLLVMStyleWithColumns(28));
5717   verifyFormat("#if 1\n"
5718                "int i;");
5719   verifyFormat("#if 1\n"
5720                "#endif\n"
5721                "#if 1\n"
5722                "#else\n"
5723                "#endif\n");
5724   verifyFormat("DEBUG({\n"
5725                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5726                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5727                "});\n"
5728                "#if a\n"
5729                "#else\n"
5730                "#endif");
5731 
5732   verifyIncompleteFormat("void f(\n"
5733                          "#if A\n"
5734                          ");\n"
5735                          "#else\n"
5736                          "#endif");
5737 }
5738 
5739 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5740   verifyFormat("#endif\n"
5741                "#if B");
5742 }
5743 
5744 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5745   FormatStyle SingleLine = getLLVMStyle();
5746   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5747   verifyFormat("#if 0\n"
5748                "#elif 1\n"
5749                "#endif\n"
5750                "void foo() {\n"
5751                "  if (test) foo2();\n"
5752                "}",
5753                SingleLine);
5754 }
5755 
5756 TEST_F(FormatTest, LayoutBlockInsideParens) {
5757   verifyFormat("functionCall({ int i; });");
5758   verifyFormat("functionCall({\n"
5759                "  int i;\n"
5760                "  int j;\n"
5761                "});");
5762   verifyFormat("functionCall(\n"
5763                "    {\n"
5764                "      int i;\n"
5765                "      int j;\n"
5766                "    },\n"
5767                "    aaaa, bbbb, cccc);");
5768   verifyFormat("functionA(functionB({\n"
5769                "            int i;\n"
5770                "            int j;\n"
5771                "          }),\n"
5772                "          aaaa, bbbb, cccc);");
5773   verifyFormat("functionCall(\n"
5774                "    {\n"
5775                "      int i;\n"
5776                "      int j;\n"
5777                "    },\n"
5778                "    aaaa, bbbb, // comment\n"
5779                "    cccc);");
5780   verifyFormat("functionA(functionB({\n"
5781                "            int i;\n"
5782                "            int j;\n"
5783                "          }),\n"
5784                "          aaaa, bbbb, // comment\n"
5785                "          cccc);");
5786   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5787   verifyFormat("functionCall(aaaa, bbbb, {\n"
5788                "  int i;\n"
5789                "  int j;\n"
5790                "});");
5791   verifyFormat(
5792       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5793       "    {\n"
5794       "      int i; // break\n"
5795       "    },\n"
5796       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5797       "                                     ccccccccccccccccc));");
5798   verifyFormat("DEBUG({\n"
5799                "  if (a)\n"
5800                "    f();\n"
5801                "});");
5802 }
5803 
5804 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5805   EXPECT_EQ("SOME_MACRO { int i; }\n"
5806             "int i;",
5807             format("  SOME_MACRO  {int i;}  int i;"));
5808 }
5809 
5810 TEST_F(FormatTest, LayoutNestedBlocks) {
5811   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5812                "  struct s {\n"
5813                "    int i;\n"
5814                "  };\n"
5815                "  s kBitsToOs[] = {{10}};\n"
5816                "  for (int i = 0; i < 10; ++i)\n"
5817                "    return;\n"
5818                "}");
5819   verifyFormat("call(parameter, {\n"
5820                "  something();\n"
5821                "  // Comment using all columns.\n"
5822                "  somethingelse();\n"
5823                "});",
5824                getLLVMStyleWithColumns(40));
5825   verifyFormat("DEBUG( //\n"
5826                "    { f(); }, a);");
5827   verifyFormat("DEBUG( //\n"
5828                "    {\n"
5829                "      f(); //\n"
5830                "    },\n"
5831                "    a);");
5832 
5833   EXPECT_EQ("call(parameter, {\n"
5834             "  something();\n"
5835             "  // Comment too\n"
5836             "  // looooooooooong.\n"
5837             "  somethingElse();\n"
5838             "});",
5839             format("call(parameter, {\n"
5840                    "  something();\n"
5841                    "  // Comment too looooooooooong.\n"
5842                    "  somethingElse();\n"
5843                    "});",
5844                    getLLVMStyleWithColumns(29)));
5845   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5846   EXPECT_EQ("DEBUG({ // comment\n"
5847             "  int i;\n"
5848             "});",
5849             format("DEBUG({ // comment\n"
5850                    "int  i;\n"
5851                    "});"));
5852   EXPECT_EQ("DEBUG({\n"
5853             "  int i;\n"
5854             "\n"
5855             "  // comment\n"
5856             "  int j;\n"
5857             "});",
5858             format("DEBUG({\n"
5859                    "  int  i;\n"
5860                    "\n"
5861                    "  // comment\n"
5862                    "  int  j;\n"
5863                    "});"));
5864 
5865   verifyFormat("DEBUG({\n"
5866                "  if (a)\n"
5867                "    return;\n"
5868                "});");
5869   verifyGoogleFormat("DEBUG({\n"
5870                      "  if (a) return;\n"
5871                      "});");
5872   FormatStyle Style = getGoogleStyle();
5873   Style.ColumnLimit = 45;
5874   verifyFormat("Debug(\n"
5875                "    aaaaa,\n"
5876                "    {\n"
5877                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5878                "    },\n"
5879                "    a);",
5880                Style);
5881 
5882   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5883 
5884   verifyNoCrash("^{v^{a}}");
5885 }
5886 
5887 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
5888   EXPECT_EQ("#define MACRO()                     \\\n"
5889             "  Debug(aaa, /* force line break */ \\\n"
5890             "        {                           \\\n"
5891             "          int i;                    \\\n"
5892             "          int j;                    \\\n"
5893             "        })",
5894             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
5895                    "          {  int   i;  int  j;   })",
5896                    getGoogleStyle()));
5897 
5898   EXPECT_EQ("#define A                                       \\\n"
5899             "  [] {                                          \\\n"
5900             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
5901             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
5902             "  }",
5903             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5904                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
5905                    getGoogleStyle()));
5906 }
5907 
5908 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
5909   EXPECT_EQ("{}", format("{}"));
5910   verifyFormat("enum E {};");
5911   verifyFormat("enum E {}");
5912   FormatStyle Style = getLLVMStyle();
5913   Style.SpaceInEmptyBlock = true;
5914   EXPECT_EQ("void f() { }", format("void f() {}", Style));
5915   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
5916   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
5917   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5918   Style.BraceWrapping.BeforeElse = false;
5919   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5920   verifyFormat("if (a)\n"
5921                "{\n"
5922                "} else if (b)\n"
5923                "{\n"
5924                "} else\n"
5925                "{ }",
5926                Style);
5927   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
5928   verifyFormat("if (a) {\n"
5929                "} else if (b) {\n"
5930                "} else {\n"
5931                "}",
5932                Style);
5933   Style.BraceWrapping.BeforeElse = true;
5934   verifyFormat("if (a) { }\n"
5935                "else if (b) { }\n"
5936                "else { }",
5937                Style);
5938 }
5939 
5940 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
5941   FormatStyle Style = getLLVMStyle();
5942   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
5943   Style.MacroBlockEnd = "^[A-Z_]+_END$";
5944   verifyFormat("FOO_BEGIN\n"
5945                "  FOO_ENTRY\n"
5946                "FOO_END",
5947                Style);
5948   verifyFormat("FOO_BEGIN\n"
5949                "  NESTED_FOO_BEGIN\n"
5950                "    NESTED_FOO_ENTRY\n"
5951                "  NESTED_FOO_END\n"
5952                "FOO_END",
5953                Style);
5954   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
5955                "  int x;\n"
5956                "  x = 1;\n"
5957                "FOO_END(Baz)",
5958                Style);
5959 }
5960 
5961 //===----------------------------------------------------------------------===//
5962 // Line break tests.
5963 //===----------------------------------------------------------------------===//
5964 
5965 TEST_F(FormatTest, PreventConfusingIndents) {
5966   verifyFormat(
5967       "void f() {\n"
5968       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
5969       "                         parameter, parameter, parameter)),\n"
5970       "                     SecondLongCall(parameter));\n"
5971       "}");
5972   verifyFormat(
5973       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5974       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5975       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5976       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
5977   verifyFormat(
5978       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5979       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
5980       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5981       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
5982   verifyFormat(
5983       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5984       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
5985       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
5986       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
5987   verifyFormat("int a = bbbb && ccc &&\n"
5988                "        fffff(\n"
5989                "#define A Just forcing a new line\n"
5990                "            ddd);");
5991 }
5992 
5993 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
5994   verifyFormat(
5995       "bool aaaaaaa =\n"
5996       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
5997       "    bbbbbbbb();");
5998   verifyFormat(
5999       "bool aaaaaaa =\n"
6000       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
6001       "    bbbbbbbb();");
6002 
6003   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6004                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
6005                "    ccccccccc == ddddddddddd;");
6006   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6007                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
6008                "    ccccccccc == ddddddddddd;");
6009   verifyFormat(
6010       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6011       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
6012       "    ccccccccc == ddddddddddd;");
6013 
6014   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6015                "                 aaaaaa) &&\n"
6016                "         bbbbbb && cccccc;");
6017   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6018                "                 aaaaaa) >>\n"
6019                "         bbbbbb;");
6020   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
6021                "    SourceMgr.getSpellingColumnNumber(\n"
6022                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
6023                "    1);");
6024 
6025   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6026                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
6027                "    cccccc) {\n}");
6028   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6029                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6030                "              cccccc) {\n}");
6031   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6032                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6033                "              cccccc) {\n}");
6034   verifyFormat("b = a &&\n"
6035                "    // Comment\n"
6036                "    b.c && d;");
6037 
6038   // If the LHS of a comparison is not a binary expression itself, the
6039   // additional linebreak confuses many people.
6040   verifyFormat(
6041       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6042       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
6043       "}");
6044   verifyFormat(
6045       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6046       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6047       "}");
6048   verifyFormat(
6049       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
6050       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6051       "}");
6052   verifyFormat(
6053       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6054       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
6055       "}");
6056   // Even explicit parentheses stress the precedence enough to make the
6057   // additional break unnecessary.
6058   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6059                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6060                "}");
6061   // This cases is borderline, but with the indentation it is still readable.
6062   verifyFormat(
6063       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6064       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6065       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6066       "}",
6067       getLLVMStyleWithColumns(75));
6068 
6069   // If the LHS is a binary expression, we should still use the additional break
6070   // as otherwise the formatting hides the operator precedence.
6071   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6072                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6073                "    5) {\n"
6074                "}");
6075   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6076                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
6077                "    5) {\n"
6078                "}");
6079 
6080   FormatStyle OnePerLine = getLLVMStyle();
6081   OnePerLine.BinPackParameters = false;
6082   verifyFormat(
6083       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6084       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6085       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
6086       OnePerLine);
6087 
6088   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
6089                "                .aaa(aaaaaaaaaaaaa) *\n"
6090                "            aaaaaaa +\n"
6091                "        aaaaaaa;",
6092                getLLVMStyleWithColumns(40));
6093 }
6094 
6095 TEST_F(FormatTest, ExpressionIndentation) {
6096   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6097                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6098                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6099                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6100                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6101                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
6102                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6103                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
6104                "                 ccccccccccccccccccccccccccccccccccccccccc;");
6105   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6106                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6107                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6108                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6109   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6110                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6111                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6112                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6113   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6114                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6115                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6116                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6117   verifyFormat("if () {\n"
6118                "} else if (aaaaa && bbbbb > // break\n"
6119                "                        ccccc) {\n"
6120                "}");
6121   verifyFormat("if () {\n"
6122                "} else if constexpr (aaaaa && bbbbb > // break\n"
6123                "                                  ccccc) {\n"
6124                "}");
6125   verifyFormat("if () {\n"
6126                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
6127                "                                  ccccc) {\n"
6128                "}");
6129   verifyFormat("if () {\n"
6130                "} else if (aaaaa &&\n"
6131                "           bbbbb > // break\n"
6132                "               ccccc &&\n"
6133                "           ddddd) {\n"
6134                "}");
6135 
6136   // Presence of a trailing comment used to change indentation of b.
6137   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
6138                "       b;\n"
6139                "return aaaaaaaaaaaaaaaaaaa +\n"
6140                "       b; //",
6141                getLLVMStyleWithColumns(30));
6142 }
6143 
6144 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
6145   // Not sure what the best system is here. Like this, the LHS can be found
6146   // immediately above an operator (everything with the same or a higher
6147   // indent). The RHS is aligned right of the operator and so compasses
6148   // everything until something with the same indent as the operator is found.
6149   // FIXME: Is this a good system?
6150   FormatStyle Style = getLLVMStyle();
6151   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6152   verifyFormat(
6153       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6154       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6155       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6156       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6157       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6158       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6159       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6160       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6161       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
6162       Style);
6163   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6164                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6165                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6166                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6167                Style);
6168   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6169                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6170                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6171                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6172                Style);
6173   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6174                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6175                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6176                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6177                Style);
6178   verifyFormat("if () {\n"
6179                "} else if (aaaaa\n"
6180                "           && bbbbb // break\n"
6181                "                  > ccccc) {\n"
6182                "}",
6183                Style);
6184   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6185                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6186                Style);
6187   verifyFormat("return (a)\n"
6188                "       // comment\n"
6189                "       + b;",
6190                Style);
6191   verifyFormat(
6192       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6193       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6194       "             + cc;",
6195       Style);
6196 
6197   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6198                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6199                Style);
6200 
6201   // Forced by comments.
6202   verifyFormat(
6203       "unsigned ContentSize =\n"
6204       "    sizeof(int16_t)   // DWARF ARange version number\n"
6205       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6206       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6207       "    + sizeof(int8_t); // Segment Size (in bytes)");
6208 
6209   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6210                "       == boost::fusion::at_c<1>(iiii).second;",
6211                Style);
6212 
6213   Style.ColumnLimit = 60;
6214   verifyFormat("zzzzzzzzzz\n"
6215                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6216                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6217                Style);
6218 
6219   Style.ColumnLimit = 80;
6220   Style.IndentWidth = 4;
6221   Style.TabWidth = 4;
6222   Style.UseTab = FormatStyle::UT_Always;
6223   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6224   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6225   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6226             "\t&& (someOtherLongishConditionPart1\n"
6227             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6228             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6229                    "(someOtherLongishConditionPart1 || "
6230                    "someOtherEvenLongerNestedConditionPart2);",
6231                    Style));
6232 }
6233 
6234 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6235   FormatStyle Style = getLLVMStyle();
6236   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6237   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6238 
6239   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6240                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6241                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6242                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6243                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6244                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6245                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6246                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6247                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6248                Style);
6249   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6250                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6251                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6252                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6253                Style);
6254   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6255                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6256                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6257                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6258                Style);
6259   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6260                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6261                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6262                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6263                Style);
6264   verifyFormat("if () {\n"
6265                "} else if (aaaaa\n"
6266                "           && bbbbb // break\n"
6267                "                  > ccccc) {\n"
6268                "}",
6269                Style);
6270   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6271                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6272                Style);
6273   verifyFormat("return (a)\n"
6274                "     // comment\n"
6275                "     + b;",
6276                Style);
6277   verifyFormat(
6278       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6279       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6280       "           + cc;",
6281       Style);
6282   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6283                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6284                "                        : 3333333333333333;",
6285                Style);
6286   verifyFormat(
6287       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6288       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6289       "                                             : eeeeeeeeeeeeeeeeee)\n"
6290       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6291       "                        : 3333333333333333;",
6292       Style);
6293   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6294                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6295                Style);
6296 
6297   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6298                "    == boost::fusion::at_c<1>(iiii).second;",
6299                Style);
6300 
6301   Style.ColumnLimit = 60;
6302   verifyFormat("zzzzzzzzzzzzz\n"
6303                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6304                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6305                Style);
6306 
6307   // Forced by comments.
6308   Style.ColumnLimit = 80;
6309   verifyFormat(
6310       "unsigned ContentSize\n"
6311       "    = sizeof(int16_t) // DWARF ARange version number\n"
6312       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6313       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6314       "    + sizeof(int8_t); // Segment Size (in bytes)",
6315       Style);
6316 
6317   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6318   verifyFormat(
6319       "unsigned ContentSize =\n"
6320       "    sizeof(int16_t)   // DWARF ARange version number\n"
6321       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6322       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6323       "    + sizeof(int8_t); // Segment Size (in bytes)",
6324       Style);
6325 
6326   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6327   verifyFormat(
6328       "unsigned ContentSize =\n"
6329       "    sizeof(int16_t)   // DWARF ARange version number\n"
6330       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6331       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6332       "    + sizeof(int8_t); // Segment Size (in bytes)",
6333       Style);
6334 }
6335 
6336 TEST_F(FormatTest, EnforcedOperatorWraps) {
6337   // Here we'd like to wrap after the || operators, but a comment is forcing an
6338   // earlier wrap.
6339   verifyFormat("bool x = aaaaa //\n"
6340                "         || bbbbb\n"
6341                "         //\n"
6342                "         || cccc;");
6343 }
6344 
6345 TEST_F(FormatTest, NoOperandAlignment) {
6346   FormatStyle Style = getLLVMStyle();
6347   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6348   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6349                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6350                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6351                Style);
6352   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6353   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6354                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6355                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6356                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6357                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6358                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6359                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6360                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6361                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6362                Style);
6363 
6364   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6365                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6366                "    + cc;",
6367                Style);
6368   verifyFormat("int a = aa\n"
6369                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6370                "        * cccccccccccccccccccccccccccccccccccc;\n",
6371                Style);
6372 
6373   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6374   verifyFormat("return (a > b\n"
6375                "    // comment1\n"
6376                "    // comment2\n"
6377                "    || c);",
6378                Style);
6379 }
6380 
6381 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6382   FormatStyle Style = getLLVMStyle();
6383   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6384   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6385                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6386                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6387                Style);
6388 }
6389 
6390 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6391   FormatStyle Style = getLLVMStyleWithColumns(40);
6392   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6393   Style.BinPackArguments = false;
6394   verifyFormat("void test() {\n"
6395                "  someFunction(\n"
6396                "      this + argument + is + quite\n"
6397                "      + long + so + it + gets + wrapped\n"
6398                "      + but + remains + bin - packed);\n"
6399                "}",
6400                Style);
6401   verifyFormat("void test() {\n"
6402                "  someFunction(arg1,\n"
6403                "               this + argument + is\n"
6404                "                   + quite + long + so\n"
6405                "                   + it + gets + wrapped\n"
6406                "                   + but + remains + bin\n"
6407                "                   - packed,\n"
6408                "               arg3);\n"
6409                "}",
6410                Style);
6411   verifyFormat("void test() {\n"
6412                "  someFunction(\n"
6413                "      arg1,\n"
6414                "      this + argument + has\n"
6415                "          + anotherFunc(nested,\n"
6416                "                        calls + whose\n"
6417                "                            + arguments\n"
6418                "                            + are + also\n"
6419                "                            + wrapped,\n"
6420                "                        in + addition)\n"
6421                "          + to + being + bin - packed,\n"
6422                "      arg3);\n"
6423                "}",
6424                Style);
6425 
6426   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6427   verifyFormat("void test() {\n"
6428                "  someFunction(\n"
6429                "      arg1,\n"
6430                "      this + argument + has +\n"
6431                "          anotherFunc(nested,\n"
6432                "                      calls + whose +\n"
6433                "                          arguments +\n"
6434                "                          are + also +\n"
6435                "                          wrapped,\n"
6436                "                      in + addition) +\n"
6437                "          to + being + bin - packed,\n"
6438                "      arg3);\n"
6439                "}",
6440                Style);
6441 }
6442 
6443 TEST_F(FormatTest, ConstructorInitializers) {
6444   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6445   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6446                getLLVMStyleWithColumns(45));
6447   verifyFormat("Constructor()\n"
6448                "    : Inttializer(FitsOnTheLine) {}",
6449                getLLVMStyleWithColumns(44));
6450   verifyFormat("Constructor()\n"
6451                "    : Inttializer(FitsOnTheLine) {}",
6452                getLLVMStyleWithColumns(43));
6453 
6454   verifyFormat("template <typename T>\n"
6455                "Constructor() : Initializer(FitsOnTheLine) {}",
6456                getLLVMStyleWithColumns(45));
6457 
6458   verifyFormat(
6459       "SomeClass::Constructor()\n"
6460       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6461 
6462   verifyFormat(
6463       "SomeClass::Constructor()\n"
6464       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6465       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6466   verifyFormat(
6467       "SomeClass::Constructor()\n"
6468       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6469       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6470   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6471                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6472                "    : aaaaaaaaaa(aaaaaa) {}");
6473 
6474   verifyFormat("Constructor()\n"
6475                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6476                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6477                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6478                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6479 
6480   verifyFormat("Constructor()\n"
6481                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6482                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6483 
6484   verifyFormat("Constructor(int Parameter = 0)\n"
6485                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6486                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6487   verifyFormat("Constructor()\n"
6488                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6489                "}",
6490                getLLVMStyleWithColumns(60));
6491   verifyFormat("Constructor()\n"
6492                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6493                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6494 
6495   // Here a line could be saved by splitting the second initializer onto two
6496   // lines, but that is not desirable.
6497   verifyFormat("Constructor()\n"
6498                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6499                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6500                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6501 
6502   FormatStyle OnePerLine = getLLVMStyle();
6503   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6504   verifyFormat("MyClass::MyClass()\n"
6505                "    : a(a),\n"
6506                "      b(b),\n"
6507                "      c(c) {}",
6508                OnePerLine);
6509   verifyFormat("MyClass::MyClass()\n"
6510                "    : a(a), // comment\n"
6511                "      b(b),\n"
6512                "      c(c) {}",
6513                OnePerLine);
6514   verifyFormat("MyClass::MyClass(int a)\n"
6515                "    : b(a),      // comment\n"
6516                "      c(a + 1) { // lined up\n"
6517                "}",
6518                OnePerLine);
6519   verifyFormat("Constructor()\n"
6520                "    : a(b, b, b) {}",
6521                OnePerLine);
6522   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6523   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6524   verifyFormat("SomeClass::Constructor()\n"
6525                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6526                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6527                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6528                OnePerLine);
6529   verifyFormat("SomeClass::Constructor()\n"
6530                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6531                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6532                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6533                OnePerLine);
6534   verifyFormat("MyClass::MyClass(int var)\n"
6535                "    : some_var_(var),            // 4 space indent\n"
6536                "      some_other_var_(var + 1) { // lined up\n"
6537                "}",
6538                OnePerLine);
6539   verifyFormat("Constructor()\n"
6540                "    : aaaaa(aaaaaa),\n"
6541                "      aaaaa(aaaaaa),\n"
6542                "      aaaaa(aaaaaa),\n"
6543                "      aaaaa(aaaaaa),\n"
6544                "      aaaaa(aaaaaa) {}",
6545                OnePerLine);
6546   verifyFormat("Constructor()\n"
6547                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6548                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6549                OnePerLine);
6550   OnePerLine.BinPackParameters = false;
6551   verifyFormat(
6552       "Constructor()\n"
6553       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6554       "          aaaaaaaaaaa().aaa(),\n"
6555       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6556       OnePerLine);
6557   OnePerLine.ColumnLimit = 60;
6558   verifyFormat("Constructor()\n"
6559                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6560                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6561                OnePerLine);
6562 
6563   EXPECT_EQ("Constructor()\n"
6564             "    : // Comment forcing unwanted break.\n"
6565             "      aaaa(aaaa) {}",
6566             format("Constructor() :\n"
6567                    "    // Comment forcing unwanted break.\n"
6568                    "    aaaa(aaaa) {}"));
6569 }
6570 
6571 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6572   FormatStyle Style = getLLVMStyleWithColumns(60);
6573   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6574   Style.BinPackParameters = false;
6575 
6576   for (int i = 0; i < 4; ++i) {
6577     // Test all combinations of parameters that should not have an effect.
6578     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6579     Style.AllowAllArgumentsOnNextLine = i & 2;
6580 
6581     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6582     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6583     verifyFormat("Constructor()\n"
6584                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6585                  Style);
6586     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6587 
6588     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6589     verifyFormat("Constructor()\n"
6590                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6591                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6592                  Style);
6593     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6594 
6595     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6596     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6597     verifyFormat("Constructor()\n"
6598                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6599                  Style);
6600 
6601     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6602     verifyFormat("Constructor()\n"
6603                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6604                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6605                  Style);
6606 
6607     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6608     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6609     verifyFormat("Constructor() :\n"
6610                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6611                  Style);
6612 
6613     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6614     verifyFormat("Constructor() :\n"
6615                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6616                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6617                  Style);
6618   }
6619 
6620   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6621   // AllowAllConstructorInitializersOnNextLine in all
6622   // BreakConstructorInitializers modes
6623   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6624   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6625   verifyFormat("SomeClassWithALongName::Constructor(\n"
6626                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6627                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6628                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6629                Style);
6630 
6631   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6632   verifyFormat("SomeClassWithALongName::Constructor(\n"
6633                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6634                "    int bbbbbbbbbbbbb,\n"
6635                "    int cccccccccccccccc)\n"
6636                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6637                Style);
6638 
6639   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6640   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6641   verifyFormat("SomeClassWithALongName::Constructor(\n"
6642                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6643                "    int bbbbbbbbbbbbb)\n"
6644                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6645                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6646                Style);
6647 
6648   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6649 
6650   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6651   verifyFormat("SomeClassWithALongName::Constructor(\n"
6652                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6653                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6654                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6655                Style);
6656 
6657   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6658   verifyFormat("SomeClassWithALongName::Constructor(\n"
6659                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6660                "    int bbbbbbbbbbbbb,\n"
6661                "    int cccccccccccccccc)\n"
6662                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6663                Style);
6664 
6665   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6666   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6667   verifyFormat("SomeClassWithALongName::Constructor(\n"
6668                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6669                "    int bbbbbbbbbbbbb)\n"
6670                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6671                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6672                Style);
6673 
6674   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6675   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6676   verifyFormat("SomeClassWithALongName::Constructor(\n"
6677                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6678                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6679                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6680                Style);
6681 
6682   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6683   verifyFormat("SomeClassWithALongName::Constructor(\n"
6684                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6685                "    int bbbbbbbbbbbbb,\n"
6686                "    int cccccccccccccccc) :\n"
6687                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6688                Style);
6689 
6690   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6691   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6692   verifyFormat("SomeClassWithALongName::Constructor(\n"
6693                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6694                "    int bbbbbbbbbbbbb) :\n"
6695                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6696                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6697                Style);
6698 }
6699 
6700 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6701   FormatStyle Style = getLLVMStyleWithColumns(60);
6702   Style.BinPackArguments = false;
6703   for (int i = 0; i < 4; ++i) {
6704     // Test all combinations of parameters that should not have an effect.
6705     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6706     Style.PackConstructorInitializers =
6707         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6708 
6709     Style.AllowAllArgumentsOnNextLine = true;
6710     verifyFormat("void foo() {\n"
6711                  "  FunctionCallWithReallyLongName(\n"
6712                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6713                  "}",
6714                  Style);
6715     Style.AllowAllArgumentsOnNextLine = false;
6716     verifyFormat("void foo() {\n"
6717                  "  FunctionCallWithReallyLongName(\n"
6718                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6719                  "      bbbbbbbbbbbb);\n"
6720                  "}",
6721                  Style);
6722 
6723     Style.AllowAllArgumentsOnNextLine = true;
6724     verifyFormat("void foo() {\n"
6725                  "  auto VariableWithReallyLongName = {\n"
6726                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6727                  "}",
6728                  Style);
6729     Style.AllowAllArgumentsOnNextLine = false;
6730     verifyFormat("void foo() {\n"
6731                  "  auto VariableWithReallyLongName = {\n"
6732                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6733                  "      bbbbbbbbbbbb};\n"
6734                  "}",
6735                  Style);
6736   }
6737 
6738   // This parameter should not affect declarations.
6739   Style.BinPackParameters = false;
6740   Style.AllowAllArgumentsOnNextLine = false;
6741   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6742   verifyFormat("void FunctionCallWithReallyLongName(\n"
6743                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6744                Style);
6745   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6746   verifyFormat("void FunctionCallWithReallyLongName(\n"
6747                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6748                "    int bbbbbbbbbbbb);",
6749                Style);
6750 }
6751 
6752 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6753   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6754   // and BAS_Align.
6755   FormatStyle Style = getLLVMStyleWithColumns(35);
6756   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6757                     "void functionDecl(int A, int B, int C);";
6758   Style.AllowAllArgumentsOnNextLine = false;
6759   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6760   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6761                       "    paramC);\n"
6762                       "void functionDecl(int A, int B,\n"
6763                       "    int C);"),
6764             format(Input, Style));
6765   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6766   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6767                       "             paramC);\n"
6768                       "void functionDecl(int A, int B,\n"
6769                       "                  int C);"),
6770             format(Input, Style));
6771   // However, BAS_AlwaysBreak should take precedence over
6772   // AllowAllArgumentsOnNextLine.
6773   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6774   EXPECT_EQ(StringRef("functionCall(\n"
6775                       "    paramA, paramB, paramC);\n"
6776                       "void functionDecl(\n"
6777                       "    int A, int B, int C);"),
6778             format(Input, Style));
6779 
6780   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6781   // first argument.
6782   Style.AllowAllArgumentsOnNextLine = true;
6783   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6784   EXPECT_EQ(StringRef("functionCall(\n"
6785                       "    paramA, paramB, paramC);\n"
6786                       "void functionDecl(\n"
6787                       "    int A, int B, int C);"),
6788             format(Input, Style));
6789   // It wouldn't fit on one line with aligned parameters so this setting
6790   // doesn't change anything for BAS_Align.
6791   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6792   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6793                       "             paramC);\n"
6794                       "void functionDecl(int A, int B,\n"
6795                       "                  int C);"),
6796             format(Input, Style));
6797   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6798   EXPECT_EQ(StringRef("functionCall(\n"
6799                       "    paramA, paramB, paramC);\n"
6800                       "void functionDecl(\n"
6801                       "    int A, int B, int C);"),
6802             format(Input, Style));
6803 }
6804 
6805 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6806   FormatStyle Style = getLLVMStyle();
6807   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6808 
6809   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6810   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6811                getStyleWithColumns(Style, 45));
6812   verifyFormat("Constructor() :\n"
6813                "    Initializer(FitsOnTheLine) {}",
6814                getStyleWithColumns(Style, 44));
6815   verifyFormat("Constructor() :\n"
6816                "    Initializer(FitsOnTheLine) {}",
6817                getStyleWithColumns(Style, 43));
6818 
6819   verifyFormat("template <typename T>\n"
6820                "Constructor() : Initializer(FitsOnTheLine) {}",
6821                getStyleWithColumns(Style, 50));
6822   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6823   verifyFormat(
6824       "SomeClass::Constructor() :\n"
6825       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6826       Style);
6827 
6828   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6829   verifyFormat(
6830       "SomeClass::Constructor() :\n"
6831       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6832       Style);
6833 
6834   verifyFormat(
6835       "SomeClass::Constructor() :\n"
6836       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6837       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6838       Style);
6839   verifyFormat(
6840       "SomeClass::Constructor() :\n"
6841       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6842       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6843       Style);
6844   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6845                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6846                "    aaaaaaaaaa(aaaaaa) {}",
6847                Style);
6848 
6849   verifyFormat("Constructor() :\n"
6850                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6851                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6852                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6853                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
6854                Style);
6855 
6856   verifyFormat("Constructor() :\n"
6857                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6858                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6859                Style);
6860 
6861   verifyFormat("Constructor(int Parameter = 0) :\n"
6862                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6863                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
6864                Style);
6865   verifyFormat("Constructor() :\n"
6866                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6867                "}",
6868                getStyleWithColumns(Style, 60));
6869   verifyFormat("Constructor() :\n"
6870                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6871                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
6872                Style);
6873 
6874   // Here a line could be saved by splitting the second initializer onto two
6875   // lines, but that is not desirable.
6876   verifyFormat("Constructor() :\n"
6877                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6878                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
6879                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6880                Style);
6881 
6882   FormatStyle OnePerLine = Style;
6883   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6884   verifyFormat("SomeClass::Constructor() :\n"
6885                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6886                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6887                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6888                OnePerLine);
6889   verifyFormat("SomeClass::Constructor() :\n"
6890                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6891                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6892                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6893                OnePerLine);
6894   verifyFormat("MyClass::MyClass(int var) :\n"
6895                "    some_var_(var),            // 4 space indent\n"
6896                "    some_other_var_(var + 1) { // lined up\n"
6897                "}",
6898                OnePerLine);
6899   verifyFormat("Constructor() :\n"
6900                "    aaaaa(aaaaaa),\n"
6901                "    aaaaa(aaaaaa),\n"
6902                "    aaaaa(aaaaaa),\n"
6903                "    aaaaa(aaaaaa),\n"
6904                "    aaaaa(aaaaaa) {}",
6905                OnePerLine);
6906   verifyFormat("Constructor() :\n"
6907                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6908                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
6909                OnePerLine);
6910   OnePerLine.BinPackParameters = false;
6911   verifyFormat("Constructor() :\n"
6912                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6913                "        aaaaaaaaaaa().aaa(),\n"
6914                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6915                OnePerLine);
6916   OnePerLine.ColumnLimit = 60;
6917   verifyFormat("Constructor() :\n"
6918                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6919                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6920                OnePerLine);
6921 
6922   EXPECT_EQ("Constructor() :\n"
6923             "    // Comment forcing unwanted break.\n"
6924             "    aaaa(aaaa) {}",
6925             format("Constructor() :\n"
6926                    "    // Comment forcing unwanted break.\n"
6927                    "    aaaa(aaaa) {}",
6928                    Style));
6929 
6930   Style.ColumnLimit = 0;
6931   verifyFormat("SomeClass::Constructor() :\n"
6932                "    a(a) {}",
6933                Style);
6934   verifyFormat("SomeClass::Constructor() noexcept :\n"
6935                "    a(a) {}",
6936                Style);
6937   verifyFormat("SomeClass::Constructor() :\n"
6938                "    a(a), b(b), c(c) {}",
6939                Style);
6940   verifyFormat("SomeClass::Constructor() :\n"
6941                "    a(a) {\n"
6942                "  foo();\n"
6943                "  bar();\n"
6944                "}",
6945                Style);
6946 
6947   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6948   verifyFormat("SomeClass::Constructor() :\n"
6949                "    a(a), b(b), c(c) {\n"
6950                "}",
6951                Style);
6952   verifyFormat("SomeClass::Constructor() :\n"
6953                "    a(a) {\n"
6954                "}",
6955                Style);
6956 
6957   Style.ColumnLimit = 80;
6958   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
6959   Style.ConstructorInitializerIndentWidth = 2;
6960   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
6961   verifyFormat("SomeClass::Constructor() :\n"
6962                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6963                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
6964                Style);
6965 
6966   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
6967   // well
6968   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
6969   verifyFormat(
6970       "class SomeClass\n"
6971       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6972       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6973       Style);
6974   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
6975   verifyFormat(
6976       "class SomeClass\n"
6977       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6978       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6979       Style);
6980   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
6981   verifyFormat(
6982       "class SomeClass :\n"
6983       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6984       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6985       Style);
6986   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
6987   verifyFormat(
6988       "class SomeClass\n"
6989       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6990       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6991       Style);
6992 }
6993 
6994 #ifndef EXPENSIVE_CHECKS
6995 // Expensive checks enables libstdc++ checking which includes validating the
6996 // state of ranges used in std::priority_queue - this blows out the
6997 // runtime/scalability of the function and makes this test unacceptably slow.
6998 TEST_F(FormatTest, MemoizationTests) {
6999   // This breaks if the memoization lookup does not take \c Indent and
7000   // \c LastSpace into account.
7001   verifyFormat(
7002       "extern CFRunLoopTimerRef\n"
7003       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
7004       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
7005       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
7006       "                     CFRunLoopTimerContext *context) {}");
7007 
7008   // Deep nesting somewhat works around our memoization.
7009   verifyFormat(
7010       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7011       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7012       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7013       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7014       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
7015       getLLVMStyleWithColumns(65));
7016   verifyFormat(
7017       "aaaaa(\n"
7018       "    aaaaa,\n"
7019       "    aaaaa(\n"
7020       "        aaaaa,\n"
7021       "        aaaaa(\n"
7022       "            aaaaa,\n"
7023       "            aaaaa(\n"
7024       "                aaaaa,\n"
7025       "                aaaaa(\n"
7026       "                    aaaaa,\n"
7027       "                    aaaaa(\n"
7028       "                        aaaaa,\n"
7029       "                        aaaaa(\n"
7030       "                            aaaaa,\n"
7031       "                            aaaaa(\n"
7032       "                                aaaaa,\n"
7033       "                                aaaaa(\n"
7034       "                                    aaaaa,\n"
7035       "                                    aaaaa(\n"
7036       "                                        aaaaa,\n"
7037       "                                        aaaaa(\n"
7038       "                                            aaaaa,\n"
7039       "                                            aaaaa(\n"
7040       "                                                aaaaa,\n"
7041       "                                                aaaaa))))))))))));",
7042       getLLVMStyleWithColumns(65));
7043   verifyFormat(
7044       "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"
7045       "                                  a),\n"
7046       "                                a),\n"
7047       "                              a),\n"
7048       "                            a),\n"
7049       "                          a),\n"
7050       "                        a),\n"
7051       "                      a),\n"
7052       "                    a),\n"
7053       "                  a),\n"
7054       "                a),\n"
7055       "              a),\n"
7056       "            a),\n"
7057       "          a),\n"
7058       "        a),\n"
7059       "      a),\n"
7060       "    a),\n"
7061       "  a)",
7062       getLLVMStyleWithColumns(65));
7063 
7064   // This test takes VERY long when memoization is broken.
7065   FormatStyle OnePerLine = getLLVMStyle();
7066   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7067   OnePerLine.BinPackParameters = false;
7068   std::string input = "Constructor()\n"
7069                       "    : aaaa(a,\n";
7070   for (unsigned i = 0, e = 80; i != e; ++i) {
7071     input += "           a,\n";
7072   }
7073   input += "           a) {}";
7074   verifyFormat(input, OnePerLine);
7075 }
7076 #endif
7077 
7078 TEST_F(FormatTest, BreaksAsHighAsPossible) {
7079   verifyFormat(
7080       "void f() {\n"
7081       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
7082       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
7083       "    f();\n"
7084       "}");
7085   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
7086                "    Intervals[i - 1].getRange().getLast()) {\n}");
7087 }
7088 
7089 TEST_F(FormatTest, BreaksFunctionDeclarations) {
7090   // Principially, we break function declarations in a certain order:
7091   // 1) break amongst arguments.
7092   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
7093                "                              Cccccccccccccc cccccccccccccc);");
7094   verifyFormat("template <class TemplateIt>\n"
7095                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
7096                "                            TemplateIt *stop) {}");
7097 
7098   // 2) break after return type.
7099   verifyFormat(
7100       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7101       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
7102       getGoogleStyle());
7103 
7104   // 3) break after (.
7105   verifyFormat(
7106       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
7107       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
7108       getGoogleStyle());
7109 
7110   // 4) break before after nested name specifiers.
7111   verifyFormat(
7112       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7113       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
7114       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
7115       getGoogleStyle());
7116 
7117   // However, there are exceptions, if a sufficient amount of lines can be
7118   // saved.
7119   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
7120   // more adjusting.
7121   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7122                "                                  Cccccccccccccc cccccccccc,\n"
7123                "                                  Cccccccccccccc cccccccccc,\n"
7124                "                                  Cccccccccccccc cccccccccc,\n"
7125                "                                  Cccccccccccccc cccccccccc);");
7126   verifyFormat(
7127       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7128       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7129       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7130       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
7131       getGoogleStyle());
7132   verifyFormat(
7133       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7134       "                                          Cccccccccccccc cccccccccc,\n"
7135       "                                          Cccccccccccccc cccccccccc,\n"
7136       "                                          Cccccccccccccc cccccccccc,\n"
7137       "                                          Cccccccccccccc cccccccccc,\n"
7138       "                                          Cccccccccccccc cccccccccc,\n"
7139       "                                          Cccccccccccccc cccccccccc);");
7140   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7141                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7142                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7143                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7144                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
7145 
7146   // Break after multi-line parameters.
7147   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7148                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7149                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7150                "    bbbb bbbb);");
7151   verifyFormat("void SomeLoooooooooooongFunction(\n"
7152                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
7153                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7154                "    int bbbbbbbbbbbbb);");
7155 
7156   // Treat overloaded operators like other functions.
7157   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7158                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
7159   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7160                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
7161   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7162                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
7163   verifyGoogleFormat(
7164       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
7165       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7166   verifyGoogleFormat(
7167       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
7168       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7169   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7170                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7171   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
7172                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7173   verifyGoogleFormat(
7174       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
7175       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7176       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
7177   verifyGoogleFormat("template <typename T>\n"
7178                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7179                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
7180                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
7181 
7182   FormatStyle Style = getLLVMStyle();
7183   Style.PointerAlignment = FormatStyle::PAS_Left;
7184   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7185                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
7186                Style);
7187   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
7188                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7189                Style);
7190 }
7191 
7192 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
7193   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
7194   // Prefer keeping `::` followed by `operator` together.
7195   EXPECT_EQ("const aaaa::bbbbbbb &\n"
7196             "ccccccccc::operator++() {\n"
7197             "  stuff();\n"
7198             "}",
7199             format("const aaaa::bbbbbbb\n"
7200                    "&ccccccccc::operator++() { stuff(); }",
7201                    getLLVMStyleWithColumns(40)));
7202 }
7203 
7204 TEST_F(FormatTest, TrailingReturnType) {
7205   verifyFormat("auto foo() -> int;\n");
7206   // correct trailing return type spacing
7207   verifyFormat("auto operator->() -> int;\n");
7208   verifyFormat("auto operator++(int) -> int;\n");
7209 
7210   verifyFormat("struct S {\n"
7211                "  auto bar() const -> int;\n"
7212                "};");
7213   verifyFormat("template <size_t Order, typename T>\n"
7214                "auto load_img(const std::string &filename)\n"
7215                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
7216   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
7217                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
7218   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
7219   verifyFormat("template <typename T>\n"
7220                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
7221                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
7222 
7223   // Not trailing return types.
7224   verifyFormat("void f() { auto a = b->c(); }");
7225   verifyFormat("auto a = p->foo();");
7226   verifyFormat("int a = p->foo();");
7227   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
7228 }
7229 
7230 TEST_F(FormatTest, DeductionGuides) {
7231   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
7232   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
7233   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
7234   verifyFormat(
7235       "template <class... T>\n"
7236       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
7237   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
7238   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
7239   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
7240   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
7241   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
7242   verifyFormat("template <class T> x() -> x<1>;");
7243   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
7244 
7245   // Ensure not deduction guides.
7246   verifyFormat("c()->f<int>();");
7247   verifyFormat("x()->foo<1>;");
7248   verifyFormat("x = p->foo<3>();");
7249   verifyFormat("x()->x<1>();");
7250   verifyFormat("x()->x<1>;");
7251 }
7252 
7253 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
7254   // Avoid breaking before trailing 'const' or other trailing annotations, if
7255   // they are not function-like.
7256   FormatStyle Style = getGoogleStyleWithColumns(47);
7257   verifyFormat("void someLongFunction(\n"
7258                "    int someLoooooooooooooongParameter) const {\n}",
7259                getLLVMStyleWithColumns(47));
7260   verifyFormat("LoooooongReturnType\n"
7261                "someLoooooooongFunction() const {}",
7262                getLLVMStyleWithColumns(47));
7263   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
7264                "    const {}",
7265                Style);
7266   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7267                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
7268   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7269                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
7270   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7271                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
7272   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
7273                "                   aaaaaaaaaaa aaaaa) const override;");
7274   verifyGoogleFormat(
7275       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7276       "    const override;");
7277 
7278   // Even if the first parameter has to be wrapped.
7279   verifyFormat("void someLongFunction(\n"
7280                "    int someLongParameter) const {}",
7281                getLLVMStyleWithColumns(46));
7282   verifyFormat("void someLongFunction(\n"
7283                "    int someLongParameter) const {}",
7284                Style);
7285   verifyFormat("void someLongFunction(\n"
7286                "    int someLongParameter) override {}",
7287                Style);
7288   verifyFormat("void someLongFunction(\n"
7289                "    int someLongParameter) OVERRIDE {}",
7290                Style);
7291   verifyFormat("void someLongFunction(\n"
7292                "    int someLongParameter) final {}",
7293                Style);
7294   verifyFormat("void someLongFunction(\n"
7295                "    int someLongParameter) FINAL {}",
7296                Style);
7297   verifyFormat("void someLongFunction(\n"
7298                "    int parameter) const override {}",
7299                Style);
7300 
7301   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7302   verifyFormat("void someLongFunction(\n"
7303                "    int someLongParameter) const\n"
7304                "{\n"
7305                "}",
7306                Style);
7307 
7308   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7309   verifyFormat("void someLongFunction(\n"
7310                "    int someLongParameter) const\n"
7311                "  {\n"
7312                "  }",
7313                Style);
7314 
7315   // Unless these are unknown annotations.
7316   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7317                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7318                "    LONG_AND_UGLY_ANNOTATION;");
7319 
7320   // Breaking before function-like trailing annotations is fine to keep them
7321   // close to their arguments.
7322   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7323                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7324   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7325                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7326   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7327                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7328   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7329                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7330   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7331 
7332   verifyFormat(
7333       "void aaaaaaaaaaaaaaaaaa()\n"
7334       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7335       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7336   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7337                "    __attribute__((unused));");
7338   verifyGoogleFormat(
7339       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7340       "    GUARDED_BY(aaaaaaaaaaaa);");
7341   verifyGoogleFormat(
7342       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7343       "    GUARDED_BY(aaaaaaaaaaaa);");
7344   verifyGoogleFormat(
7345       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7346       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7347   verifyGoogleFormat(
7348       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7349       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7350 }
7351 
7352 TEST_F(FormatTest, FunctionAnnotations) {
7353   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7354                "int OldFunction(const string &parameter) {}");
7355   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7356                "string OldFunction(const string &parameter) {}");
7357   verifyFormat("template <typename T>\n"
7358                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7359                "string OldFunction(const string &parameter) {}");
7360 
7361   // Not function annotations.
7362   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7363                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7364   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7365                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7366   verifyFormat("MACRO(abc).function() // wrap\n"
7367                "    << abc;");
7368   verifyFormat("MACRO(abc)->function() // wrap\n"
7369                "    << abc;");
7370   verifyFormat("MACRO(abc)::function() // wrap\n"
7371                "    << abc;");
7372 }
7373 
7374 TEST_F(FormatTest, BreaksDesireably) {
7375   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7376                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7377                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7378   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7379                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7380                "}");
7381 
7382   verifyFormat(
7383       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7384       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7385 
7386   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7387                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7388                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7389 
7390   verifyFormat(
7391       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7392       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7393       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7394       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7395       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7396 
7397   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7398                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7399 
7400   verifyFormat(
7401       "void f() {\n"
7402       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7403       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7404       "}");
7405   verifyFormat(
7406       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7407       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7408   verifyFormat(
7409       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7410       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7411   verifyFormat(
7412       "aaaaaa(aaa,\n"
7413       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7414       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7415       "       aaaa);");
7416   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7417                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7418                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7419 
7420   // Indent consistently independent of call expression and unary operator.
7421   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7422                "    dddddddddddddddddddddddddddddd));");
7423   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7424                "    dddddddddddddddddddddddddddddd));");
7425   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7426                "    dddddddddddddddddddddddddddddd));");
7427 
7428   // This test case breaks on an incorrect memoization, i.e. an optimization not
7429   // taking into account the StopAt value.
7430   verifyFormat(
7431       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7432       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7433       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7434       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7435 
7436   verifyFormat("{\n  {\n    {\n"
7437                "      Annotation.SpaceRequiredBefore =\n"
7438                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7439                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7440                "    }\n  }\n}");
7441 
7442   // Break on an outer level if there was a break on an inner level.
7443   EXPECT_EQ("f(g(h(a, // comment\n"
7444             "      b, c),\n"
7445             "    d, e),\n"
7446             "  x, y);",
7447             format("f(g(h(a, // comment\n"
7448                    "    b, c), d, e), x, y);"));
7449 
7450   // Prefer breaking similar line breaks.
7451   verifyFormat(
7452       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7453       "                             NSTrackingMouseEnteredAndExited |\n"
7454       "                             NSTrackingActiveAlways;");
7455 }
7456 
7457 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7458   FormatStyle NoBinPacking = getGoogleStyle();
7459   NoBinPacking.BinPackParameters = false;
7460   NoBinPacking.BinPackArguments = true;
7461   verifyFormat("void f() {\n"
7462                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7463                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7464                "}",
7465                NoBinPacking);
7466   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7467                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7468                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7469                NoBinPacking);
7470 
7471   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7472   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7473                "                        vector<int> bbbbbbbbbbbbbbb);",
7474                NoBinPacking);
7475   // FIXME: This behavior difference is probably not wanted. However, currently
7476   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7477   // template arguments from BreakBeforeParameter being set because of the
7478   // one-per-line formatting.
7479   verifyFormat(
7480       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7481       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7482       NoBinPacking);
7483   verifyFormat(
7484       "void fffffffffff(\n"
7485       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7486       "        aaaaaaaaaa);");
7487 }
7488 
7489 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7490   FormatStyle NoBinPacking = getGoogleStyle();
7491   NoBinPacking.BinPackParameters = false;
7492   NoBinPacking.BinPackArguments = false;
7493   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7494                "  aaaaaaaaaaaaaaaaaaaa,\n"
7495                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7496                NoBinPacking);
7497   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7498                "        aaaaaaaaaaaaa,\n"
7499                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7500                NoBinPacking);
7501   verifyFormat(
7502       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7503       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7504       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7505       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7506       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7507       NoBinPacking);
7508   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7509                "    .aaaaaaaaaaaaaaaaaa();",
7510                NoBinPacking);
7511   verifyFormat("void f() {\n"
7512                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7513                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7514                "}",
7515                NoBinPacking);
7516 
7517   verifyFormat(
7518       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7519       "             aaaaaaaaaaaa,\n"
7520       "             aaaaaaaaaaaa);",
7521       NoBinPacking);
7522   verifyFormat(
7523       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7524       "                               ddddddddddddddddddddddddddddd),\n"
7525       "             test);",
7526       NoBinPacking);
7527 
7528   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7529                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7530                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7531                "    aaaaaaaaaaaaaaaaaa;",
7532                NoBinPacking);
7533   verifyFormat("a(\"a\"\n"
7534                "  \"a\",\n"
7535                "  a);");
7536 
7537   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7538   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7539                "                aaaaaaaaa,\n"
7540                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7541                NoBinPacking);
7542   verifyFormat(
7543       "void f() {\n"
7544       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7545       "      .aaaaaaa();\n"
7546       "}",
7547       NoBinPacking);
7548   verifyFormat(
7549       "template <class SomeType, class SomeOtherType>\n"
7550       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7551       NoBinPacking);
7552 }
7553 
7554 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7555   FormatStyle Style = getLLVMStyleWithColumns(15);
7556   Style.ExperimentalAutoDetectBinPacking = true;
7557   EXPECT_EQ("aaa(aaaa,\n"
7558             "    aaaa,\n"
7559             "    aaaa);\n"
7560             "aaa(aaaa,\n"
7561             "    aaaa,\n"
7562             "    aaaa);",
7563             format("aaa(aaaa,\n" // one-per-line
7564                    "  aaaa,\n"
7565                    "    aaaa  );\n"
7566                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7567                    Style));
7568   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7569             "    aaaa);\n"
7570             "aaa(aaaa, aaaa,\n"
7571             "    aaaa);",
7572             format("aaa(aaaa,  aaaa,\n" // bin-packed
7573                    "    aaaa  );\n"
7574                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7575                    Style));
7576 }
7577 
7578 TEST_F(FormatTest, FormatsBuilderPattern) {
7579   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7580                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7581                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7582                "    .StartsWith(\".init\", ORDER_INIT)\n"
7583                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7584                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7585                "    .Default(ORDER_TEXT);\n");
7586 
7587   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7588                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7589   verifyFormat("aaaaaaa->aaaaaaa\n"
7590                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7591                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7592                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7593   verifyFormat(
7594       "aaaaaaa->aaaaaaa\n"
7595       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7596       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7597   verifyFormat(
7598       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7599       "    aaaaaaaaaaaaaa);");
7600   verifyFormat(
7601       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7602       "    aaaaaa->aaaaaaaaaaaa()\n"
7603       "        ->aaaaaaaaaaaaaaaa(\n"
7604       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7605       "        ->aaaaaaaaaaaaaaaaa();");
7606   verifyGoogleFormat(
7607       "void f() {\n"
7608       "  someo->Add((new util::filetools::Handler(dir))\n"
7609       "                 ->OnEvent1(NewPermanentCallback(\n"
7610       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7611       "                 ->OnEvent2(NewPermanentCallback(\n"
7612       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7613       "                 ->OnEvent3(NewPermanentCallback(\n"
7614       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7615       "                 ->OnEvent5(NewPermanentCallback(\n"
7616       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7617       "                 ->OnEvent6(NewPermanentCallback(\n"
7618       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7619       "}");
7620 
7621   verifyFormat(
7622       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7623   verifyFormat("aaaaaaaaaaaaaaa()\n"
7624                "    .aaaaaaaaaaaaaaa()\n"
7625                "    .aaaaaaaaaaaaaaa()\n"
7626                "    .aaaaaaaaaaaaaaa()\n"
7627                "    .aaaaaaaaaaaaaaa();");
7628   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7629                "    .aaaaaaaaaaaaaaa()\n"
7630                "    .aaaaaaaaaaaaaaa()\n"
7631                "    .aaaaaaaaaaaaaaa();");
7632   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7633                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7634                "    .aaaaaaaaaaaaaaa();");
7635   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7636                "    ->aaaaaaaaaaaaaae(0)\n"
7637                "    ->aaaaaaaaaaaaaaa();");
7638 
7639   // Don't linewrap after very short segments.
7640   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7641                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7642                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7643   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7644                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7645                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7646   verifyFormat("aaa()\n"
7647                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7648                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7649                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7650 
7651   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7652                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7653                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7654   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7655                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7656                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7657 
7658   // Prefer not to break after empty parentheses.
7659   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7660                "    First->LastNewlineOffset);");
7661 
7662   // Prefer not to create "hanging" indents.
7663   verifyFormat(
7664       "return !soooooooooooooome_map\n"
7665       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7666       "            .second;");
7667   verifyFormat(
7668       "return aaaaaaaaaaaaaaaa\n"
7669       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7670       "    .aaaa(aaaaaaaaaaaaaa);");
7671   // No hanging indent here.
7672   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7673                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7674   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7675                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7676   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7677                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7678                getLLVMStyleWithColumns(60));
7679   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7680                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7681                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7682                getLLVMStyleWithColumns(59));
7683   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7684                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7685                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7686 
7687   // Dont break if only closing statements before member call
7688   verifyFormat("test() {\n"
7689                "  ([]() -> {\n"
7690                "    int b = 32;\n"
7691                "    return 3;\n"
7692                "  }).foo();\n"
7693                "}");
7694   verifyFormat("test() {\n"
7695                "  (\n"
7696                "      []() -> {\n"
7697                "        int b = 32;\n"
7698                "        return 3;\n"
7699                "      },\n"
7700                "      foo, bar)\n"
7701                "      .foo();\n"
7702                "}");
7703   verifyFormat("test() {\n"
7704                "  ([]() -> {\n"
7705                "    int b = 32;\n"
7706                "    return 3;\n"
7707                "  })\n"
7708                "      .foo()\n"
7709                "      .bar();\n"
7710                "}");
7711   verifyFormat("test() {\n"
7712                "  ([]() -> {\n"
7713                "    int b = 32;\n"
7714                "    return 3;\n"
7715                "  })\n"
7716                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7717                "           \"bbbb\");\n"
7718                "}",
7719                getLLVMStyleWithColumns(30));
7720 }
7721 
7722 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7723   verifyFormat(
7724       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7725       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7726   verifyFormat(
7727       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7728       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7729 
7730   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7731                "    ccccccccccccccccccccccccc) {\n}");
7732   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7733                "    ccccccccccccccccccccccccc) {\n}");
7734 
7735   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7736                "    ccccccccccccccccccccccccc) {\n}");
7737   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7738                "    ccccccccccccccccccccccccc) {\n}");
7739 
7740   verifyFormat(
7741       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7742       "    ccccccccccccccccccccccccc) {\n}");
7743   verifyFormat(
7744       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7745       "    ccccccccccccccccccccccccc) {\n}");
7746 
7747   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7748                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7749                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7750                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7751   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7752                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7753                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7754                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7755 
7756   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7757                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7758                "    aaaaaaaaaaaaaaa != aa) {\n}");
7759   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7760                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7761                "    aaaaaaaaaaaaaaa != aa) {\n}");
7762 }
7763 
7764 TEST_F(FormatTest, BreaksAfterAssignments) {
7765   verifyFormat(
7766       "unsigned Cost =\n"
7767       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7768       "                        SI->getPointerAddressSpaceee());\n");
7769   verifyFormat(
7770       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7771       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7772 
7773   verifyFormat(
7774       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7775       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7776   verifyFormat("unsigned OriginalStartColumn =\n"
7777                "    SourceMgr.getSpellingColumnNumber(\n"
7778                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7779                "    1;");
7780 }
7781 
7782 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7783   FormatStyle Style = getLLVMStyle();
7784   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7785                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7786                Style);
7787 
7788   Style.PenaltyBreakAssignment = 20;
7789   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7790                "                                 cccccccccccccccccccccccccc;",
7791                Style);
7792 }
7793 
7794 TEST_F(FormatTest, AlignsAfterAssignments) {
7795   verifyFormat(
7796       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7797       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7798   verifyFormat(
7799       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7800       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7801   verifyFormat(
7802       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7803       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7804   verifyFormat(
7805       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7806       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7807   verifyFormat(
7808       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7809       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7810       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7811 }
7812 
7813 TEST_F(FormatTest, AlignsAfterReturn) {
7814   verifyFormat(
7815       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7816       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7817   verifyFormat(
7818       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7819       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7820   verifyFormat(
7821       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7822       "       aaaaaaaaaaaaaaaaaaaaaa();");
7823   verifyFormat(
7824       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7825       "        aaaaaaaaaaaaaaaaaaaaaa());");
7826   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7827                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7828   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7829                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7830                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7831   verifyFormat("return\n"
7832                "    // true if code is one of a or b.\n"
7833                "    code == a || code == b;");
7834 }
7835 
7836 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7837   verifyFormat(
7838       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7839       "                                                aaaaaaaaa aaaaaaa) {}");
7840   verifyFormat(
7841       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7842       "                                               aaaaaaaaaaa aaaaaaaaa);");
7843   verifyFormat(
7844       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7845       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7846   FormatStyle Style = getLLVMStyle();
7847   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7848   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7849                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7850                Style);
7851   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7852                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
7853                Style);
7854   verifyFormat("SomeLongVariableName->someFunction(\n"
7855                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
7856                Style);
7857   verifyFormat(
7858       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7859       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7860       Style);
7861   verifyFormat(
7862       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7863       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7864       Style);
7865   verifyFormat(
7866       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7867       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7868       Style);
7869 
7870   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
7871                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
7872                "        b));",
7873                Style);
7874 
7875   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7876   Style.BinPackArguments = false;
7877   Style.BinPackParameters = false;
7878   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7879                "    aaaaaaaaaaa aaaaaaaa,\n"
7880                "    aaaaaaaaa aaaaaaa,\n"
7881                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7882                Style);
7883   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7884                "    aaaaaaaaaaa aaaaaaaaa,\n"
7885                "    aaaaaaaaaaa aaaaaaaaa,\n"
7886                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7887                Style);
7888   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
7889                "    aaaaaaaaaaaaaaa,\n"
7890                "    aaaaaaaaaaaaaaaaaaaaa,\n"
7891                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7892                Style);
7893   verifyFormat(
7894       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
7895       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7896       Style);
7897   verifyFormat(
7898       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
7899       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7900       Style);
7901   verifyFormat(
7902       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7903       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7904       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
7905       "    aaaaaaaaaaaaaaaa);",
7906       Style);
7907   verifyFormat(
7908       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7909       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7910       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
7911       "    aaaaaaaaaaaaaaaa);",
7912       Style);
7913 }
7914 
7915 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
7916   FormatStyle Style = getLLVMStyleWithColumns(40);
7917   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7918                "          bbbbbbbbbbbbbbbbbbbbbb);",
7919                Style);
7920   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7921   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7922   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7923                "          bbbbbbbbbbbbbbbbbbbbbb);",
7924                Style);
7925   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7926   Style.AlignOperands = FormatStyle::OAS_Align;
7927   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7928                "          bbbbbbbbbbbbbbbbbbbbbb);",
7929                Style);
7930   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7931   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7932   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7933                "    bbbbbbbbbbbbbbbbbbbbbb);",
7934                Style);
7935 }
7936 
7937 TEST_F(FormatTest, BreaksConditionalExpressions) {
7938   verifyFormat(
7939       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7940       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7941       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7942   verifyFormat(
7943       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7944       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7945       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7946   verifyFormat(
7947       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7948       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7949   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
7950                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7951                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7952   verifyFormat(
7953       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
7954       "                                                    : aaaaaaaaaaaaa);");
7955   verifyFormat(
7956       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7957       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7958       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7959       "                   aaaaaaaaaaaaa);");
7960   verifyFormat(
7961       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7962       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7963       "                   aaaaaaaaaaaaa);");
7964   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7965                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7966                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7967                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7968                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7969   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7970                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7971                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7972                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7973                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7974                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7975                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7976   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7977                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7978                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7979                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7980                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7981   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7982                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7983                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7984   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7985                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7986                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7987                "        : aaaaaaaaaaaaaaaa;");
7988   verifyFormat(
7989       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7990       "    ? aaaaaaaaaaaaaaa\n"
7991       "    : aaaaaaaaaaaaaaa;");
7992   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7993                "          aaaaaaaaa\n"
7994                "      ? b\n"
7995                "      : c);");
7996   verifyFormat("return aaaa == bbbb\n"
7997                "           // comment\n"
7998                "           ? aaaa\n"
7999                "           : bbbb;");
8000   verifyFormat("unsigned Indent =\n"
8001                "    format(TheLine.First,\n"
8002                "           IndentForLevel[TheLine.Level] >= 0\n"
8003                "               ? IndentForLevel[TheLine.Level]\n"
8004                "               : TheLine * 2,\n"
8005                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8006                getLLVMStyleWithColumns(60));
8007   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8008                "                  ? aaaaaaaaaaaaaaa\n"
8009                "                  : bbbbbbbbbbbbbbb //\n"
8010                "                        ? ccccccccccccccc\n"
8011                "                        : ddddddddddddddd;");
8012   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8013                "                  ? aaaaaaaaaaaaaaa\n"
8014                "                  : (bbbbbbbbbbbbbbb //\n"
8015                "                         ? ccccccccccccccc\n"
8016                "                         : ddddddddddddddd);");
8017   verifyFormat(
8018       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8019       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8020       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
8021       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
8022       "                                      : aaaaaaaaaa;");
8023   verifyFormat(
8024       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8025       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
8026       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8027 
8028   FormatStyle NoBinPacking = getLLVMStyle();
8029   NoBinPacking.BinPackArguments = false;
8030   verifyFormat(
8031       "void f() {\n"
8032       "  g(aaa,\n"
8033       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8034       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8035       "        ? aaaaaaaaaaaaaaa\n"
8036       "        : aaaaaaaaaaaaaaa);\n"
8037       "}",
8038       NoBinPacking);
8039   verifyFormat(
8040       "void f() {\n"
8041       "  g(aaa,\n"
8042       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8043       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8044       "        ?: aaaaaaaaaaaaaaa);\n"
8045       "}",
8046       NoBinPacking);
8047 
8048   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
8049                "             // comment.\n"
8050                "             ccccccccccccccccccccccccccccccccccccccc\n"
8051                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8052                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
8053 
8054   // Assignments in conditional expressions. Apparently not uncommon :-(.
8055   verifyFormat("return a != b\n"
8056                "           // comment\n"
8057                "           ? a = b\n"
8058                "           : a = b;");
8059   verifyFormat("return a != b\n"
8060                "           // comment\n"
8061                "           ? a = a != b\n"
8062                "                     // comment\n"
8063                "                     ? a = b\n"
8064                "                     : a\n"
8065                "           : a;\n");
8066   verifyFormat("return a != b\n"
8067                "           // comment\n"
8068                "           ? a\n"
8069                "           : a = a != b\n"
8070                "                     // comment\n"
8071                "                     ? a = b\n"
8072                "                     : a;");
8073 
8074   // Chained conditionals
8075   FormatStyle Style = getLLVMStyleWithColumns(70);
8076   Style.AlignOperands = FormatStyle::OAS_Align;
8077   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8078                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8079                "                        : 3333333333333333;",
8080                Style);
8081   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8082                "       : bbbbbbbbbb     ? 2222222222222222\n"
8083                "                        : 3333333333333333;",
8084                Style);
8085   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
8086                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
8087                "                          : 3333333333333333;",
8088                Style);
8089   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8090                "       : bbbbbbbbbbbbbb ? 222222\n"
8091                "                        : 333333;",
8092                Style);
8093   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8094                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8095                "       : cccccccccccccc ? 3333333333333333\n"
8096                "                        : 4444444444444444;",
8097                Style);
8098   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
8099                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8100                "                        : 3333333333333333;",
8101                Style);
8102   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8103                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8104                "                        : (aaa ? bbb : ccc);",
8105                Style);
8106   verifyFormat(
8107       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8108       "                                             : cccccccccccccccccc)\n"
8109       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8110       "                        : 3333333333333333;",
8111       Style);
8112   verifyFormat(
8113       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8114       "                                             : cccccccccccccccccc)\n"
8115       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8116       "                        : 3333333333333333;",
8117       Style);
8118   verifyFormat(
8119       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8120       "                                             : dddddddddddddddddd)\n"
8121       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8122       "                        : 3333333333333333;",
8123       Style);
8124   verifyFormat(
8125       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8126       "                                             : dddddddddddddddddd)\n"
8127       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8128       "                        : 3333333333333333;",
8129       Style);
8130   verifyFormat(
8131       "return aaaaaaaaa        ? 1111111111111111\n"
8132       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8133       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8134       "                                             : dddddddddddddddddd)\n",
8135       Style);
8136   verifyFormat(
8137       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8138       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8139       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8140       "                                             : cccccccccccccccccc);",
8141       Style);
8142   verifyFormat(
8143       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8144       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8145       "                                             : eeeeeeeeeeeeeeeeee)\n"
8146       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8147       "                        : 3333333333333333;",
8148       Style);
8149   verifyFormat(
8150       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
8151       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8152       "                                             : eeeeeeeeeeeeeeeeee)\n"
8153       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8154       "                        : 3333333333333333;",
8155       Style);
8156   verifyFormat(
8157       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8158       "                           : cccccccccccc    ? dddddddddddddddddd\n"
8159       "                                             : eeeeeeeeeeeeeeeeee)\n"
8160       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8161       "                        : 3333333333333333;",
8162       Style);
8163   verifyFormat(
8164       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8165       "                                             : cccccccccccccccccc\n"
8166       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8167       "                        : 3333333333333333;",
8168       Style);
8169   verifyFormat(
8170       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8171       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
8172       "                                             : eeeeeeeeeeeeeeeeee\n"
8173       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8174       "                        : 3333333333333333;",
8175       Style);
8176   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
8177                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
8178                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
8179                "                                   : eeeeeeeeeeeeeeeeee)\n"
8180                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8181                "                             : 3333333333333333;",
8182                Style);
8183   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
8184                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8185                "             : cccccccccccccccc ? dddddddddddddddddd\n"
8186                "                                : eeeeeeeeeeeeeeeeee\n"
8187                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8188                "                                 : 3333333333333333;",
8189                Style);
8190 
8191   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8192   Style.BreakBeforeTernaryOperators = false;
8193   // FIXME: Aligning the question marks is weird given DontAlign.
8194   // Consider disabling this alignment in this case. Also check whether this
8195   // will render the adjustment from https://reviews.llvm.org/D82199
8196   // unnecessary.
8197   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
8198                "    bbbb                ? cccccccccccccccccc :\n"
8199                "                          ddddd;\n",
8200                Style);
8201 
8202   EXPECT_EQ(
8203       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8204       "    /*\n"
8205       "     */\n"
8206       "    function() {\n"
8207       "      try {\n"
8208       "        return JJJJJJJJJJJJJJ(\n"
8209       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8210       "      }\n"
8211       "    } :\n"
8212       "    function() {};",
8213       format(
8214           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8215           "     /*\n"
8216           "      */\n"
8217           "     function() {\n"
8218           "      try {\n"
8219           "        return JJJJJJJJJJJJJJ(\n"
8220           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8221           "      }\n"
8222           "    } :\n"
8223           "    function() {};",
8224           getGoogleStyle(FormatStyle::LK_JavaScript)));
8225 }
8226 
8227 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
8228   FormatStyle Style = getLLVMStyleWithColumns(70);
8229   Style.BreakBeforeTernaryOperators = false;
8230   verifyFormat(
8231       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8232       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8233       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8234       Style);
8235   verifyFormat(
8236       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8237       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8238       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8239       Style);
8240   verifyFormat(
8241       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8242       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8243       Style);
8244   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
8245                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8246                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8247                Style);
8248   verifyFormat(
8249       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
8250       "                                                      aaaaaaaaaaaaa);",
8251       Style);
8252   verifyFormat(
8253       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8254       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8255       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8256       "                   aaaaaaaaaaaaa);",
8257       Style);
8258   verifyFormat(
8259       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8260       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8261       "                   aaaaaaaaaaaaa);",
8262       Style);
8263   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8264                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8265                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8266                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8267                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8268                Style);
8269   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8270                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8271                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8272                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8273                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8274                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8275                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8276                Style);
8277   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8278                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8279                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8280                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8281                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8282                Style);
8283   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8284                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8285                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8286                Style);
8287   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8288                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8289                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8290                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8291                Style);
8292   verifyFormat(
8293       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8294       "    aaaaaaaaaaaaaaa :\n"
8295       "    aaaaaaaaaaaaaaa;",
8296       Style);
8297   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8298                "          aaaaaaaaa ?\n"
8299                "      b :\n"
8300                "      c);",
8301                Style);
8302   verifyFormat("unsigned Indent =\n"
8303                "    format(TheLine.First,\n"
8304                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8305                "               IndentForLevel[TheLine.Level] :\n"
8306                "               TheLine * 2,\n"
8307                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8308                Style);
8309   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8310                "                  aaaaaaaaaaaaaaa :\n"
8311                "                  bbbbbbbbbbbbbbb ? //\n"
8312                "                      ccccccccccccccc :\n"
8313                "                      ddddddddddddddd;",
8314                Style);
8315   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8316                "                  aaaaaaaaaaaaaaa :\n"
8317                "                  (bbbbbbbbbbbbbbb ? //\n"
8318                "                       ccccccccccccccc :\n"
8319                "                       ddddddddddddddd);",
8320                Style);
8321   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8322                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8323                "            ccccccccccccccccccccccccccc;",
8324                Style);
8325   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8326                "           aaaaa :\n"
8327                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8328                Style);
8329 
8330   // Chained conditionals
8331   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8332                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8333                "                          3333333333333333;",
8334                Style);
8335   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8336                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8337                "                          3333333333333333;",
8338                Style);
8339   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8340                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8341                "                          3333333333333333;",
8342                Style);
8343   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8344                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8345                "                          333333;",
8346                Style);
8347   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8348                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8349                "       cccccccccccccccc ? 3333333333333333 :\n"
8350                "                          4444444444444444;",
8351                Style);
8352   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8353                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8354                "                          3333333333333333;",
8355                Style);
8356   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8357                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8358                "                          (aaa ? bbb : ccc);",
8359                Style);
8360   verifyFormat(
8361       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8362       "                                               cccccccccccccccccc) :\n"
8363       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8364       "                          3333333333333333;",
8365       Style);
8366   verifyFormat(
8367       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8368       "                                               cccccccccccccccccc) :\n"
8369       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8370       "                          3333333333333333;",
8371       Style);
8372   verifyFormat(
8373       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8374       "                                               dddddddddddddddddd) :\n"
8375       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8376       "                          3333333333333333;",
8377       Style);
8378   verifyFormat(
8379       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8380       "                                               dddddddddddddddddd) :\n"
8381       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8382       "                          3333333333333333;",
8383       Style);
8384   verifyFormat(
8385       "return aaaaaaaaa        ? 1111111111111111 :\n"
8386       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8387       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8388       "                                               dddddddddddddddddd)\n",
8389       Style);
8390   verifyFormat(
8391       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8392       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8393       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8394       "                                               cccccccccccccccccc);",
8395       Style);
8396   verifyFormat(
8397       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8398       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8399       "                                               eeeeeeeeeeeeeeeeee) :\n"
8400       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8401       "                          3333333333333333;",
8402       Style);
8403   verifyFormat(
8404       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8405       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8406       "                                               eeeeeeeeeeeeeeeeee) :\n"
8407       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8408       "                          3333333333333333;",
8409       Style);
8410   verifyFormat(
8411       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8412       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8413       "                                               eeeeeeeeeeeeeeeeee) :\n"
8414       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8415       "                          3333333333333333;",
8416       Style);
8417   verifyFormat(
8418       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8419       "                                               cccccccccccccccccc :\n"
8420       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8421       "                          3333333333333333;",
8422       Style);
8423   verifyFormat(
8424       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8425       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8426       "                                               eeeeeeeeeeeeeeeeee :\n"
8427       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8428       "                          3333333333333333;",
8429       Style);
8430   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8431                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8432                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8433                "                                 eeeeeeeeeeeeeeeeee) :\n"
8434                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8435                "                               3333333333333333;",
8436                Style);
8437   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8438                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8439                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8440                "                                  eeeeeeeeeeeeeeeeee :\n"
8441                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8442                "                               3333333333333333;",
8443                Style);
8444 }
8445 
8446 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8447   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8448                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8449   verifyFormat("bool a = true, b = false;");
8450 
8451   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8452                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8453                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8454                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8455   verifyFormat(
8456       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8457       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8458       "     d = e && f;");
8459   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8460                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8461   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8462                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8463   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8464                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8465 
8466   FormatStyle Style = getGoogleStyle();
8467   Style.PointerAlignment = FormatStyle::PAS_Left;
8468   Style.DerivePointerAlignment = false;
8469   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8470                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8471                "    *b = bbbbbbbbbbbbbbbbbbb;",
8472                Style);
8473   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8474                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8475                Style);
8476   verifyFormat("vector<int*> a, b;", Style);
8477   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8478   verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
8479   verifyFormat("if (int *p, *q; p != q) {\n  p = p->next;\n}", Style);
8480   verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n  p = p->next;\n}",
8481                Style);
8482   verifyFormat("switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8483                Style);
8484   verifyFormat(
8485       "/*comment*/ switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8486       Style);
8487 
8488   verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
8489   verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
8490   verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
8491   verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
8492   verifyFormat("switch ([](int* p, int* q) {}()) {\n  default:\n    break;\n}",
8493                Style);
8494 }
8495 
8496 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8497   verifyFormat("arr[foo ? bar : baz];");
8498   verifyFormat("f()[foo ? bar : baz];");
8499   verifyFormat("(a + b)[foo ? bar : baz];");
8500   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8501 }
8502 
8503 TEST_F(FormatTest, AlignsStringLiterals) {
8504   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8505                "                                      \"short literal\");");
8506   verifyFormat(
8507       "looooooooooooooooooooooooongFunction(\n"
8508       "    \"short literal\"\n"
8509       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8510   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8511                "             \" string literals\",\n"
8512                "             and, other, parameters);");
8513   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8514             "      \"5678\";",
8515             format("fun + \"1243\" /* comment */\n"
8516                    "    \"5678\";",
8517                    getLLVMStyleWithColumns(28)));
8518   EXPECT_EQ(
8519       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8520       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8521       "         \"aaaaaaaaaaaaaaaa\";",
8522       format("aaaaaa ="
8523              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8524              "aaaaaaaaaaaaaaaaaaaaa\" "
8525              "\"aaaaaaaaaaaaaaaa\";"));
8526   verifyFormat("a = a + \"a\"\n"
8527                "        \"a\"\n"
8528                "        \"a\";");
8529   verifyFormat("f(\"a\", \"b\"\n"
8530                "       \"c\");");
8531 
8532   verifyFormat(
8533       "#define LL_FORMAT \"ll\"\n"
8534       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8535       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8536 
8537   verifyFormat("#define A(X)          \\\n"
8538                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8539                "  \"ccccc\"",
8540                getLLVMStyleWithColumns(23));
8541   verifyFormat("#define A \"def\"\n"
8542                "f(\"abc\" A \"ghi\"\n"
8543                "  \"jkl\");");
8544 
8545   verifyFormat("f(L\"a\"\n"
8546                "  L\"b\");");
8547   verifyFormat("#define A(X)            \\\n"
8548                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8549                "  L\"ccccc\"",
8550                getLLVMStyleWithColumns(25));
8551 
8552   verifyFormat("f(@\"a\"\n"
8553                "  @\"b\");");
8554   verifyFormat("NSString s = @\"a\"\n"
8555                "             @\"b\"\n"
8556                "             @\"c\";");
8557   verifyFormat("NSString s = @\"a\"\n"
8558                "              \"b\"\n"
8559                "              \"c\";");
8560 }
8561 
8562 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8563   FormatStyle Style = getLLVMStyle();
8564   // No declarations or definitions should be moved to own line.
8565   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8566   verifyFormat("class A {\n"
8567                "  int f() { return 1; }\n"
8568                "  int g();\n"
8569                "};\n"
8570                "int f() { return 1; }\n"
8571                "int g();\n",
8572                Style);
8573 
8574   // All declarations and definitions should have the return type moved to its
8575   // own line.
8576   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8577   Style.TypenameMacros = {"LIST"};
8578   verifyFormat("SomeType\n"
8579                "funcdecl(LIST(uint64_t));",
8580                Style);
8581   verifyFormat("class E {\n"
8582                "  int\n"
8583                "  f() {\n"
8584                "    return 1;\n"
8585                "  }\n"
8586                "  int\n"
8587                "  g();\n"
8588                "};\n"
8589                "int\n"
8590                "f() {\n"
8591                "  return 1;\n"
8592                "}\n"
8593                "int\n"
8594                "g();\n",
8595                Style);
8596 
8597   // Top-level definitions, and no kinds of declarations should have the
8598   // return type moved to its own line.
8599   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8600   verifyFormat("class B {\n"
8601                "  int f() { return 1; }\n"
8602                "  int g();\n"
8603                "};\n"
8604                "int\n"
8605                "f() {\n"
8606                "  return 1;\n"
8607                "}\n"
8608                "int g();\n",
8609                Style);
8610 
8611   // Top-level definitions and declarations should have the return type moved
8612   // to its own line.
8613   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8614   verifyFormat("class C {\n"
8615                "  int f() { return 1; }\n"
8616                "  int g();\n"
8617                "};\n"
8618                "int\n"
8619                "f() {\n"
8620                "  return 1;\n"
8621                "}\n"
8622                "int\n"
8623                "g();\n",
8624                Style);
8625 
8626   // All definitions should have the return type moved to its own line, but no
8627   // kinds of declarations.
8628   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8629   verifyFormat("class D {\n"
8630                "  int\n"
8631                "  f() {\n"
8632                "    return 1;\n"
8633                "  }\n"
8634                "  int g();\n"
8635                "};\n"
8636                "int\n"
8637                "f() {\n"
8638                "  return 1;\n"
8639                "}\n"
8640                "int g();\n",
8641                Style);
8642   verifyFormat("const char *\n"
8643                "f(void) {\n" // Break here.
8644                "  return \"\";\n"
8645                "}\n"
8646                "const char *bar(void);\n", // No break here.
8647                Style);
8648   verifyFormat("template <class T>\n"
8649                "T *\n"
8650                "f(T &c) {\n" // Break here.
8651                "  return NULL;\n"
8652                "}\n"
8653                "template <class T> T *f(T &c);\n", // No break here.
8654                Style);
8655   verifyFormat("class C {\n"
8656                "  int\n"
8657                "  operator+() {\n"
8658                "    return 1;\n"
8659                "  }\n"
8660                "  int\n"
8661                "  operator()() {\n"
8662                "    return 1;\n"
8663                "  }\n"
8664                "};\n",
8665                Style);
8666   verifyFormat("void\n"
8667                "A::operator()() {}\n"
8668                "void\n"
8669                "A::operator>>() {}\n"
8670                "void\n"
8671                "A::operator+() {}\n"
8672                "void\n"
8673                "A::operator*() {}\n"
8674                "void\n"
8675                "A::operator->() {}\n"
8676                "void\n"
8677                "A::operator void *() {}\n"
8678                "void\n"
8679                "A::operator void &() {}\n"
8680                "void\n"
8681                "A::operator void &&() {}\n"
8682                "void\n"
8683                "A::operator char *() {}\n"
8684                "void\n"
8685                "A::operator[]() {}\n"
8686                "void\n"
8687                "A::operator!() {}\n"
8688                "void\n"
8689                "A::operator**() {}\n"
8690                "void\n"
8691                "A::operator<Foo> *() {}\n"
8692                "void\n"
8693                "A::operator<Foo> **() {}\n"
8694                "void\n"
8695                "A::operator<Foo> &() {}\n"
8696                "void\n"
8697                "A::operator void **() {}\n",
8698                Style);
8699   verifyFormat("constexpr auto\n"
8700                "operator()() const -> reference {}\n"
8701                "constexpr auto\n"
8702                "operator>>() const -> reference {}\n"
8703                "constexpr auto\n"
8704                "operator+() const -> reference {}\n"
8705                "constexpr auto\n"
8706                "operator*() const -> reference {}\n"
8707                "constexpr auto\n"
8708                "operator->() const -> reference {}\n"
8709                "constexpr auto\n"
8710                "operator++() const -> reference {}\n"
8711                "constexpr auto\n"
8712                "operator void *() const -> reference {}\n"
8713                "constexpr auto\n"
8714                "operator void **() const -> reference {}\n"
8715                "constexpr auto\n"
8716                "operator void *() const -> reference {}\n"
8717                "constexpr auto\n"
8718                "operator void &() const -> reference {}\n"
8719                "constexpr auto\n"
8720                "operator void &&() const -> reference {}\n"
8721                "constexpr auto\n"
8722                "operator char *() const -> reference {}\n"
8723                "constexpr auto\n"
8724                "operator!() const -> reference {}\n"
8725                "constexpr auto\n"
8726                "operator[]() const -> reference {}\n",
8727                Style);
8728   verifyFormat("void *operator new(std::size_t s);", // No break here.
8729                Style);
8730   verifyFormat("void *\n"
8731                "operator new(std::size_t s) {}",
8732                Style);
8733   verifyFormat("void *\n"
8734                "operator delete[](void *ptr) {}",
8735                Style);
8736   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8737   verifyFormat("const char *\n"
8738                "f(void)\n" // Break here.
8739                "{\n"
8740                "  return \"\";\n"
8741                "}\n"
8742                "const char *bar(void);\n", // No break here.
8743                Style);
8744   verifyFormat("template <class T>\n"
8745                "T *\n"     // Problem here: no line break
8746                "f(T &c)\n" // Break here.
8747                "{\n"
8748                "  return NULL;\n"
8749                "}\n"
8750                "template <class T> T *f(T &c);\n", // No break here.
8751                Style);
8752   verifyFormat("int\n"
8753                "foo(A<bool> a)\n"
8754                "{\n"
8755                "  return a;\n"
8756                "}\n",
8757                Style);
8758   verifyFormat("int\n"
8759                "foo(A<8> a)\n"
8760                "{\n"
8761                "  return a;\n"
8762                "}\n",
8763                Style);
8764   verifyFormat("int\n"
8765                "foo(A<B<bool>, 8> a)\n"
8766                "{\n"
8767                "  return a;\n"
8768                "}\n",
8769                Style);
8770   verifyFormat("int\n"
8771                "foo(A<B<8>, bool> a)\n"
8772                "{\n"
8773                "  return a;\n"
8774                "}\n",
8775                Style);
8776   verifyFormat("int\n"
8777                "foo(A<B<bool>, bool> a)\n"
8778                "{\n"
8779                "  return a;\n"
8780                "}\n",
8781                Style);
8782   verifyFormat("int\n"
8783                "foo(A<B<8>, 8> a)\n"
8784                "{\n"
8785                "  return a;\n"
8786                "}\n",
8787                Style);
8788 
8789   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8790   Style.BraceWrapping.AfterFunction = true;
8791   verifyFormat("int f(i);\n" // No break here.
8792                "int\n"       // Break here.
8793                "f(i)\n"
8794                "{\n"
8795                "  return i + 1;\n"
8796                "}\n"
8797                "int\n" // Break here.
8798                "f(i)\n"
8799                "{\n"
8800                "  return i + 1;\n"
8801                "};",
8802                Style);
8803   verifyFormat("int f(a, b, c);\n" // No break here.
8804                "int\n"             // Break here.
8805                "f(a, b, c)\n"      // Break here.
8806                "short a, b;\n"
8807                "float c;\n"
8808                "{\n"
8809                "  return a + b < c;\n"
8810                "}\n"
8811                "int\n"        // Break here.
8812                "f(a, b, c)\n" // Break here.
8813                "short a, b;\n"
8814                "float c;\n"
8815                "{\n"
8816                "  return a + b < c;\n"
8817                "};",
8818                Style);
8819   verifyFormat("byte *\n" // Break here.
8820                "f(a)\n"   // Break here.
8821                "byte a[];\n"
8822                "{\n"
8823                "  return a;\n"
8824                "}",
8825                Style);
8826   verifyFormat("bool f(int a, int) override;\n"
8827                "Bar g(int a, Bar) final;\n"
8828                "Bar h(a, Bar) final;",
8829                Style);
8830   verifyFormat("int\n"
8831                "f(a)",
8832                Style);
8833   verifyFormat("bool\n"
8834                "f(size_t = 0, bool b = false)\n"
8835                "{\n"
8836                "  return !b;\n"
8837                "}",
8838                Style);
8839 
8840   // The return breaking style doesn't affect:
8841   // * function and object definitions with attribute-like macros
8842   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8843                "    ABSL_GUARDED_BY(mutex) = {};",
8844                getGoogleStyleWithColumns(40));
8845   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8846                "    ABSL_GUARDED_BY(mutex);  // comment",
8847                getGoogleStyleWithColumns(40));
8848   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8849                "    ABSL_GUARDED_BY(mutex1)\n"
8850                "        ABSL_GUARDED_BY(mutex2);",
8851                getGoogleStyleWithColumns(40));
8852   verifyFormat("Tttttt f(int a, int b)\n"
8853                "    ABSL_GUARDED_BY(mutex1)\n"
8854                "        ABSL_GUARDED_BY(mutex2);",
8855                getGoogleStyleWithColumns(40));
8856   // * typedefs
8857   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
8858 
8859   Style = getGNUStyle();
8860 
8861   // Test for comments at the end of function declarations.
8862   verifyFormat("void\n"
8863                "foo (int a, /*abc*/ int b) // def\n"
8864                "{\n"
8865                "}\n",
8866                Style);
8867 
8868   verifyFormat("void\n"
8869                "foo (int a, /* abc */ int b) /* def */\n"
8870                "{\n"
8871                "}\n",
8872                Style);
8873 
8874   // Definitions that should not break after return type
8875   verifyFormat("void foo (int a, int b); // def\n", Style);
8876   verifyFormat("void foo (int a, int b); /* def */\n", Style);
8877   verifyFormat("void foo (int a, int b);\n", Style);
8878 }
8879 
8880 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
8881   FormatStyle NoBreak = getLLVMStyle();
8882   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
8883   FormatStyle Break = getLLVMStyle();
8884   Break.AlwaysBreakBeforeMultilineStrings = true;
8885   verifyFormat("aaaa = \"bbbb\"\n"
8886                "       \"cccc\";",
8887                NoBreak);
8888   verifyFormat("aaaa =\n"
8889                "    \"bbbb\"\n"
8890                "    \"cccc\";",
8891                Break);
8892   verifyFormat("aaaa(\"bbbb\"\n"
8893                "     \"cccc\");",
8894                NoBreak);
8895   verifyFormat("aaaa(\n"
8896                "    \"bbbb\"\n"
8897                "    \"cccc\");",
8898                Break);
8899   verifyFormat("aaaa(qqq, \"bbbb\"\n"
8900                "          \"cccc\");",
8901                NoBreak);
8902   verifyFormat("aaaa(qqq,\n"
8903                "     \"bbbb\"\n"
8904                "     \"cccc\");",
8905                Break);
8906   verifyFormat("aaaa(qqq,\n"
8907                "     L\"bbbb\"\n"
8908                "     L\"cccc\");",
8909                Break);
8910   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
8911                "                      \"bbbb\"));",
8912                Break);
8913   verifyFormat("string s = someFunction(\n"
8914                "    \"abc\"\n"
8915                "    \"abc\");",
8916                Break);
8917 
8918   // As we break before unary operators, breaking right after them is bad.
8919   verifyFormat("string foo = abc ? \"x\"\n"
8920                "                   \"blah blah blah blah blah blah\"\n"
8921                "                 : \"y\";",
8922                Break);
8923 
8924   // Don't break if there is no column gain.
8925   verifyFormat("f(\"aaaa\"\n"
8926                "  \"bbbb\");",
8927                Break);
8928 
8929   // Treat literals with escaped newlines like multi-line string literals.
8930   EXPECT_EQ("x = \"a\\\n"
8931             "b\\\n"
8932             "c\";",
8933             format("x = \"a\\\n"
8934                    "b\\\n"
8935                    "c\";",
8936                    NoBreak));
8937   EXPECT_EQ("xxxx =\n"
8938             "    \"a\\\n"
8939             "b\\\n"
8940             "c\";",
8941             format("xxxx = \"a\\\n"
8942                    "b\\\n"
8943                    "c\";",
8944                    Break));
8945 
8946   EXPECT_EQ("NSString *const kString =\n"
8947             "    @\"aaaa\"\n"
8948             "    @\"bbbb\";",
8949             format("NSString *const kString = @\"aaaa\"\n"
8950                    "@\"bbbb\";",
8951                    Break));
8952 
8953   Break.ColumnLimit = 0;
8954   verifyFormat("const char *hello = \"hello llvm\";", Break);
8955 }
8956 
8957 TEST_F(FormatTest, AlignsPipes) {
8958   verifyFormat(
8959       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8960       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8961       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8962   verifyFormat(
8963       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
8964       "                     << aaaaaaaaaaaaaaaaaaaa;");
8965   verifyFormat(
8966       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8967       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8968   verifyFormat(
8969       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
8970       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8971   verifyFormat(
8972       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
8973       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
8974       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
8975   verifyFormat(
8976       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8977       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8978       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8979   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8980                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8981                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8982                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8983   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
8984                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
8985   verifyFormat(
8986       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8987       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8988   verifyFormat(
8989       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
8990       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
8991 
8992   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
8993                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
8994   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8995                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8996                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
8997                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
8998   verifyFormat("LOG_IF(aaa == //\n"
8999                "       bbb)\n"
9000                "    << a << b;");
9001 
9002   // But sometimes, breaking before the first "<<" is desirable.
9003   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9004                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
9005   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
9006                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9007                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9008   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
9009                "    << BEF << IsTemplate << Description << E->getType();");
9010   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9011                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9012                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9013   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9014                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9015                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9016                "    << aaa;");
9017 
9018   verifyFormat(
9019       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9020       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9021 
9022   // Incomplete string literal.
9023   EXPECT_EQ("llvm::errs() << \"\n"
9024             "             << a;",
9025             format("llvm::errs() << \"\n<<a;"));
9026 
9027   verifyFormat("void f() {\n"
9028                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
9029                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
9030                "}");
9031 
9032   // Handle 'endl'.
9033   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
9034                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9035   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9036 
9037   // Handle '\n'.
9038   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
9039                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9040   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
9041                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
9042   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
9043                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
9044   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9045 }
9046 
9047 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
9048   verifyFormat("return out << \"somepacket = {\\n\"\n"
9049                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
9050                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
9051                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
9052                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
9053                "           << \"}\";");
9054 
9055   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9056                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9057                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
9058   verifyFormat(
9059       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
9060       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
9061       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
9062       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
9063       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
9064   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
9065                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9066   verifyFormat(
9067       "void f() {\n"
9068       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
9069       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
9070       "}");
9071 
9072   // Breaking before the first "<<" is generally not desirable.
9073   verifyFormat(
9074       "llvm::errs()\n"
9075       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9076       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9077       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9078       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9079       getLLVMStyleWithColumns(70));
9080   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9081                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9082                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9083                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9084                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9085                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9086                getLLVMStyleWithColumns(70));
9087 
9088   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9089                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9090                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
9091   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9092                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9093                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
9094   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
9095                "           (aaaa + aaaa);",
9096                getLLVMStyleWithColumns(40));
9097   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
9098                "                  (aaaaaaa + aaaaa));",
9099                getLLVMStyleWithColumns(40));
9100   verifyFormat(
9101       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
9102       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
9103       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
9104 }
9105 
9106 TEST_F(FormatTest, UnderstandsEquals) {
9107   verifyFormat(
9108       "aaaaaaaaaaaaaaaaa =\n"
9109       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9110   verifyFormat(
9111       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9112       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9113   verifyFormat(
9114       "if (a) {\n"
9115       "  f();\n"
9116       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9117       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
9118       "}");
9119 
9120   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9121                "        100000000 + 10000000) {\n}");
9122 }
9123 
9124 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
9125   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9126                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
9127 
9128   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9129                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
9130 
9131   verifyFormat(
9132       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
9133       "                                                          Parameter2);");
9134 
9135   verifyFormat(
9136       "ShortObject->shortFunction(\n"
9137       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
9138       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
9139 
9140   verifyFormat("loooooooooooooongFunction(\n"
9141                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
9142 
9143   verifyFormat(
9144       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
9145       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
9146 
9147   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9148                "    .WillRepeatedly(Return(SomeValue));");
9149   verifyFormat("void f() {\n"
9150                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9151                "      .Times(2)\n"
9152                "      .WillRepeatedly(Return(SomeValue));\n"
9153                "}");
9154   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
9155                "    ccccccccccccccccccccccc);");
9156   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9157                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9158                "          .aaaaa(aaaaa),\n"
9159                "      aaaaaaaaaaaaaaaaaaaaa);");
9160   verifyFormat("void f() {\n"
9161                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9162                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
9163                "}");
9164   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9165                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9166                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9167                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9168                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9169   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9170                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9171                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9172                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
9173                "}");
9174 
9175   // Here, it is not necessary to wrap at "." or "->".
9176   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
9177                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9178   verifyFormat(
9179       "aaaaaaaaaaa->aaaaaaaaa(\n"
9180       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9181       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
9182 
9183   verifyFormat(
9184       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9185       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
9186   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
9187                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9188   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
9189                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9190 
9191   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9192                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9193                "    .a();");
9194 
9195   FormatStyle NoBinPacking = getLLVMStyle();
9196   NoBinPacking.BinPackParameters = false;
9197   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9198                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9199                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
9200                "                         aaaaaaaaaaaaaaaaaaa,\n"
9201                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
9202                NoBinPacking);
9203 
9204   // If there is a subsequent call, change to hanging indentation.
9205   verifyFormat(
9206       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9207       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
9208       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9209   verifyFormat(
9210       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9211       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
9212   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9213                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9214                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9215   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9216                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9217                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9218 }
9219 
9220 TEST_F(FormatTest, WrapsTemplateDeclarations) {
9221   verifyFormat("template <typename T>\n"
9222                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9223   verifyFormat("template <typename T>\n"
9224                "// T should be one of {A, B}.\n"
9225                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9226   verifyFormat(
9227       "template <typename T>\n"
9228       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
9229   verifyFormat("template <typename T>\n"
9230                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
9231                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
9232   verifyFormat(
9233       "template <typename T>\n"
9234       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
9235       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
9236   verifyFormat(
9237       "template <typename T>\n"
9238       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
9239       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
9240       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9241   verifyFormat("template <typename T>\n"
9242                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9243                "    int aaaaaaaaaaaaaaaaaaaaaa);");
9244   verifyFormat(
9245       "template <typename T1, typename T2 = char, typename T3 = char,\n"
9246       "          typename T4 = char>\n"
9247       "void f();");
9248   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
9249                "          template <typename> class cccccccccccccccccccccc,\n"
9250                "          typename ddddddddddddd>\n"
9251                "class C {};");
9252   verifyFormat(
9253       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
9254       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9255 
9256   verifyFormat("void f() {\n"
9257                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
9258                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
9259                "}");
9260 
9261   verifyFormat("template <typename T> class C {};");
9262   verifyFormat("template <typename T> void f();");
9263   verifyFormat("template <typename T> void f() {}");
9264   verifyFormat(
9265       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9266       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9267       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
9268       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9269       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9270       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
9271       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
9272       getLLVMStyleWithColumns(72));
9273   EXPECT_EQ("static_cast<A< //\n"
9274             "    B> *>(\n"
9275             "\n"
9276             ");",
9277             format("static_cast<A<//\n"
9278                    "    B>*>(\n"
9279                    "\n"
9280                    "    );"));
9281   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9282                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
9283 
9284   FormatStyle AlwaysBreak = getLLVMStyle();
9285   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9286   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
9287   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
9288   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
9289   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9290                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9291                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9292   verifyFormat("template <template <typename> class Fooooooo,\n"
9293                "          template <typename> class Baaaaaaar>\n"
9294                "struct C {};",
9295                AlwaysBreak);
9296   verifyFormat("template <typename T> // T can be A, B or C.\n"
9297                "struct C {};",
9298                AlwaysBreak);
9299   verifyFormat("template <enum E> class A {\n"
9300                "public:\n"
9301                "  E *f();\n"
9302                "};");
9303 
9304   FormatStyle NeverBreak = getLLVMStyle();
9305   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9306   verifyFormat("template <typename T> class C {};", NeverBreak);
9307   verifyFormat("template <typename T> void f();", NeverBreak);
9308   verifyFormat("template <typename T> void f() {}", NeverBreak);
9309   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9310                "bbbbbbbbbbbbbbbbbbbb) {}",
9311                NeverBreak);
9312   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9313                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9314                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9315                NeverBreak);
9316   verifyFormat("template <template <typename> class Fooooooo,\n"
9317                "          template <typename> class Baaaaaaar>\n"
9318                "struct C {};",
9319                NeverBreak);
9320   verifyFormat("template <typename T> // T can be A, B or C.\n"
9321                "struct C {};",
9322                NeverBreak);
9323   verifyFormat("template <enum E> class A {\n"
9324                "public:\n"
9325                "  E *f();\n"
9326                "};",
9327                NeverBreak);
9328   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9329   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9330                "bbbbbbbbbbbbbbbbbbbb) {}",
9331                NeverBreak);
9332 }
9333 
9334 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9335   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9336   Style.ColumnLimit = 60;
9337   EXPECT_EQ("// Baseline - no comments.\n"
9338             "template <\n"
9339             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9340             "void f() {}",
9341             format("// Baseline - no comments.\n"
9342                    "template <\n"
9343                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9344                    "void f() {}",
9345                    Style));
9346 
9347   EXPECT_EQ("template <\n"
9348             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9349             "void f() {}",
9350             format("template <\n"
9351                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9352                    "void f() {}",
9353                    Style));
9354 
9355   EXPECT_EQ(
9356       "template <\n"
9357       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9358       "void f() {}",
9359       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9360              "void f() {}",
9361              Style));
9362 
9363   EXPECT_EQ(
9364       "template <\n"
9365       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9366       "                                               // multiline\n"
9367       "void f() {}",
9368       format("template <\n"
9369              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9370              "                                              // multiline\n"
9371              "void f() {}",
9372              Style));
9373 
9374   EXPECT_EQ(
9375       "template <typename aaaaaaaaaa<\n"
9376       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9377       "void f() {}",
9378       format(
9379           "template <\n"
9380           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9381           "void f() {}",
9382           Style));
9383 }
9384 
9385 TEST_F(FormatTest, WrapsTemplateParameters) {
9386   FormatStyle Style = getLLVMStyle();
9387   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9388   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9389   verifyFormat(
9390       "template <typename... a> struct q {};\n"
9391       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9392       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9393       "    y;",
9394       Style);
9395   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9396   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9397   verifyFormat(
9398       "template <typename... a> struct r {};\n"
9399       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9400       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9401       "    y;",
9402       Style);
9403   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9404   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9405   verifyFormat("template <typename... a> struct s {};\n"
9406                "extern s<\n"
9407                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9408                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9409                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9410                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9411                "    y;",
9412                Style);
9413   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9414   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9415   verifyFormat("template <typename... a> struct t {};\n"
9416                "extern t<\n"
9417                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9418                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9419                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9420                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9421                "    y;",
9422                Style);
9423 }
9424 
9425 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9426   verifyFormat(
9427       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9428       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9429   verifyFormat(
9430       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9431       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9432       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9433 
9434   // FIXME: Should we have the extra indent after the second break?
9435   verifyFormat(
9436       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9437       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9438       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9439 
9440   verifyFormat(
9441       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9442       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9443 
9444   // Breaking at nested name specifiers is generally not desirable.
9445   verifyFormat(
9446       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9447       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9448 
9449   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9450                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9451                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9452                "                   aaaaaaaaaaaaaaaaaaaaa);",
9453                getLLVMStyleWithColumns(74));
9454 
9455   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9456                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9457                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9458 }
9459 
9460 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9461   verifyFormat("A<int> a;");
9462   verifyFormat("A<A<A<int>>> a;");
9463   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9464   verifyFormat("bool x = a < 1 || 2 > a;");
9465   verifyFormat("bool x = 5 < f<int>();");
9466   verifyFormat("bool x = f<int>() > 5;");
9467   verifyFormat("bool x = 5 < a<int>::x;");
9468   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9469   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9470 
9471   verifyGoogleFormat("A<A<int>> a;");
9472   verifyGoogleFormat("A<A<A<int>>> a;");
9473   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9474   verifyGoogleFormat("A<A<int> > a;");
9475   verifyGoogleFormat("A<A<A<int> > > a;");
9476   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9477   verifyGoogleFormat("A<::A<int>> a;");
9478   verifyGoogleFormat("A<::A> a;");
9479   verifyGoogleFormat("A< ::A> a;");
9480   verifyGoogleFormat("A< ::A<int> > a;");
9481   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9482   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9483   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9484   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9485   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9486             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9487 
9488   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9489 
9490   // template closer followed by a token that starts with > or =
9491   verifyFormat("bool b = a<1> > 1;");
9492   verifyFormat("bool b = a<1> >= 1;");
9493   verifyFormat("int i = a<1> >> 1;");
9494   FormatStyle Style = getLLVMStyle();
9495   Style.SpaceBeforeAssignmentOperators = false;
9496   verifyFormat("bool b= a<1> == 1;", Style);
9497   verifyFormat("a<int> = 1;", Style);
9498   verifyFormat("a<int> >>= 1;", Style);
9499 
9500   verifyFormat("test < a | b >> c;");
9501   verifyFormat("test<test<a | b>> c;");
9502   verifyFormat("test >> a >> b;");
9503   verifyFormat("test << a >> b;");
9504 
9505   verifyFormat("f<int>();");
9506   verifyFormat("template <typename T> void f() {}");
9507   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9508   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9509                "sizeof(char)>::type>;");
9510   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9511   verifyFormat("f(a.operator()<A>());");
9512   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9513                "      .template operator()<A>());",
9514                getLLVMStyleWithColumns(35));
9515 
9516   // Not template parameters.
9517   verifyFormat("return a < b && c > d;");
9518   verifyFormat("void f() {\n"
9519                "  while (a < b && c > d) {\n"
9520                "  }\n"
9521                "}");
9522   verifyFormat("template <typename... Types>\n"
9523                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9524 
9525   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9526                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9527                getLLVMStyleWithColumns(60));
9528   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9529   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9530   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9531   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9532 }
9533 
9534 TEST_F(FormatTest, UnderstandsShiftOperators) {
9535   verifyFormat("if (i < x >> 1)");
9536   verifyFormat("while (i < x >> 1)");
9537   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9538   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9539   verifyFormat(
9540       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9541   verifyFormat("Foo.call<Bar<Function>>()");
9542   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9543   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9544                "++i, v = v >> 1)");
9545   verifyFormat("if (w<u<v<x>>, 1>::t)");
9546 }
9547 
9548 TEST_F(FormatTest, BitshiftOperatorWidth) {
9549   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9550             "                   bar */",
9551             format("int    a=1<<2;  /* foo\n"
9552                    "                   bar */"));
9553 
9554   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9555             "                     bar */",
9556             format("int  b  =256>>1 ;  /* foo\n"
9557                    "                      bar */"));
9558 }
9559 
9560 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9561   verifyFormat("COMPARE(a, ==, b);");
9562   verifyFormat("auto s = sizeof...(Ts) - 1;");
9563 }
9564 
9565 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9566   verifyFormat("int A::*x;");
9567   verifyFormat("int (S::*func)(void *);");
9568   verifyFormat("void f() { int (S::*func)(void *); }");
9569   verifyFormat("typedef bool *(Class::*Member)() const;");
9570   verifyFormat("void f() {\n"
9571                "  (a->*f)();\n"
9572                "  a->*x;\n"
9573                "  (a.*f)();\n"
9574                "  ((*a).*f)();\n"
9575                "  a.*x;\n"
9576                "}");
9577   verifyFormat("void f() {\n"
9578                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9579                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9580                "}");
9581   verifyFormat(
9582       "(aaaaaaaaaa->*bbbbbbb)(\n"
9583       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9584   FormatStyle Style = getLLVMStyle();
9585   Style.PointerAlignment = FormatStyle::PAS_Left;
9586   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9587 }
9588 
9589 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9590   verifyFormat("int a = -2;");
9591   verifyFormat("f(-1, -2, -3);");
9592   verifyFormat("a[-1] = 5;");
9593   verifyFormat("int a = 5 + -2;");
9594   verifyFormat("if (i == -1) {\n}");
9595   verifyFormat("if (i != -1) {\n}");
9596   verifyFormat("if (i > -1) {\n}");
9597   verifyFormat("if (i < -1) {\n}");
9598   verifyFormat("++(a->f());");
9599   verifyFormat("--(a->f());");
9600   verifyFormat("(a->f())++;");
9601   verifyFormat("a[42]++;");
9602   verifyFormat("if (!(a->f())) {\n}");
9603   verifyFormat("if (!+i) {\n}");
9604   verifyFormat("~&a;");
9605 
9606   verifyFormat("a-- > b;");
9607   verifyFormat("b ? -a : c;");
9608   verifyFormat("n * sizeof char16;");
9609   verifyFormat("n * alignof char16;", getGoogleStyle());
9610   verifyFormat("sizeof(char);");
9611   verifyFormat("alignof(char);", getGoogleStyle());
9612 
9613   verifyFormat("return -1;");
9614   verifyFormat("throw -1;");
9615   verifyFormat("switch (a) {\n"
9616                "case -1:\n"
9617                "  break;\n"
9618                "}");
9619   verifyFormat("#define X -1");
9620   verifyFormat("#define X -kConstant");
9621 
9622   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9623   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9624 
9625   verifyFormat("int a = /* confusing comment */ -1;");
9626   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9627   verifyFormat("int a = i /* confusing comment */++;");
9628 
9629   verifyFormat("co_yield -1;");
9630   verifyFormat("co_return -1;");
9631 
9632   // Check that * is not treated as a binary operator when we set
9633   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9634   FormatStyle PASLeftStyle = getLLVMStyle();
9635   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9636   verifyFormat("co_return *a;", PASLeftStyle);
9637   verifyFormat("co_await *a;", PASLeftStyle);
9638   verifyFormat("co_yield *a", PASLeftStyle);
9639   verifyFormat("return *a;", PASLeftStyle);
9640 }
9641 
9642 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9643   verifyFormat("if (!aaaaaaaaaa( // break\n"
9644                "        aaaaa)) {\n"
9645                "}");
9646   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9647                "    aaaaa));");
9648   verifyFormat("*aaa = aaaaaaa( // break\n"
9649                "    bbbbbb);");
9650 }
9651 
9652 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9653   verifyFormat("bool operator<();");
9654   verifyFormat("bool operator>();");
9655   verifyFormat("bool operator=();");
9656   verifyFormat("bool operator==();");
9657   verifyFormat("bool operator!=();");
9658   verifyFormat("int operator+();");
9659   verifyFormat("int operator++();");
9660   verifyFormat("int operator++(int) volatile noexcept;");
9661   verifyFormat("bool operator,();");
9662   verifyFormat("bool operator();");
9663   verifyFormat("bool operator()();");
9664   verifyFormat("bool operator[]();");
9665   verifyFormat("operator bool();");
9666   verifyFormat("operator int();");
9667   verifyFormat("operator void *();");
9668   verifyFormat("operator SomeType<int>();");
9669   verifyFormat("operator SomeType<int, int>();");
9670   verifyFormat("operator SomeType<SomeType<int>>();");
9671   verifyFormat("operator< <>();");
9672   verifyFormat("operator<< <>();");
9673   verifyFormat("< <>");
9674 
9675   verifyFormat("void *operator new(std::size_t size);");
9676   verifyFormat("void *operator new[](std::size_t size);");
9677   verifyFormat("void operator delete(void *ptr);");
9678   verifyFormat("void operator delete[](void *ptr);");
9679   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9680                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9681   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9682                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9683 
9684   verifyFormat(
9685       "ostream &operator<<(ostream &OutputStream,\n"
9686       "                    SomeReallyLongType WithSomeReallyLongValue);");
9687   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9688                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9689                "  return left.group < right.group;\n"
9690                "}");
9691   verifyFormat("SomeType &operator=(const SomeType &S);");
9692   verifyFormat("f.template operator()<int>();");
9693 
9694   verifyGoogleFormat("operator void*();");
9695   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9696   verifyGoogleFormat("operator ::A();");
9697 
9698   verifyFormat("using A::operator+;");
9699   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9700                "int i;");
9701 
9702   // Calling an operator as a member function.
9703   verifyFormat("void f() { a.operator*(); }");
9704   verifyFormat("void f() { a.operator*(b & b); }");
9705   verifyFormat("void f() { a->operator&(a * b); }");
9706   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9707   // TODO: Calling an operator as a non-member function is hard to distinguish.
9708   // https://llvm.org/PR50629
9709   // verifyFormat("void f() { operator*(a & a); }");
9710   // verifyFormat("void f() { operator&(a, b * b); }");
9711 
9712   verifyFormat("::operator delete(foo);");
9713   verifyFormat("::operator new(n * sizeof(foo));");
9714   verifyFormat("foo() { ::operator delete(foo); }");
9715   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9716 }
9717 
9718 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9719   verifyFormat("void A::b() && {}");
9720   verifyFormat("void A::b() &&noexcept {}");
9721   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9722   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9723   verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
9724   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9725   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9726   verifyFormat("Deleted &operator=(const Deleted &) &;");
9727   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9728   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9729   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9730   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9731   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9732   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9733   verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
9734   verifyFormat("void Fn(T const &) const &;");
9735   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9736   verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
9737   verifyFormat("template <typename T>\n"
9738                "void F(T) && = delete;",
9739                getGoogleStyle());
9740 
9741   FormatStyle AlignLeft = getLLVMStyle();
9742   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9743   verifyFormat("void A::b() && {}", AlignLeft);
9744   verifyFormat("void A::b() && noexcept {}", AlignLeft);
9745   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9746   verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
9747                AlignLeft);
9748   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9749                AlignLeft);
9750   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9751   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9752   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9753   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9754   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9755   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9756   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9757   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9758   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
9759                AlignLeft);
9760 
9761   FormatStyle AlignMiddle = getLLVMStyle();
9762   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9763   verifyFormat("void A::b() && {}", AlignMiddle);
9764   verifyFormat("void A::b() && noexcept {}", AlignMiddle);
9765   verifyFormat("Deleted & operator=(const Deleted &) & = default;",
9766                AlignMiddle);
9767   verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
9768                AlignMiddle);
9769   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
9770                AlignMiddle);
9771   verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
9772   verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
9773   verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
9774   verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
9775   verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
9776   verifyFormat("auto Function(T) & -> void;", AlignMiddle);
9777   verifyFormat("void Fn(T const &) const &;", AlignMiddle);
9778   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
9779   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
9780                AlignMiddle);
9781 
9782   FormatStyle Spaces = getLLVMStyle();
9783   Spaces.SpacesInCStyleCastParentheses = true;
9784   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9785   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9786   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9787   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9788 
9789   Spaces.SpacesInCStyleCastParentheses = false;
9790   Spaces.SpacesInParentheses = true;
9791   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9792   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9793                Spaces);
9794   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9795   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9796 
9797   FormatStyle BreakTemplate = getLLVMStyle();
9798   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9799 
9800   verifyFormat("struct f {\n"
9801                "  template <class T>\n"
9802                "  int &foo(const std::string &str) &noexcept {}\n"
9803                "};",
9804                BreakTemplate);
9805 
9806   verifyFormat("struct f {\n"
9807                "  template <class T>\n"
9808                "  int &foo(const std::string &str) &&noexcept {}\n"
9809                "};",
9810                BreakTemplate);
9811 
9812   verifyFormat("struct f {\n"
9813                "  template <class T>\n"
9814                "  int &foo(const std::string &str) const &noexcept {}\n"
9815                "};",
9816                BreakTemplate);
9817 
9818   verifyFormat("struct f {\n"
9819                "  template <class T>\n"
9820                "  int &foo(const std::string &str) const &noexcept {}\n"
9821                "};",
9822                BreakTemplate);
9823 
9824   verifyFormat("struct f {\n"
9825                "  template <class T>\n"
9826                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
9827                "};",
9828                BreakTemplate);
9829 
9830   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
9831   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
9832       FormatStyle::BTDS_Yes;
9833   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
9834 
9835   verifyFormat("struct f {\n"
9836                "  template <class T>\n"
9837                "  int& foo(const std::string& str) & noexcept {}\n"
9838                "};",
9839                AlignLeftBreakTemplate);
9840 
9841   verifyFormat("struct f {\n"
9842                "  template <class T>\n"
9843                "  int& foo(const std::string& str) && noexcept {}\n"
9844                "};",
9845                AlignLeftBreakTemplate);
9846 
9847   verifyFormat("struct f {\n"
9848                "  template <class T>\n"
9849                "  int& foo(const std::string& str) const& noexcept {}\n"
9850                "};",
9851                AlignLeftBreakTemplate);
9852 
9853   verifyFormat("struct f {\n"
9854                "  template <class T>\n"
9855                "  int& foo(const std::string& str) const&& noexcept {}\n"
9856                "};",
9857                AlignLeftBreakTemplate);
9858 
9859   verifyFormat("struct f {\n"
9860                "  template <class T>\n"
9861                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
9862                "};",
9863                AlignLeftBreakTemplate);
9864 
9865   // The `&` in `Type&` should not be confused with a trailing `&` of
9866   // DEPRECATED(reason) member function.
9867   verifyFormat("struct f {\n"
9868                "  template <class T>\n"
9869                "  DEPRECATED(reason)\n"
9870                "  Type &foo(arguments) {}\n"
9871                "};",
9872                BreakTemplate);
9873 
9874   verifyFormat("struct f {\n"
9875                "  template <class T>\n"
9876                "  DEPRECATED(reason)\n"
9877                "  Type& foo(arguments) {}\n"
9878                "};",
9879                AlignLeftBreakTemplate);
9880 
9881   verifyFormat("void (*foopt)(int) = &func;");
9882 
9883   FormatStyle DerivePointerAlignment = getLLVMStyle();
9884   DerivePointerAlignment.DerivePointerAlignment = true;
9885   // There's always a space between the function and its trailing qualifiers.
9886   // This isn't evidence for PAS_Right (or for PAS_Left).
9887   std::string Prefix = "void a() &;\n"
9888                        "void b() &;\n";
9889   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
9890   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
9891   // Same if the function is an overloaded operator, and with &&.
9892   Prefix = "void operator()() &&;\n"
9893            "void operator()() &&;\n";
9894   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
9895   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
9896   // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
9897   Prefix = "void a() const &;\n"
9898            "void b() const &;\n";
9899   EXPECT_EQ(Prefix + "int *x;",
9900             format(Prefix + "int* x;", DerivePointerAlignment));
9901 }
9902 
9903 TEST_F(FormatTest, UnderstandsNewAndDelete) {
9904   verifyFormat("void f() {\n"
9905                "  A *a = new A;\n"
9906                "  A *a = new (placement) A;\n"
9907                "  delete a;\n"
9908                "  delete (A *)a;\n"
9909                "}");
9910   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9911                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9912   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9913                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9914                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9915   verifyFormat("delete[] h->p;");
9916   verifyFormat("delete[] (void *)p;");
9917 
9918   verifyFormat("void operator delete(void *foo) ATTRIB;");
9919   verifyFormat("void operator new(void *foo) ATTRIB;");
9920   verifyFormat("void operator delete[](void *foo) ATTRIB;");
9921   verifyFormat("void operator delete(void *ptr) noexcept;");
9922 
9923   EXPECT_EQ("void new(link p);\n"
9924             "void delete(link p);\n",
9925             format("void new (link p);\n"
9926                    "void delete (link p);\n"));
9927 }
9928 
9929 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
9930   verifyFormat("int *f(int *a) {}");
9931   verifyFormat("int main(int argc, char **argv) {}");
9932   verifyFormat("Test::Test(int b) : a(b * b) {}");
9933   verifyIndependentOfContext("f(a, *a);");
9934   verifyFormat("void g() { f(*a); }");
9935   verifyIndependentOfContext("int a = b * 10;");
9936   verifyIndependentOfContext("int a = 10 * b;");
9937   verifyIndependentOfContext("int a = b * c;");
9938   verifyIndependentOfContext("int a += b * c;");
9939   verifyIndependentOfContext("int a -= b * c;");
9940   verifyIndependentOfContext("int a *= b * c;");
9941   verifyIndependentOfContext("int a /= b * c;");
9942   verifyIndependentOfContext("int a = *b;");
9943   verifyIndependentOfContext("int a = *b * c;");
9944   verifyIndependentOfContext("int a = b * *c;");
9945   verifyIndependentOfContext("int a = b * (10);");
9946   verifyIndependentOfContext("S << b * (10);");
9947   verifyIndependentOfContext("return 10 * b;");
9948   verifyIndependentOfContext("return *b * *c;");
9949   verifyIndependentOfContext("return a & ~b;");
9950   verifyIndependentOfContext("f(b ? *c : *d);");
9951   verifyIndependentOfContext("int a = b ? *c : *d;");
9952   verifyIndependentOfContext("*b = a;");
9953   verifyIndependentOfContext("a * ~b;");
9954   verifyIndependentOfContext("a * !b;");
9955   verifyIndependentOfContext("a * +b;");
9956   verifyIndependentOfContext("a * -b;");
9957   verifyIndependentOfContext("a * ++b;");
9958   verifyIndependentOfContext("a * --b;");
9959   verifyIndependentOfContext("a[4] * b;");
9960   verifyIndependentOfContext("a[a * a] = 1;");
9961   verifyIndependentOfContext("f() * b;");
9962   verifyIndependentOfContext("a * [self dostuff];");
9963   verifyIndependentOfContext("int x = a * (a + b);");
9964   verifyIndependentOfContext("(a *)(a + b);");
9965   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
9966   verifyIndependentOfContext("int *pa = (int *)&a;");
9967   verifyIndependentOfContext("return sizeof(int **);");
9968   verifyIndependentOfContext("return sizeof(int ******);");
9969   verifyIndependentOfContext("return (int **&)a;");
9970   verifyIndependentOfContext("f((*PointerToArray)[10]);");
9971   verifyFormat("void f(Type (*parameter)[10]) {}");
9972   verifyFormat("void f(Type (&parameter)[10]) {}");
9973   verifyGoogleFormat("return sizeof(int**);");
9974   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
9975   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
9976   verifyFormat("auto a = [](int **&, int ***) {};");
9977   verifyFormat("auto PointerBinding = [](const char *S) {};");
9978   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
9979   verifyFormat("[](const decltype(*a) &value) {}");
9980   verifyFormat("[](const typeof(*a) &value) {}");
9981   verifyFormat("[](const _Atomic(a *) &value) {}");
9982   verifyFormat("[](const __underlying_type(a) &value) {}");
9983   verifyFormat("decltype(a * b) F();");
9984   verifyFormat("typeof(a * b) F();");
9985   verifyFormat("#define MACRO() [](A *a) { return 1; }");
9986   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
9987   verifyIndependentOfContext("typedef void (*f)(int *a);");
9988   verifyIndependentOfContext("int i{a * b};");
9989   verifyIndependentOfContext("aaa && aaa->f();");
9990   verifyIndependentOfContext("int x = ~*p;");
9991   verifyFormat("Constructor() : a(a), area(width * height) {}");
9992   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
9993   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
9994   verifyFormat("void f() { f(a, c * d); }");
9995   verifyFormat("void f() { f(new a(), c * d); }");
9996   verifyFormat("void f(const MyOverride &override);");
9997   verifyFormat("void f(const MyFinal &final);");
9998   verifyIndependentOfContext("bool a = f() && override.f();");
9999   verifyIndependentOfContext("bool a = f() && final.f();");
10000 
10001   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
10002 
10003   verifyIndependentOfContext("A<int *> a;");
10004   verifyIndependentOfContext("A<int **> a;");
10005   verifyIndependentOfContext("A<int *, int *> a;");
10006   verifyIndependentOfContext("A<int *[]> a;");
10007   verifyIndependentOfContext(
10008       "const char *const p = reinterpret_cast<const char *const>(q);");
10009   verifyIndependentOfContext("A<int **, int **> a;");
10010   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
10011   verifyFormat("for (char **a = b; *a; ++a) {\n}");
10012   verifyFormat("for (; a && b;) {\n}");
10013   verifyFormat("bool foo = true && [] { return false; }();");
10014 
10015   verifyFormat(
10016       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10017       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10018 
10019   verifyGoogleFormat("int const* a = &b;");
10020   verifyGoogleFormat("**outparam = 1;");
10021   verifyGoogleFormat("*outparam = a * b;");
10022   verifyGoogleFormat("int main(int argc, char** argv) {}");
10023   verifyGoogleFormat("A<int*> a;");
10024   verifyGoogleFormat("A<int**> a;");
10025   verifyGoogleFormat("A<int*, int*> a;");
10026   verifyGoogleFormat("A<int**, int**> a;");
10027   verifyGoogleFormat("f(b ? *c : *d);");
10028   verifyGoogleFormat("int a = b ? *c : *d;");
10029   verifyGoogleFormat("Type* t = **x;");
10030   verifyGoogleFormat("Type* t = *++*x;");
10031   verifyGoogleFormat("*++*x;");
10032   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
10033   verifyGoogleFormat("Type* t = x++ * y;");
10034   verifyGoogleFormat(
10035       "const char* const p = reinterpret_cast<const char* const>(q);");
10036   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
10037   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
10038   verifyGoogleFormat("template <typename T>\n"
10039                      "void f(int i = 0, SomeType** temps = NULL);");
10040 
10041   FormatStyle Left = getLLVMStyle();
10042   Left.PointerAlignment = FormatStyle::PAS_Left;
10043   verifyFormat("x = *a(x) = *a(y);", Left);
10044   verifyFormat("for (;; *a = b) {\n}", Left);
10045   verifyFormat("return *this += 1;", Left);
10046   verifyFormat("throw *x;", Left);
10047   verifyFormat("delete *x;", Left);
10048   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
10049   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
10050   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
10051   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
10052   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
10053   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
10054   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
10055   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
10056   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
10057 
10058   verifyIndependentOfContext("a = *(x + y);");
10059   verifyIndependentOfContext("a = &(x + y);");
10060   verifyIndependentOfContext("*(x + y).call();");
10061   verifyIndependentOfContext("&(x + y)->call();");
10062   verifyFormat("void f() { &(*I).first; }");
10063 
10064   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
10065   verifyFormat("f(* /* confusing comment */ foo);");
10066   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
10067   verifyFormat("void foo(int * // this is the first paramters\n"
10068                "         ,\n"
10069                "         int second);");
10070   verifyFormat("double term = a * // first\n"
10071                "              b;");
10072   verifyFormat(
10073       "int *MyValues = {\n"
10074       "    *A, // Operator detection might be confused by the '{'\n"
10075       "    *BB // Operator detection might be confused by previous comment\n"
10076       "};");
10077 
10078   verifyIndependentOfContext("if (int *a = &b)");
10079   verifyIndependentOfContext("if (int &a = *b)");
10080   verifyIndependentOfContext("if (a & b[i])");
10081   verifyIndependentOfContext("if constexpr (a & b[i])");
10082   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
10083   verifyIndependentOfContext("if (a * (b * c))");
10084   verifyIndependentOfContext("if constexpr (a * (b * c))");
10085   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
10086   verifyIndependentOfContext("if (a::b::c::d & b[i])");
10087   verifyIndependentOfContext("if (*b[i])");
10088   verifyIndependentOfContext("if (int *a = (&b))");
10089   verifyIndependentOfContext("while (int *a = &b)");
10090   verifyIndependentOfContext("while (a * (b * c))");
10091   verifyIndependentOfContext("size = sizeof *a;");
10092   verifyIndependentOfContext("if (a && (b = c))");
10093   verifyFormat("void f() {\n"
10094                "  for (const int &v : Values) {\n"
10095                "  }\n"
10096                "}");
10097   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
10098   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
10099   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
10100 
10101   verifyFormat("#define A (!a * b)");
10102   verifyFormat("#define MACRO     \\\n"
10103                "  int *i = a * b; \\\n"
10104                "  void f(a *b);",
10105                getLLVMStyleWithColumns(19));
10106 
10107   verifyIndependentOfContext("A = new SomeType *[Length];");
10108   verifyIndependentOfContext("A = new SomeType *[Length]();");
10109   verifyIndependentOfContext("T **t = new T *;");
10110   verifyIndependentOfContext("T **t = new T *();");
10111   verifyGoogleFormat("A = new SomeType*[Length]();");
10112   verifyGoogleFormat("A = new SomeType*[Length];");
10113   verifyGoogleFormat("T** t = new T*;");
10114   verifyGoogleFormat("T** t = new T*();");
10115 
10116   verifyFormat("STATIC_ASSERT((a & b) == 0);");
10117   verifyFormat("STATIC_ASSERT(0 == (a & b));");
10118   verifyFormat("template <bool a, bool b> "
10119                "typename t::if<x && y>::type f() {}");
10120   verifyFormat("template <int *y> f() {}");
10121   verifyFormat("vector<int *> v;");
10122   verifyFormat("vector<int *const> v;");
10123   verifyFormat("vector<int *const **const *> v;");
10124   verifyFormat("vector<int *volatile> v;");
10125   verifyFormat("vector<a *_Nonnull> v;");
10126   verifyFormat("vector<a *_Nullable> v;");
10127   verifyFormat("vector<a *_Null_unspecified> v;");
10128   verifyFormat("vector<a *__ptr32> v;");
10129   verifyFormat("vector<a *__ptr64> v;");
10130   verifyFormat("vector<a *__capability> v;");
10131   FormatStyle TypeMacros = getLLVMStyle();
10132   TypeMacros.TypenameMacros = {"LIST"};
10133   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
10134   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
10135   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
10136   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
10137   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
10138 
10139   FormatStyle CustomQualifier = getLLVMStyle();
10140   // Add identifiers that should not be parsed as a qualifier by default.
10141   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10142   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
10143   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
10144   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
10145   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
10146   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
10147   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
10148   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
10149   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
10150   verifyFormat("vector<a * _NotAQualifier> v;");
10151   verifyFormat("vector<a * __not_a_qualifier> v;");
10152   verifyFormat("vector<a * b> v;");
10153   verifyFormat("foo<b && false>();");
10154   verifyFormat("foo<b & 1>();");
10155   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
10156   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
10157   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
10158   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
10159   verifyFormat(
10160       "template <class T, class = typename std::enable_if<\n"
10161       "                       std::is_integral<T>::value &&\n"
10162       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
10163       "void F();",
10164       getLLVMStyleWithColumns(70));
10165   verifyFormat("template <class T,\n"
10166                "          class = typename std::enable_if<\n"
10167                "              std::is_integral<T>::value &&\n"
10168                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
10169                "          class U>\n"
10170                "void F();",
10171                getLLVMStyleWithColumns(70));
10172   verifyFormat(
10173       "template <class T,\n"
10174       "          class = typename ::std::enable_if<\n"
10175       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
10176       "void F();",
10177       getGoogleStyleWithColumns(68));
10178 
10179   verifyIndependentOfContext("MACRO(int *i);");
10180   verifyIndependentOfContext("MACRO(auto *a);");
10181   verifyIndependentOfContext("MACRO(const A *a);");
10182   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10183   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10184   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10185   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10186   verifyIndependentOfContext("MACRO(A *const a);");
10187   verifyIndependentOfContext("MACRO(A *restrict a);");
10188   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10189   verifyIndependentOfContext("MACRO(A *__restrict a);");
10190   verifyIndependentOfContext("MACRO(A *volatile a);");
10191   verifyIndependentOfContext("MACRO(A *__volatile a);");
10192   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10193   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10194   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10195   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10196   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10197   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10198   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10199   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10200   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10201   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10202   verifyIndependentOfContext("MACRO(A *__capability);");
10203   verifyIndependentOfContext("MACRO(A &__capability);");
10204   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10205   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10206   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10207   // a type declaration:
10208   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10209   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10210   // Also check that TypenameMacros prevents parsing it as multiplication:
10211   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10212   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10213 
10214   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10215   verifyFormat("void f() { f(float{1}, a * a); }");
10216   verifyFormat("void f() { f(float(1), a * a); }");
10217 
10218   verifyFormat("f((void (*)(int))g);");
10219   verifyFormat("f((void (&)(int))g);");
10220   verifyFormat("f((void (^)(int))g);");
10221 
10222   // FIXME: Is there a way to make this work?
10223   // verifyIndependentOfContext("MACRO(A *a);");
10224   verifyFormat("MACRO(A &B);");
10225   verifyFormat("MACRO(A *B);");
10226   verifyFormat("void f() { MACRO(A * B); }");
10227   verifyFormat("void f() { MACRO(A & B); }");
10228 
10229   // This lambda was mis-formatted after D88956 (treating it as a binop):
10230   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10231   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10232   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10233   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10234 
10235   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10236   verifyFormat("return options != nullptr && operator==(*options);");
10237 
10238   EXPECT_EQ("#define OP(x)                                    \\\n"
10239             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10240             "    return s << a.DebugString();                 \\\n"
10241             "  }",
10242             format("#define OP(x) \\\n"
10243                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10244                    "    return s << a.DebugString(); \\\n"
10245                    "  }",
10246                    getLLVMStyleWithColumns(50)));
10247 
10248   // FIXME: We cannot handle this case yet; we might be able to figure out that
10249   // foo<x> d > v; doesn't make sense.
10250   verifyFormat("foo<a<b && c> d> v;");
10251 
10252   FormatStyle PointerMiddle = getLLVMStyle();
10253   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10254   verifyFormat("delete *x;", PointerMiddle);
10255   verifyFormat("int * x;", PointerMiddle);
10256   verifyFormat("int *[] x;", PointerMiddle);
10257   verifyFormat("template <int * y> f() {}", PointerMiddle);
10258   verifyFormat("int * f(int * a) {}", PointerMiddle);
10259   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10260   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10261   verifyFormat("A<int *> a;", PointerMiddle);
10262   verifyFormat("A<int **> a;", PointerMiddle);
10263   verifyFormat("A<int *, int *> a;", PointerMiddle);
10264   verifyFormat("A<int *[]> a;", PointerMiddle);
10265   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10266   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10267   verifyFormat("T ** t = new T *;", PointerMiddle);
10268 
10269   // Member function reference qualifiers aren't binary operators.
10270   verifyFormat("string // break\n"
10271                "operator()() & {}");
10272   verifyFormat("string // break\n"
10273                "operator()() && {}");
10274   verifyGoogleFormat("template <typename T>\n"
10275                      "auto x() & -> int {}");
10276 
10277   // Should be binary operators when used as an argument expression (overloaded
10278   // operator invoked as a member function).
10279   verifyFormat("void f() { a.operator()(a * a); }");
10280   verifyFormat("void f() { a->operator()(a & a); }");
10281   verifyFormat("void f() { a.operator()(*a & *a); }");
10282   verifyFormat("void f() { a->operator()(*a * *a); }");
10283 
10284   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10285   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10286 }
10287 
10288 TEST_F(FormatTest, UnderstandsAttributes) {
10289   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10290   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10291                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10292   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10293   FormatStyle AfterType = getLLVMStyle();
10294   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10295   verifyFormat("__attribute__((nodebug)) void\n"
10296                "foo() {}\n",
10297                AfterType);
10298   verifyFormat("__unused void\n"
10299                "foo() {}",
10300                AfterType);
10301 
10302   FormatStyle CustomAttrs = getLLVMStyle();
10303   CustomAttrs.AttributeMacros.push_back("__unused");
10304   CustomAttrs.AttributeMacros.push_back("__attr1");
10305   CustomAttrs.AttributeMacros.push_back("__attr2");
10306   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10307   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10308   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10309   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10310   // Check that it is parsed as a multiplication without AttributeMacros and
10311   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10312   verifyFormat("vector<SomeType * __attr1> v;");
10313   verifyFormat("vector<SomeType __attr1 *> v;");
10314   verifyFormat("vector<SomeType __attr1 *const> v;");
10315   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10316   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10317   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10318   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10319   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10320   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10321   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10322   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10323 
10324   // Check that these are not parsed as function declarations:
10325   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10326   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10327   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10328   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10329   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10330   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10331   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10332   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10333   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10334   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10335 }
10336 
10337 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10338   // Check that qualifiers on pointers don't break parsing of casts.
10339   verifyFormat("x = (foo *const)*v;");
10340   verifyFormat("x = (foo *volatile)*v;");
10341   verifyFormat("x = (foo *restrict)*v;");
10342   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10343   verifyFormat("x = (foo *_Nonnull)*v;");
10344   verifyFormat("x = (foo *_Nullable)*v;");
10345   verifyFormat("x = (foo *_Null_unspecified)*v;");
10346   verifyFormat("x = (foo *_Nonnull)*v;");
10347   verifyFormat("x = (foo *[[clang::attr]])*v;");
10348   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10349   verifyFormat("x = (foo *__ptr32)*v;");
10350   verifyFormat("x = (foo *__ptr64)*v;");
10351   verifyFormat("x = (foo *__capability)*v;");
10352 
10353   // Check that we handle multiple trailing qualifiers and skip them all to
10354   // determine that the expression is a cast to a pointer type.
10355   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10356   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10357   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10358   StringRef AllQualifiers =
10359       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10360       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10361   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10362   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10363 
10364   // Also check that address-of is not parsed as a binary bitwise-and:
10365   verifyFormat("x = (foo *const)&v;");
10366   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10367   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10368 
10369   // Check custom qualifiers:
10370   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10371   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10372   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10373   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10374   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10375                CustomQualifier);
10376   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10377                CustomQualifier);
10378 
10379   // Check that unknown identifiers result in binary operator parsing:
10380   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10381   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10382 }
10383 
10384 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10385   verifyFormat("SomeType s [[unused]] (InitValue);");
10386   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10387   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10388   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10389   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10390   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10391                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10392   verifyFormat("[[nodiscard]] bool f() { return false; }");
10393   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10394   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10395   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10396   verifyFormat("[[nodiscard]] ::qualified_type f();");
10397 
10398   // Make sure we do not mistake attributes for array subscripts.
10399   verifyFormat("int a() {}\n"
10400                "[[unused]] int b() {}\n");
10401   verifyFormat("NSArray *arr;\n"
10402                "arr[[Foo() bar]];");
10403 
10404   // On the other hand, we still need to correctly find array subscripts.
10405   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10406 
10407   // Make sure that we do not mistake Objective-C method inside array literals
10408   // as attributes, even if those method names are also keywords.
10409   verifyFormat("@[ [foo bar] ];");
10410   verifyFormat("@[ [NSArray class] ];");
10411   verifyFormat("@[ [foo enum] ];");
10412 
10413   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10414 
10415   // Make sure we do not parse attributes as lambda introducers.
10416   FormatStyle MultiLineFunctions = getLLVMStyle();
10417   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10418   verifyFormat("[[unused]] int b() {\n"
10419                "  return 42;\n"
10420                "}\n",
10421                MultiLineFunctions);
10422 }
10423 
10424 TEST_F(FormatTest, AttributeClass) {
10425   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10426   verifyFormat("class S {\n"
10427                "  S(S&&) = default;\n"
10428                "};",
10429                Style);
10430   verifyFormat("class [[nodiscard]] S {\n"
10431                "  S(S&&) = default;\n"
10432                "};",
10433                Style);
10434   verifyFormat("class __attribute((maybeunused)) S {\n"
10435                "  S(S&&) = default;\n"
10436                "};",
10437                Style);
10438   verifyFormat("struct S {\n"
10439                "  S(S&&) = default;\n"
10440                "};",
10441                Style);
10442   verifyFormat("struct [[nodiscard]] S {\n"
10443                "  S(S&&) = default;\n"
10444                "};",
10445                Style);
10446 }
10447 
10448 TEST_F(FormatTest, AttributesAfterMacro) {
10449   FormatStyle Style = getLLVMStyle();
10450   verifyFormat("MACRO;\n"
10451                "__attribute__((maybe_unused)) int foo() {\n"
10452                "  //...\n"
10453                "}");
10454 
10455   verifyFormat("MACRO;\n"
10456                "[[nodiscard]] int foo() {\n"
10457                "  //...\n"
10458                "}");
10459 
10460   EXPECT_EQ("MACRO\n\n"
10461             "__attribute__((maybe_unused)) int foo() {\n"
10462             "  //...\n"
10463             "}",
10464             format("MACRO\n\n"
10465                    "__attribute__((maybe_unused)) int foo() {\n"
10466                    "  //...\n"
10467                    "}"));
10468 
10469   EXPECT_EQ("MACRO\n\n"
10470             "[[nodiscard]] int foo() {\n"
10471             "  //...\n"
10472             "}",
10473             format("MACRO\n\n"
10474                    "[[nodiscard]] int foo() {\n"
10475                    "  //...\n"
10476                    "}"));
10477 }
10478 
10479 TEST_F(FormatTest, AttributePenaltyBreaking) {
10480   FormatStyle Style = getLLVMStyle();
10481   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10482                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10483                Style);
10484   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10485                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10486                Style);
10487   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10488                "shared_ptr<ALongTypeName> &C d) {\n}",
10489                Style);
10490 }
10491 
10492 TEST_F(FormatTest, UnderstandsEllipsis) {
10493   FormatStyle Style = getLLVMStyle();
10494   verifyFormat("int printf(const char *fmt, ...);");
10495   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10496   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10497 
10498   verifyFormat("template <int *...PP> a;", Style);
10499 
10500   Style.PointerAlignment = FormatStyle::PAS_Left;
10501   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10502 
10503   verifyFormat("template <int*... PP> a;", Style);
10504 
10505   Style.PointerAlignment = FormatStyle::PAS_Middle;
10506   verifyFormat("template <int *... PP> a;", Style);
10507 }
10508 
10509 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10510   EXPECT_EQ("int *a;\n"
10511             "int *a;\n"
10512             "int *a;",
10513             format("int *a;\n"
10514                    "int* a;\n"
10515                    "int *a;",
10516                    getGoogleStyle()));
10517   EXPECT_EQ("int* a;\n"
10518             "int* a;\n"
10519             "int* a;",
10520             format("int* a;\n"
10521                    "int* a;\n"
10522                    "int *a;",
10523                    getGoogleStyle()));
10524   EXPECT_EQ("int *a;\n"
10525             "int *a;\n"
10526             "int *a;",
10527             format("int *a;\n"
10528                    "int * a;\n"
10529                    "int *  a;",
10530                    getGoogleStyle()));
10531   EXPECT_EQ("auto x = [] {\n"
10532             "  int *a;\n"
10533             "  int *a;\n"
10534             "  int *a;\n"
10535             "};",
10536             format("auto x=[]{int *a;\n"
10537                    "int * a;\n"
10538                    "int *  a;};",
10539                    getGoogleStyle()));
10540 }
10541 
10542 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10543   verifyFormat("int f(int &&a) {}");
10544   verifyFormat("int f(int a, char &&b) {}");
10545   verifyFormat("void f() { int &&a = b; }");
10546   verifyGoogleFormat("int f(int a, char&& b) {}");
10547   verifyGoogleFormat("void f() { int&& a = b; }");
10548 
10549   verifyIndependentOfContext("A<int &&> a;");
10550   verifyIndependentOfContext("A<int &&, int &&> a;");
10551   verifyGoogleFormat("A<int&&> a;");
10552   verifyGoogleFormat("A<int&&, int&&> a;");
10553 
10554   // Not rvalue references:
10555   verifyFormat("template <bool B, bool C> class A {\n"
10556                "  static_assert(B && C, \"Something is wrong\");\n"
10557                "};");
10558   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10559   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10560   verifyFormat("#define A(a, b) (a && b)");
10561 }
10562 
10563 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10564   verifyFormat("void f() {\n"
10565                "  x[aaaaaaaaa -\n"
10566                "    b] = 23;\n"
10567                "}",
10568                getLLVMStyleWithColumns(15));
10569 }
10570 
10571 TEST_F(FormatTest, FormatsCasts) {
10572   verifyFormat("Type *A = static_cast<Type *>(P);");
10573   verifyFormat("static_cast<Type *>(P);");
10574   verifyFormat("static_cast<Type &>(Fun)(Args);");
10575   verifyFormat("static_cast<Type &>(*Fun)(Args);");
10576   verifyFormat("if (static_cast<int>(A) + B >= 0)\n  ;");
10577   // Check that static_cast<...>(...) does not require the next token to be on
10578   // the same line.
10579   verifyFormat("some_loooong_output << something_something__ << "
10580                "static_cast<const void *>(R)\n"
10581                "                    << something;");
10582   verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
10583   verifyFormat("const_cast<Type &>(*Fun)(Args);");
10584   verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
10585   verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
10586   verifyFormat("Type *A = (Type *)P;");
10587   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10588   verifyFormat("int a = (int)(2.0f);");
10589   verifyFormat("int a = (int)2.0f;");
10590   verifyFormat("x[(int32)y];");
10591   verifyFormat("x = (int32)y;");
10592   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10593   verifyFormat("int a = (int)*b;");
10594   verifyFormat("int a = (int)2.0f;");
10595   verifyFormat("int a = (int)~0;");
10596   verifyFormat("int a = (int)++a;");
10597   verifyFormat("int a = (int)sizeof(int);");
10598   verifyFormat("int a = (int)+2;");
10599   verifyFormat("my_int a = (my_int)2.0f;");
10600   verifyFormat("my_int a = (my_int)sizeof(int);");
10601   verifyFormat("return (my_int)aaa;");
10602   verifyFormat("#define x ((int)-1)");
10603   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10604   verifyFormat("#define p(q) ((int *)&q)");
10605   verifyFormat("fn(a)(b) + 1;");
10606 
10607   verifyFormat("void f() { my_int a = (my_int)*b; }");
10608   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10609   verifyFormat("my_int a = (my_int)~0;");
10610   verifyFormat("my_int a = (my_int)++a;");
10611   verifyFormat("my_int a = (my_int)-2;");
10612   verifyFormat("my_int a = (my_int)1;");
10613   verifyFormat("my_int a = (my_int *)1;");
10614   verifyFormat("my_int a = (const my_int)-1;");
10615   verifyFormat("my_int a = (const my_int *)-1;");
10616   verifyFormat("my_int a = (my_int)(my_int)-1;");
10617   verifyFormat("my_int a = (ns::my_int)-2;");
10618   verifyFormat("case (my_int)ONE:");
10619   verifyFormat("auto x = (X)this;");
10620   // Casts in Obj-C style calls used to not be recognized as such.
10621   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10622 
10623   // FIXME: single value wrapped with paren will be treated as cast.
10624   verifyFormat("void f(int i = (kValue)*kMask) {}");
10625 
10626   verifyFormat("{ (void)F; }");
10627 
10628   // Don't break after a cast's
10629   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10630                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10631                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10632 
10633   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10634   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10635   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10636   verifyFormat("bool *y = (bool *)(void *)(x);");
10637   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10638   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10639   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10640   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10641 
10642   // These are not casts.
10643   verifyFormat("void f(int *) {}");
10644   verifyFormat("f(foo)->b;");
10645   verifyFormat("f(foo).b;");
10646   verifyFormat("f(foo)(b);");
10647   verifyFormat("f(foo)[b];");
10648   verifyFormat("[](foo) { return 4; }(bar);");
10649   verifyFormat("(*funptr)(foo)[4];");
10650   verifyFormat("funptrs[4](foo)[4];");
10651   verifyFormat("void f(int *);");
10652   verifyFormat("void f(int *) = 0;");
10653   verifyFormat("void f(SmallVector<int>) {}");
10654   verifyFormat("void f(SmallVector<int>);");
10655   verifyFormat("void f(SmallVector<int>) = 0;");
10656   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10657   verifyFormat("int a = sizeof(int) * b;");
10658   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10659   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10660   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10661   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10662 
10663   // These are not casts, but at some point were confused with casts.
10664   verifyFormat("virtual void foo(int *) override;");
10665   verifyFormat("virtual void foo(char &) const;");
10666   verifyFormat("virtual void foo(int *a, char *) const;");
10667   verifyFormat("int a = sizeof(int *) + b;");
10668   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10669   verifyFormat("bool b = f(g<int>) && c;");
10670   verifyFormat("typedef void (*f)(int i) func;");
10671   verifyFormat("void operator++(int) noexcept;");
10672   verifyFormat("void operator++(int &) noexcept;");
10673   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10674                "&) noexcept;");
10675   verifyFormat(
10676       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10677   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10678   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10679   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10680   verifyFormat("void operator delete(foo &) noexcept;");
10681   verifyFormat("void operator delete(foo) noexcept;");
10682   verifyFormat("void operator delete(int) noexcept;");
10683   verifyFormat("void operator delete(int &) noexcept;");
10684   verifyFormat("void operator delete(int &) volatile noexcept;");
10685   verifyFormat("void operator delete(int &) const");
10686   verifyFormat("void operator delete(int &) = default");
10687   verifyFormat("void operator delete(int &) = delete");
10688   verifyFormat("void operator delete(int &) [[noreturn]]");
10689   verifyFormat("void operator delete(int &) throw();");
10690   verifyFormat("void operator delete(int &) throw(int);");
10691   verifyFormat("auto operator delete(int &) -> int;");
10692   verifyFormat("auto operator delete(int &) override");
10693   verifyFormat("auto operator delete(int &) final");
10694 
10695   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10696                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10697   // FIXME: The indentation here is not ideal.
10698   verifyFormat(
10699       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10700       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10701       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10702 }
10703 
10704 TEST_F(FormatTest, FormatsFunctionTypes) {
10705   verifyFormat("A<bool()> a;");
10706   verifyFormat("A<SomeType()> a;");
10707   verifyFormat("A<void (*)(int, std::string)> a;");
10708   verifyFormat("A<void *(int)>;");
10709   verifyFormat("void *(*a)(int *, SomeType *);");
10710   verifyFormat("int (*func)(void *);");
10711   verifyFormat("void f() { int (*func)(void *); }");
10712   verifyFormat("template <class CallbackClass>\n"
10713                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10714 
10715   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10716   verifyGoogleFormat("void* (*a)(int);");
10717   verifyGoogleFormat(
10718       "template <class CallbackClass>\n"
10719       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10720 
10721   // Other constructs can look somewhat like function types:
10722   verifyFormat("A<sizeof(*x)> a;");
10723   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10724   verifyFormat("some_var = function(*some_pointer_var)[0];");
10725   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10726   verifyFormat("int x = f(&h)();");
10727   verifyFormat("returnsFunction(&param1, &param2)(param);");
10728   verifyFormat("std::function<\n"
10729                "    LooooooooooongTemplatedType<\n"
10730                "        SomeType>*(\n"
10731                "        LooooooooooooooooongType type)>\n"
10732                "    function;",
10733                getGoogleStyleWithColumns(40));
10734 }
10735 
10736 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10737   verifyFormat("A (*foo_)[6];");
10738   verifyFormat("vector<int> (*foo_)[6];");
10739 }
10740 
10741 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10742   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10743                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10744   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10745                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10746   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10747                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10748 
10749   // Different ways of ()-initializiation.
10750   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10751                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10752   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10753                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10754   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10755                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10756   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10757                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10758 
10759   // Lambdas should not confuse the variable declaration heuristic.
10760   verifyFormat("LooooooooooooooooongType\n"
10761                "    variable(nullptr, [](A *a) {});",
10762                getLLVMStyleWithColumns(40));
10763 }
10764 
10765 TEST_F(FormatTest, BreaksLongDeclarations) {
10766   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10767                "    AnotherNameForTheLongType;");
10768   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10769                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10770   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10771                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10772   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10773                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10774   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10775                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10776   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10777                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10778   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10779                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10780   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10781                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10782   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10783                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10784   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10785                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10786   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10787                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10788   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10789                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10790   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10791                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10792   FormatStyle Indented = getLLVMStyle();
10793   Indented.IndentWrappedFunctionNames = true;
10794   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10795                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10796                Indented);
10797   verifyFormat(
10798       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10799       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10800       Indented);
10801   verifyFormat(
10802       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10803       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10804       Indented);
10805   verifyFormat(
10806       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10807       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10808       Indented);
10809 
10810   // FIXME: Without the comment, this breaks after "(".
10811   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10812                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10813                getGoogleStyle());
10814 
10815   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10816                "                  int LoooooooooooooooooooongParam2) {}");
10817   verifyFormat(
10818       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
10819       "                                   SourceLocation L, IdentifierIn *II,\n"
10820       "                                   Type *T) {}");
10821   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
10822                "ReallyReaaallyLongFunctionName(\n"
10823                "    const std::string &SomeParameter,\n"
10824                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10825                "        &ReallyReallyLongParameterName,\n"
10826                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10827                "        &AnotherLongParameterName) {}");
10828   verifyFormat("template <typename A>\n"
10829                "SomeLoooooooooooooooooooooongType<\n"
10830                "    typename some_namespace::SomeOtherType<A>::Type>\n"
10831                "Function() {}");
10832 
10833   verifyGoogleFormat(
10834       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
10835       "    aaaaaaaaaaaaaaaaaaaaaaa;");
10836   verifyGoogleFormat(
10837       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
10838       "                                   SourceLocation L) {}");
10839   verifyGoogleFormat(
10840       "some_namespace::LongReturnType\n"
10841       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
10842       "    int first_long_parameter, int second_parameter) {}");
10843 
10844   verifyGoogleFormat("template <typename T>\n"
10845                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10846                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
10847   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10848                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
10849 
10850   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
10851                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10852                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10853   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10854                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10855                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
10856   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10857                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
10858                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
10859                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10860 
10861   verifyFormat("template <typename T> // Templates on own line.\n"
10862                "static int            // Some comment.\n"
10863                "MyFunction(int a);",
10864                getLLVMStyle());
10865 }
10866 
10867 TEST_F(FormatTest, FormatsAccessModifiers) {
10868   FormatStyle Style = getLLVMStyle();
10869   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
10870             FormatStyle::ELBAMS_LogicalBlock);
10871   verifyFormat("struct foo {\n"
10872                "private:\n"
10873                "  void f() {}\n"
10874                "\n"
10875                "private:\n"
10876                "  int i;\n"
10877                "\n"
10878                "protected:\n"
10879                "  int j;\n"
10880                "};\n",
10881                Style);
10882   verifyFormat("struct foo {\n"
10883                "private:\n"
10884                "  void f() {}\n"
10885                "\n"
10886                "private:\n"
10887                "  int i;\n"
10888                "\n"
10889                "protected:\n"
10890                "  int j;\n"
10891                "};\n",
10892                "struct foo {\n"
10893                "private:\n"
10894                "  void f() {}\n"
10895                "private:\n"
10896                "  int i;\n"
10897                "protected:\n"
10898                "  int j;\n"
10899                "};\n",
10900                Style);
10901   verifyFormat("struct foo { /* comment */\n"
10902                "private:\n"
10903                "  int i;\n"
10904                "  // comment\n"
10905                "private:\n"
10906                "  int j;\n"
10907                "};\n",
10908                Style);
10909   verifyFormat("struct foo {\n"
10910                "#ifdef FOO\n"
10911                "#endif\n"
10912                "private:\n"
10913                "  int i;\n"
10914                "#ifdef FOO\n"
10915                "private:\n"
10916                "#endif\n"
10917                "  int j;\n"
10918                "};\n",
10919                Style);
10920   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10921   verifyFormat("struct foo {\n"
10922                "private:\n"
10923                "  void f() {}\n"
10924                "private:\n"
10925                "  int i;\n"
10926                "protected:\n"
10927                "  int j;\n"
10928                "};\n",
10929                Style);
10930   verifyFormat("struct foo {\n"
10931                "private:\n"
10932                "  void f() {}\n"
10933                "private:\n"
10934                "  int i;\n"
10935                "protected:\n"
10936                "  int j;\n"
10937                "};\n",
10938                "struct foo {\n"
10939                "\n"
10940                "private:\n"
10941                "  void f() {}\n"
10942                "\n"
10943                "private:\n"
10944                "  int i;\n"
10945                "\n"
10946                "protected:\n"
10947                "  int j;\n"
10948                "};\n",
10949                Style);
10950   verifyFormat("struct foo { /* comment */\n"
10951                "private:\n"
10952                "  int i;\n"
10953                "  // comment\n"
10954                "private:\n"
10955                "  int j;\n"
10956                "};\n",
10957                "struct foo { /* comment */\n"
10958                "\n"
10959                "private:\n"
10960                "  int i;\n"
10961                "  // comment\n"
10962                "\n"
10963                "private:\n"
10964                "  int j;\n"
10965                "};\n",
10966                Style);
10967   verifyFormat("struct foo {\n"
10968                "#ifdef FOO\n"
10969                "#endif\n"
10970                "private:\n"
10971                "  int i;\n"
10972                "#ifdef FOO\n"
10973                "private:\n"
10974                "#endif\n"
10975                "  int j;\n"
10976                "};\n",
10977                "struct foo {\n"
10978                "#ifdef FOO\n"
10979                "#endif\n"
10980                "\n"
10981                "private:\n"
10982                "  int i;\n"
10983                "#ifdef FOO\n"
10984                "\n"
10985                "private:\n"
10986                "#endif\n"
10987                "  int j;\n"
10988                "};\n",
10989                Style);
10990   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10991   verifyFormat("struct foo {\n"
10992                "private:\n"
10993                "  void f() {}\n"
10994                "\n"
10995                "private:\n"
10996                "  int i;\n"
10997                "\n"
10998                "protected:\n"
10999                "  int j;\n"
11000                "};\n",
11001                Style);
11002   verifyFormat("struct foo {\n"
11003                "private:\n"
11004                "  void f() {}\n"
11005                "\n"
11006                "private:\n"
11007                "  int i;\n"
11008                "\n"
11009                "protected:\n"
11010                "  int j;\n"
11011                "};\n",
11012                "struct foo {\n"
11013                "private:\n"
11014                "  void f() {}\n"
11015                "private:\n"
11016                "  int i;\n"
11017                "protected:\n"
11018                "  int j;\n"
11019                "};\n",
11020                Style);
11021   verifyFormat("struct foo { /* comment */\n"
11022                "private:\n"
11023                "  int i;\n"
11024                "  // comment\n"
11025                "\n"
11026                "private:\n"
11027                "  int j;\n"
11028                "};\n",
11029                "struct foo { /* comment */\n"
11030                "private:\n"
11031                "  int i;\n"
11032                "  // comment\n"
11033                "\n"
11034                "private:\n"
11035                "  int j;\n"
11036                "};\n",
11037                Style);
11038   verifyFormat("struct foo {\n"
11039                "#ifdef FOO\n"
11040                "#endif\n"
11041                "\n"
11042                "private:\n"
11043                "  int i;\n"
11044                "#ifdef FOO\n"
11045                "\n"
11046                "private:\n"
11047                "#endif\n"
11048                "  int j;\n"
11049                "};\n",
11050                "struct foo {\n"
11051                "#ifdef FOO\n"
11052                "#endif\n"
11053                "private:\n"
11054                "  int i;\n"
11055                "#ifdef FOO\n"
11056                "private:\n"
11057                "#endif\n"
11058                "  int j;\n"
11059                "};\n",
11060                Style);
11061   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11062   EXPECT_EQ("struct foo {\n"
11063             "\n"
11064             "private:\n"
11065             "  void f() {}\n"
11066             "\n"
11067             "private:\n"
11068             "  int i;\n"
11069             "\n"
11070             "protected:\n"
11071             "  int j;\n"
11072             "};\n",
11073             format("struct foo {\n"
11074                    "\n"
11075                    "private:\n"
11076                    "  void f() {}\n"
11077                    "\n"
11078                    "private:\n"
11079                    "  int i;\n"
11080                    "\n"
11081                    "protected:\n"
11082                    "  int j;\n"
11083                    "};\n",
11084                    Style));
11085   verifyFormat("struct foo {\n"
11086                "private:\n"
11087                "  void f() {}\n"
11088                "private:\n"
11089                "  int i;\n"
11090                "protected:\n"
11091                "  int j;\n"
11092                "};\n",
11093                Style);
11094   EXPECT_EQ("struct foo { /* comment */\n"
11095             "\n"
11096             "private:\n"
11097             "  int i;\n"
11098             "  // comment\n"
11099             "\n"
11100             "private:\n"
11101             "  int j;\n"
11102             "};\n",
11103             format("struct foo { /* comment */\n"
11104                    "\n"
11105                    "private:\n"
11106                    "  int i;\n"
11107                    "  // comment\n"
11108                    "\n"
11109                    "private:\n"
11110                    "  int j;\n"
11111                    "};\n",
11112                    Style));
11113   verifyFormat("struct foo { /* comment */\n"
11114                "private:\n"
11115                "  int i;\n"
11116                "  // comment\n"
11117                "private:\n"
11118                "  int j;\n"
11119                "};\n",
11120                Style);
11121   EXPECT_EQ("struct foo {\n"
11122             "#ifdef FOO\n"
11123             "#endif\n"
11124             "\n"
11125             "private:\n"
11126             "  int i;\n"
11127             "#ifdef FOO\n"
11128             "\n"
11129             "private:\n"
11130             "#endif\n"
11131             "  int j;\n"
11132             "};\n",
11133             format("struct foo {\n"
11134                    "#ifdef FOO\n"
11135                    "#endif\n"
11136                    "\n"
11137                    "private:\n"
11138                    "  int i;\n"
11139                    "#ifdef FOO\n"
11140                    "\n"
11141                    "private:\n"
11142                    "#endif\n"
11143                    "  int j;\n"
11144                    "};\n",
11145                    Style));
11146   verifyFormat("struct foo {\n"
11147                "#ifdef FOO\n"
11148                "#endif\n"
11149                "private:\n"
11150                "  int i;\n"
11151                "#ifdef FOO\n"
11152                "private:\n"
11153                "#endif\n"
11154                "  int j;\n"
11155                "};\n",
11156                Style);
11157 
11158   FormatStyle NoEmptyLines = getLLVMStyle();
11159   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11160   verifyFormat("struct foo {\n"
11161                "private:\n"
11162                "  void f() {}\n"
11163                "\n"
11164                "private:\n"
11165                "  int i;\n"
11166                "\n"
11167                "public:\n"
11168                "protected:\n"
11169                "  int j;\n"
11170                "};\n",
11171                NoEmptyLines);
11172 
11173   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11174   verifyFormat("struct foo {\n"
11175                "private:\n"
11176                "  void f() {}\n"
11177                "private:\n"
11178                "  int i;\n"
11179                "public:\n"
11180                "protected:\n"
11181                "  int j;\n"
11182                "};\n",
11183                NoEmptyLines);
11184 
11185   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11186   verifyFormat("struct foo {\n"
11187                "private:\n"
11188                "  void f() {}\n"
11189                "\n"
11190                "private:\n"
11191                "  int i;\n"
11192                "\n"
11193                "public:\n"
11194                "\n"
11195                "protected:\n"
11196                "  int j;\n"
11197                "};\n",
11198                NoEmptyLines);
11199 }
11200 
11201 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11202 
11203   FormatStyle Style = getLLVMStyle();
11204   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11205   verifyFormat("struct foo {\n"
11206                "private:\n"
11207                "  void f() {}\n"
11208                "\n"
11209                "private:\n"
11210                "  int i;\n"
11211                "\n"
11212                "protected:\n"
11213                "  int j;\n"
11214                "};\n",
11215                Style);
11216 
11217   // Check if lines are removed.
11218   verifyFormat("struct foo {\n"
11219                "private:\n"
11220                "  void f() {}\n"
11221                "\n"
11222                "private:\n"
11223                "  int i;\n"
11224                "\n"
11225                "protected:\n"
11226                "  int j;\n"
11227                "};\n",
11228                "struct foo {\n"
11229                "private:\n"
11230                "\n"
11231                "  void f() {}\n"
11232                "\n"
11233                "private:\n"
11234                "\n"
11235                "  int i;\n"
11236                "\n"
11237                "protected:\n"
11238                "\n"
11239                "  int j;\n"
11240                "};\n",
11241                Style);
11242 
11243   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11244   verifyFormat("struct foo {\n"
11245                "private:\n"
11246                "\n"
11247                "  void f() {}\n"
11248                "\n"
11249                "private:\n"
11250                "\n"
11251                "  int i;\n"
11252                "\n"
11253                "protected:\n"
11254                "\n"
11255                "  int j;\n"
11256                "};\n",
11257                Style);
11258 
11259   // Check if lines are added.
11260   verifyFormat("struct foo {\n"
11261                "private:\n"
11262                "\n"
11263                "  void f() {}\n"
11264                "\n"
11265                "private:\n"
11266                "\n"
11267                "  int i;\n"
11268                "\n"
11269                "protected:\n"
11270                "\n"
11271                "  int j;\n"
11272                "};\n",
11273                "struct foo {\n"
11274                "private:\n"
11275                "  void f() {}\n"
11276                "\n"
11277                "private:\n"
11278                "  int i;\n"
11279                "\n"
11280                "protected:\n"
11281                "  int j;\n"
11282                "};\n",
11283                Style);
11284 
11285   // Leave tests rely on the code layout, test::messUp can not be used.
11286   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11287   Style.MaxEmptyLinesToKeep = 0u;
11288   verifyFormat("struct foo {\n"
11289                "private:\n"
11290                "  void f() {}\n"
11291                "\n"
11292                "private:\n"
11293                "  int i;\n"
11294                "\n"
11295                "protected:\n"
11296                "  int j;\n"
11297                "};\n",
11298                Style);
11299 
11300   // Check if MaxEmptyLinesToKeep is respected.
11301   EXPECT_EQ("struct foo {\n"
11302             "private:\n"
11303             "  void f() {}\n"
11304             "\n"
11305             "private:\n"
11306             "  int i;\n"
11307             "\n"
11308             "protected:\n"
11309             "  int j;\n"
11310             "};\n",
11311             format("struct foo {\n"
11312                    "private:\n"
11313                    "\n\n\n"
11314                    "  void f() {}\n"
11315                    "\n"
11316                    "private:\n"
11317                    "\n\n\n"
11318                    "  int i;\n"
11319                    "\n"
11320                    "protected:\n"
11321                    "\n\n\n"
11322                    "  int j;\n"
11323                    "};\n",
11324                    Style));
11325 
11326   Style.MaxEmptyLinesToKeep = 1u;
11327   EXPECT_EQ("struct foo {\n"
11328             "private:\n"
11329             "\n"
11330             "  void f() {}\n"
11331             "\n"
11332             "private:\n"
11333             "\n"
11334             "  int i;\n"
11335             "\n"
11336             "protected:\n"
11337             "\n"
11338             "  int j;\n"
11339             "};\n",
11340             format("struct foo {\n"
11341                    "private:\n"
11342                    "\n"
11343                    "  void f() {}\n"
11344                    "\n"
11345                    "private:\n"
11346                    "\n"
11347                    "  int i;\n"
11348                    "\n"
11349                    "protected:\n"
11350                    "\n"
11351                    "  int j;\n"
11352                    "};\n",
11353                    Style));
11354   // Check if no lines are kept.
11355   EXPECT_EQ("struct foo {\n"
11356             "private:\n"
11357             "  void f() {}\n"
11358             "\n"
11359             "private:\n"
11360             "  int i;\n"
11361             "\n"
11362             "protected:\n"
11363             "  int j;\n"
11364             "};\n",
11365             format("struct foo {\n"
11366                    "private:\n"
11367                    "  void f() {}\n"
11368                    "\n"
11369                    "private:\n"
11370                    "  int i;\n"
11371                    "\n"
11372                    "protected:\n"
11373                    "  int j;\n"
11374                    "};\n",
11375                    Style));
11376   // Check if MaxEmptyLinesToKeep is respected.
11377   EXPECT_EQ("struct foo {\n"
11378             "private:\n"
11379             "\n"
11380             "  void f() {}\n"
11381             "\n"
11382             "private:\n"
11383             "\n"
11384             "  int i;\n"
11385             "\n"
11386             "protected:\n"
11387             "\n"
11388             "  int j;\n"
11389             "};\n",
11390             format("struct foo {\n"
11391                    "private:\n"
11392                    "\n\n\n"
11393                    "  void f() {}\n"
11394                    "\n"
11395                    "private:\n"
11396                    "\n\n\n"
11397                    "  int i;\n"
11398                    "\n"
11399                    "protected:\n"
11400                    "\n\n\n"
11401                    "  int j;\n"
11402                    "};\n",
11403                    Style));
11404 
11405   Style.MaxEmptyLinesToKeep = 10u;
11406   EXPECT_EQ("struct foo {\n"
11407             "private:\n"
11408             "\n\n\n"
11409             "  void f() {}\n"
11410             "\n"
11411             "private:\n"
11412             "\n\n\n"
11413             "  int i;\n"
11414             "\n"
11415             "protected:\n"
11416             "\n\n\n"
11417             "  int j;\n"
11418             "};\n",
11419             format("struct foo {\n"
11420                    "private:\n"
11421                    "\n\n\n"
11422                    "  void f() {}\n"
11423                    "\n"
11424                    "private:\n"
11425                    "\n\n\n"
11426                    "  int i;\n"
11427                    "\n"
11428                    "protected:\n"
11429                    "\n\n\n"
11430                    "  int j;\n"
11431                    "};\n",
11432                    Style));
11433 
11434   // Test with comments.
11435   Style = getLLVMStyle();
11436   verifyFormat("struct foo {\n"
11437                "private:\n"
11438                "  // comment\n"
11439                "  void f() {}\n"
11440                "\n"
11441                "private: /* comment */\n"
11442                "  int i;\n"
11443                "};\n",
11444                Style);
11445   verifyFormat("struct foo {\n"
11446                "private:\n"
11447                "  // comment\n"
11448                "  void f() {}\n"
11449                "\n"
11450                "private: /* comment */\n"
11451                "  int i;\n"
11452                "};\n",
11453                "struct foo {\n"
11454                "private:\n"
11455                "\n"
11456                "  // comment\n"
11457                "  void f() {}\n"
11458                "\n"
11459                "private: /* comment */\n"
11460                "\n"
11461                "  int i;\n"
11462                "};\n",
11463                Style);
11464 
11465   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11466   verifyFormat("struct foo {\n"
11467                "private:\n"
11468                "\n"
11469                "  // comment\n"
11470                "  void f() {}\n"
11471                "\n"
11472                "private: /* comment */\n"
11473                "\n"
11474                "  int i;\n"
11475                "};\n",
11476                "struct foo {\n"
11477                "private:\n"
11478                "  // comment\n"
11479                "  void f() {}\n"
11480                "\n"
11481                "private: /* comment */\n"
11482                "  int i;\n"
11483                "};\n",
11484                Style);
11485   verifyFormat("struct foo {\n"
11486                "private:\n"
11487                "\n"
11488                "  // comment\n"
11489                "  void f() {}\n"
11490                "\n"
11491                "private: /* comment */\n"
11492                "\n"
11493                "  int i;\n"
11494                "};\n",
11495                Style);
11496 
11497   // Test with preprocessor defines.
11498   Style = getLLVMStyle();
11499   verifyFormat("struct foo {\n"
11500                "private:\n"
11501                "#ifdef FOO\n"
11502                "#endif\n"
11503                "  void f() {}\n"
11504                "};\n",
11505                Style);
11506   verifyFormat("struct foo {\n"
11507                "private:\n"
11508                "#ifdef FOO\n"
11509                "#endif\n"
11510                "  void f() {}\n"
11511                "};\n",
11512                "struct foo {\n"
11513                "private:\n"
11514                "\n"
11515                "#ifdef FOO\n"
11516                "#endif\n"
11517                "  void f() {}\n"
11518                "};\n",
11519                Style);
11520 
11521   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11522   verifyFormat("struct foo {\n"
11523                "private:\n"
11524                "\n"
11525                "#ifdef FOO\n"
11526                "#endif\n"
11527                "  void f() {}\n"
11528                "};\n",
11529                "struct foo {\n"
11530                "private:\n"
11531                "#ifdef FOO\n"
11532                "#endif\n"
11533                "  void f() {}\n"
11534                "};\n",
11535                Style);
11536   verifyFormat("struct foo {\n"
11537                "private:\n"
11538                "\n"
11539                "#ifdef FOO\n"
11540                "#endif\n"
11541                "  void f() {}\n"
11542                "};\n",
11543                Style);
11544 }
11545 
11546 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11547   // Combined tests of EmptyLineAfterAccessModifier and
11548   // EmptyLineBeforeAccessModifier.
11549   FormatStyle Style = getLLVMStyle();
11550   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11551   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11552   verifyFormat("struct foo {\n"
11553                "private:\n"
11554                "\n"
11555                "protected:\n"
11556                "};\n",
11557                Style);
11558 
11559   Style.MaxEmptyLinesToKeep = 10u;
11560   // Both remove all new lines.
11561   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11562   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11563   verifyFormat("struct foo {\n"
11564                "private:\n"
11565                "protected:\n"
11566                "};\n",
11567                "struct foo {\n"
11568                "private:\n"
11569                "\n\n\n"
11570                "protected:\n"
11571                "};\n",
11572                Style);
11573 
11574   // Leave tests rely on the code layout, test::messUp can not be used.
11575   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11576   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11577   Style.MaxEmptyLinesToKeep = 10u;
11578   EXPECT_EQ("struct foo {\n"
11579             "private:\n"
11580             "\n\n\n"
11581             "protected:\n"
11582             "};\n",
11583             format("struct foo {\n"
11584                    "private:\n"
11585                    "\n\n\n"
11586                    "protected:\n"
11587                    "};\n",
11588                    Style));
11589   Style.MaxEmptyLinesToKeep = 3u;
11590   EXPECT_EQ("struct foo {\n"
11591             "private:\n"
11592             "\n\n\n"
11593             "protected:\n"
11594             "};\n",
11595             format("struct foo {\n"
11596                    "private:\n"
11597                    "\n\n\n"
11598                    "protected:\n"
11599                    "};\n",
11600                    Style));
11601   Style.MaxEmptyLinesToKeep = 1u;
11602   EXPECT_EQ("struct foo {\n"
11603             "private:\n"
11604             "\n\n\n"
11605             "protected:\n"
11606             "};\n",
11607             format("struct foo {\n"
11608                    "private:\n"
11609                    "\n\n\n"
11610                    "protected:\n"
11611                    "};\n",
11612                    Style)); // Based on new lines in original document and not
11613                             // on the setting.
11614 
11615   Style.MaxEmptyLinesToKeep = 10u;
11616   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11617   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11618   // Newlines are kept if they are greater than zero,
11619   // test::messUp removes all new lines which changes the logic
11620   EXPECT_EQ("struct foo {\n"
11621             "private:\n"
11622             "\n\n\n"
11623             "protected:\n"
11624             "};\n",
11625             format("struct foo {\n"
11626                    "private:\n"
11627                    "\n\n\n"
11628                    "protected:\n"
11629                    "};\n",
11630                    Style));
11631 
11632   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11633   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11634   // test::messUp removes all new lines which changes the logic
11635   EXPECT_EQ("struct foo {\n"
11636             "private:\n"
11637             "\n\n\n"
11638             "protected:\n"
11639             "};\n",
11640             format("struct foo {\n"
11641                    "private:\n"
11642                    "\n\n\n"
11643                    "protected:\n"
11644                    "};\n",
11645                    Style));
11646 
11647   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11648   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11649   EXPECT_EQ("struct foo {\n"
11650             "private:\n"
11651             "\n\n\n"
11652             "protected:\n"
11653             "};\n",
11654             format("struct foo {\n"
11655                    "private:\n"
11656                    "\n\n\n"
11657                    "protected:\n"
11658                    "};\n",
11659                    Style)); // test::messUp removes all new lines which changes
11660                             // the logic.
11661 
11662   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11663   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11664   verifyFormat("struct foo {\n"
11665                "private:\n"
11666                "protected:\n"
11667                "};\n",
11668                "struct foo {\n"
11669                "private:\n"
11670                "\n\n\n"
11671                "protected:\n"
11672                "};\n",
11673                Style);
11674 
11675   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11676   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11677   EXPECT_EQ("struct foo {\n"
11678             "private:\n"
11679             "\n\n\n"
11680             "protected:\n"
11681             "};\n",
11682             format("struct foo {\n"
11683                    "private:\n"
11684                    "\n\n\n"
11685                    "protected:\n"
11686                    "};\n",
11687                    Style)); // test::messUp removes all new lines which changes
11688                             // the logic.
11689 
11690   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11691   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11692   verifyFormat("struct foo {\n"
11693                "private:\n"
11694                "protected:\n"
11695                "};\n",
11696                "struct foo {\n"
11697                "private:\n"
11698                "\n\n\n"
11699                "protected:\n"
11700                "};\n",
11701                Style);
11702 
11703   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11704   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11705   verifyFormat("struct foo {\n"
11706                "private:\n"
11707                "protected:\n"
11708                "};\n",
11709                "struct foo {\n"
11710                "private:\n"
11711                "\n\n\n"
11712                "protected:\n"
11713                "};\n",
11714                Style);
11715 
11716   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11717   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11718   verifyFormat("struct foo {\n"
11719                "private:\n"
11720                "protected:\n"
11721                "};\n",
11722                "struct foo {\n"
11723                "private:\n"
11724                "\n\n\n"
11725                "protected:\n"
11726                "};\n",
11727                Style);
11728 
11729   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11730   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11731   verifyFormat("struct foo {\n"
11732                "private:\n"
11733                "protected:\n"
11734                "};\n",
11735                "struct foo {\n"
11736                "private:\n"
11737                "\n\n\n"
11738                "protected:\n"
11739                "};\n",
11740                Style);
11741 }
11742 
11743 TEST_F(FormatTest, FormatsArrays) {
11744   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11745                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11746   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11747                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11748   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11749                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11750   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11751                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11752   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11753                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11754   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11755                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11756                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11757   verifyFormat(
11758       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11759       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11760       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11761   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11762                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11763 
11764   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11765                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11766   verifyFormat(
11767       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11768       "                                  .aaaaaaa[0]\n"
11769       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11770   verifyFormat("a[::b::c];");
11771 
11772   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11773 
11774   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11775   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11776 }
11777 
11778 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11779   verifyFormat("(a)->b();");
11780   verifyFormat("--a;");
11781 }
11782 
11783 TEST_F(FormatTest, HandlesIncludeDirectives) {
11784   verifyFormat("#include <string>\n"
11785                "#include <a/b/c.h>\n"
11786                "#include \"a/b/string\"\n"
11787                "#include \"string.h\"\n"
11788                "#include \"string.h\"\n"
11789                "#include <a-a>\n"
11790                "#include < path with space >\n"
11791                "#include_next <test.h>"
11792                "#include \"abc.h\" // this is included for ABC\n"
11793                "#include \"some long include\" // with a comment\n"
11794                "#include \"some very long include path\"\n"
11795                "#include <some/very/long/include/path>\n",
11796                getLLVMStyleWithColumns(35));
11797   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11798   EXPECT_EQ("#include <a>", format("#include<a>"));
11799 
11800   verifyFormat("#import <string>");
11801   verifyFormat("#import <a/b/c.h>");
11802   verifyFormat("#import \"a/b/string\"");
11803   verifyFormat("#import \"string.h\"");
11804   verifyFormat("#import \"string.h\"");
11805   verifyFormat("#if __has_include(<strstream>)\n"
11806                "#include <strstream>\n"
11807                "#endif");
11808 
11809   verifyFormat("#define MY_IMPORT <a/b>");
11810 
11811   verifyFormat("#if __has_include(<a/b>)");
11812   verifyFormat("#if __has_include_next(<a/b>)");
11813   verifyFormat("#define F __has_include(<a/b>)");
11814   verifyFormat("#define F __has_include_next(<a/b>)");
11815 
11816   // Protocol buffer definition or missing "#".
11817   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
11818                getLLVMStyleWithColumns(30));
11819 
11820   FormatStyle Style = getLLVMStyle();
11821   Style.AlwaysBreakBeforeMultilineStrings = true;
11822   Style.ColumnLimit = 0;
11823   verifyFormat("#import \"abc.h\"", Style);
11824 
11825   // But 'import' might also be a regular C++ namespace.
11826   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11827                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11828 }
11829 
11830 //===----------------------------------------------------------------------===//
11831 // Error recovery tests.
11832 //===----------------------------------------------------------------------===//
11833 
11834 TEST_F(FormatTest, IncompleteParameterLists) {
11835   FormatStyle NoBinPacking = getLLVMStyle();
11836   NoBinPacking.BinPackParameters = false;
11837   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
11838                "                        double *min_x,\n"
11839                "                        double *max_x,\n"
11840                "                        double *min_y,\n"
11841                "                        double *max_y,\n"
11842                "                        double *min_z,\n"
11843                "                        double *max_z, ) {}",
11844                NoBinPacking);
11845 }
11846 
11847 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
11848   verifyFormat("void f() { return; }\n42");
11849   verifyFormat("void f() {\n"
11850                "  if (0)\n"
11851                "    return;\n"
11852                "}\n"
11853                "42");
11854   verifyFormat("void f() { return }\n42");
11855   verifyFormat("void f() {\n"
11856                "  if (0)\n"
11857                "    return\n"
11858                "}\n"
11859                "42");
11860 }
11861 
11862 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
11863   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
11864   EXPECT_EQ("void f() {\n"
11865             "  if (a)\n"
11866             "    return\n"
11867             "}",
11868             format("void  f  (  )  {  if  ( a )  return  }"));
11869   EXPECT_EQ("namespace N {\n"
11870             "void f()\n"
11871             "}",
11872             format("namespace  N  {  void f()  }"));
11873   EXPECT_EQ("namespace N {\n"
11874             "void f() {}\n"
11875             "void g()\n"
11876             "} // namespace N",
11877             format("namespace N  { void f( ) { } void g( ) }"));
11878 }
11879 
11880 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
11881   verifyFormat("int aaaaaaaa =\n"
11882                "    // Overlylongcomment\n"
11883                "    b;",
11884                getLLVMStyleWithColumns(20));
11885   verifyFormat("function(\n"
11886                "    ShortArgument,\n"
11887                "    LoooooooooooongArgument);\n",
11888                getLLVMStyleWithColumns(20));
11889 }
11890 
11891 TEST_F(FormatTest, IncorrectAccessSpecifier) {
11892   verifyFormat("public:");
11893   verifyFormat("class A {\n"
11894                "public\n"
11895                "  void f() {}\n"
11896                "};");
11897   verifyFormat("public\n"
11898                "int qwerty;");
11899   verifyFormat("public\n"
11900                "B {}");
11901   verifyFormat("public\n"
11902                "{}");
11903   verifyFormat("public\n"
11904                "B { int x; }");
11905 }
11906 
11907 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
11908   verifyFormat("{");
11909   verifyFormat("#})");
11910   verifyNoCrash("(/**/[:!] ?[).");
11911 }
11912 
11913 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
11914   // Found by oss-fuzz:
11915   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
11916   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
11917   Style.ColumnLimit = 60;
11918   verifyNoCrash(
11919       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
11920       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
11921       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
11922       Style);
11923 }
11924 
11925 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
11926   verifyFormat("do {\n}");
11927   verifyFormat("do {\n}\n"
11928                "f();");
11929   verifyFormat("do {\n}\n"
11930                "wheeee(fun);");
11931   verifyFormat("do {\n"
11932                "  f();\n"
11933                "}");
11934 }
11935 
11936 TEST_F(FormatTest, IncorrectCodeMissingParens) {
11937   verifyFormat("if {\n  foo;\n  foo();\n}");
11938   verifyFormat("switch {\n  foo;\n  foo();\n}");
11939   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
11940   verifyFormat("while {\n  foo;\n  foo();\n}");
11941   verifyFormat("do {\n  foo;\n  foo();\n} while;");
11942 }
11943 
11944 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
11945   verifyIncompleteFormat("namespace {\n"
11946                          "class Foo { Foo (\n"
11947                          "};\n"
11948                          "} // namespace");
11949 }
11950 
11951 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
11952   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
11953   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
11954   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
11955   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
11956 
11957   EXPECT_EQ("{\n"
11958             "  {\n"
11959             "    breakme(\n"
11960             "        qwe);\n"
11961             "  }\n",
11962             format("{\n"
11963                    "    {\n"
11964                    " breakme(qwe);\n"
11965                    "}\n",
11966                    getLLVMStyleWithColumns(10)));
11967 }
11968 
11969 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
11970   verifyFormat("int x = {\n"
11971                "    avariable,\n"
11972                "    b(alongervariable)};",
11973                getLLVMStyleWithColumns(25));
11974 }
11975 
11976 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
11977   verifyFormat("return (a)(b){1, 2, 3};");
11978 }
11979 
11980 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
11981   verifyFormat("vector<int> x{1, 2, 3, 4};");
11982   verifyFormat("vector<int> x{\n"
11983                "    1,\n"
11984                "    2,\n"
11985                "    3,\n"
11986                "    4,\n"
11987                "};");
11988   verifyFormat("vector<T> x{{}, {}, {}, {}};");
11989   verifyFormat("f({1, 2});");
11990   verifyFormat("auto v = Foo{-1};");
11991   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
11992   verifyFormat("Class::Class : member{1, 2, 3} {}");
11993   verifyFormat("new vector<int>{1, 2, 3};");
11994   verifyFormat("new int[3]{1, 2, 3};");
11995   verifyFormat("new int{1};");
11996   verifyFormat("return {arg1, arg2};");
11997   verifyFormat("return {arg1, SomeType{parameter}};");
11998   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
11999   verifyFormat("new T{arg1, arg2};");
12000   verifyFormat("f(MyMap[{composite, key}]);");
12001   verifyFormat("class Class {\n"
12002                "  T member = {arg1, arg2};\n"
12003                "};");
12004   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
12005   verifyFormat("const struct A a = {.a = 1, .b = 2};");
12006   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
12007   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
12008   verifyFormat("int a = std::is_integral<int>{} + 0;");
12009 
12010   verifyFormat("int foo(int i) { return fo1{}(i); }");
12011   verifyFormat("int foo(int i) { return fo1{}(i); }");
12012   verifyFormat("auto i = decltype(x){};");
12013   verifyFormat("auto i = typeof(x){};");
12014   verifyFormat("auto i = _Atomic(x){};");
12015   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
12016   verifyFormat("Node n{1, Node{1000}, //\n"
12017                "       2};");
12018   verifyFormat("Aaaa aaaaaaa{\n"
12019                "    {\n"
12020                "        aaaa,\n"
12021                "    },\n"
12022                "};");
12023   verifyFormat("class C : public D {\n"
12024                "  SomeClass SC{2};\n"
12025                "};");
12026   verifyFormat("class C : public A {\n"
12027                "  class D : public B {\n"
12028                "    void f() { int i{2}; }\n"
12029                "  };\n"
12030                "};");
12031   verifyFormat("#define A {a, a},");
12032   // Don't confuse braced list initializers with compound statements.
12033   verifyFormat(
12034       "class A {\n"
12035       "  A() : a{} {}\n"
12036       "  A(int b) : b(b) {}\n"
12037       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12038       "  int a, b;\n"
12039       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12040       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12041       "{}\n"
12042       "};");
12043 
12044   // Avoid breaking between equal sign and opening brace
12045   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12046   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12047   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12048                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12049                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12050                "     {\"ccccccccccccccccccccc\", 2}};",
12051                AvoidBreakingFirstArgument);
12052 
12053   // Binpacking only if there is no trailing comma
12054   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12055                "                      cccccccccc, dddddddddd};",
12056                getLLVMStyleWithColumns(50));
12057   verifyFormat("const Aaaaaa aaaaa = {\n"
12058                "    aaaaaaaaaaa,\n"
12059                "    bbbbbbbbbbb,\n"
12060                "    ccccccccccc,\n"
12061                "    ddddddddddd,\n"
12062                "};",
12063                getLLVMStyleWithColumns(50));
12064 
12065   // Cases where distinguising braced lists and blocks is hard.
12066   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12067   verifyFormat("void f() {\n"
12068                "  return; // comment\n"
12069                "}\n"
12070                "SomeType t;");
12071   verifyFormat("void f() {\n"
12072                "  if (a) {\n"
12073                "    f();\n"
12074                "  }\n"
12075                "}\n"
12076                "SomeType t;");
12077 
12078   // In combination with BinPackArguments = false.
12079   FormatStyle NoBinPacking = getLLVMStyle();
12080   NoBinPacking.BinPackArguments = false;
12081   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12082                "                      bbbbb,\n"
12083                "                      ccccc,\n"
12084                "                      ddddd,\n"
12085                "                      eeeee,\n"
12086                "                      ffffff,\n"
12087                "                      ggggg,\n"
12088                "                      hhhhhh,\n"
12089                "                      iiiiii,\n"
12090                "                      jjjjjj,\n"
12091                "                      kkkkkk};",
12092                NoBinPacking);
12093   verifyFormat("const Aaaaaa aaaaa = {\n"
12094                "    aaaaa,\n"
12095                "    bbbbb,\n"
12096                "    ccccc,\n"
12097                "    ddddd,\n"
12098                "    eeeee,\n"
12099                "    ffffff,\n"
12100                "    ggggg,\n"
12101                "    hhhhhh,\n"
12102                "    iiiiii,\n"
12103                "    jjjjjj,\n"
12104                "    kkkkkk,\n"
12105                "};",
12106                NoBinPacking);
12107   verifyFormat(
12108       "const Aaaaaa aaaaa = {\n"
12109       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12110       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12111       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12112       "};",
12113       NoBinPacking);
12114 
12115   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12116   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12117             "    CDDDP83848_BMCR_REGISTER,\n"
12118             "    CDDDP83848_BMSR_REGISTER,\n"
12119             "    CDDDP83848_RBR_REGISTER};",
12120             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12121                    "                                CDDDP83848_BMSR_REGISTER,\n"
12122                    "                                CDDDP83848_RBR_REGISTER};",
12123                    NoBinPacking));
12124 
12125   // FIXME: The alignment of these trailing comments might be bad. Then again,
12126   // this might be utterly useless in real code.
12127   verifyFormat("Constructor::Constructor()\n"
12128                "    : some_value{         //\n"
12129                "                 aaaaaaa, //\n"
12130                "                 bbbbbbb} {}");
12131 
12132   // In braced lists, the first comment is always assumed to belong to the
12133   // first element. Thus, it can be moved to the next or previous line as
12134   // appropriate.
12135   EXPECT_EQ("function({// First element:\n"
12136             "          1,\n"
12137             "          // Second element:\n"
12138             "          2});",
12139             format("function({\n"
12140                    "    // First element:\n"
12141                    "    1,\n"
12142                    "    // Second element:\n"
12143                    "    2});"));
12144   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12145             "    // First element:\n"
12146             "    1,\n"
12147             "    // Second element:\n"
12148             "    2};",
12149             format("std::vector<int> MyNumbers{// First element:\n"
12150                    "                           1,\n"
12151                    "                           // Second element:\n"
12152                    "                           2};",
12153                    getLLVMStyleWithColumns(30)));
12154   // A trailing comma should still lead to an enforced line break and no
12155   // binpacking.
12156   EXPECT_EQ("vector<int> SomeVector = {\n"
12157             "    // aaa\n"
12158             "    1,\n"
12159             "    2,\n"
12160             "};",
12161             format("vector<int> SomeVector = { // aaa\n"
12162                    "    1, 2, };"));
12163 
12164   // C++11 brace initializer list l-braces should not be treated any differently
12165   // when breaking before lambda bodies is enabled
12166   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12167   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12168   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12169   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12170   verifyFormat(
12171       "std::runtime_error{\n"
12172       "    \"Long string which will force a break onto the next line...\"};",
12173       BreakBeforeLambdaBody);
12174 
12175   FormatStyle ExtraSpaces = getLLVMStyle();
12176   ExtraSpaces.Cpp11BracedListStyle = false;
12177   ExtraSpaces.ColumnLimit = 75;
12178   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12179   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12180   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12181   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12182   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12183   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12184   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12185   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12186   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12187   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12188   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12189   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12190   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12191   verifyFormat("class Class {\n"
12192                "  T member = { arg1, arg2 };\n"
12193                "};",
12194                ExtraSpaces);
12195   verifyFormat(
12196       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12197       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12198       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12199       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12200       ExtraSpaces);
12201   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12202   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12203                ExtraSpaces);
12204   verifyFormat(
12205       "someFunction(OtherParam,\n"
12206       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12207       "                         param1, param2,\n"
12208       "                         // comment 2\n"
12209       "                         param3, param4 });",
12210       ExtraSpaces);
12211   verifyFormat(
12212       "std::this_thread::sleep_for(\n"
12213       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12214       ExtraSpaces);
12215   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12216                "    aaaaaaa,\n"
12217                "    aaaaaaaaaa,\n"
12218                "    aaaaa,\n"
12219                "    aaaaaaaaaaaaaaa,\n"
12220                "    aaa,\n"
12221                "    aaaaaaaaaa,\n"
12222                "    a,\n"
12223                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12224                "    aaaaaaaaaaaa,\n"
12225                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12226                "    aaaaaaa,\n"
12227                "    a};");
12228   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12229   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12230   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12231 
12232   // Avoid breaking between initializer/equal sign and opening brace
12233   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12234   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12235                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12236                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12237                "  { \"ccccccccccccccccccccc\", 2 }\n"
12238                "};",
12239                ExtraSpaces);
12240   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12241                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12242                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12243                "  { \"ccccccccccccccccccccc\", 2 }\n"
12244                "};",
12245                ExtraSpaces);
12246 
12247   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12248   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12249   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12250   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12251 
12252   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12253   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12254   SpaceBetweenBraces.SpacesInParentheses = true;
12255   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12256   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12257   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12258   verifyFormat("vector< int > x{ // comment 1\n"
12259                "                 1, 2, 3, 4 };",
12260                SpaceBetweenBraces);
12261   SpaceBetweenBraces.ColumnLimit = 20;
12262   EXPECT_EQ("vector< int > x{\n"
12263             "    1, 2, 3, 4 };",
12264             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12265   SpaceBetweenBraces.ColumnLimit = 24;
12266   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12267             "                 3, 4 };",
12268             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12269   EXPECT_EQ("vector< int > x{\n"
12270             "    1,\n"
12271             "    2,\n"
12272             "    3,\n"
12273             "    4,\n"
12274             "};",
12275             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12276   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12277   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12278   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12279 }
12280 
12281 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12282   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12283                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12284                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12285                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12286                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12287                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12288   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12289                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12290                "                 1, 22, 333, 4444, 55555, //\n"
12291                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12292                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12293   verifyFormat(
12294       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12295       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12296       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12297       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12298       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12299       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12300       "                 7777777};");
12301   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12302                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12303                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12304   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12305                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12306                "    // Separating comment.\n"
12307                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12308   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12309                "    // Leading comment\n"
12310                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12311                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12312   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12313                "                 1, 1, 1, 1};",
12314                getLLVMStyleWithColumns(39));
12315   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12316                "                 1, 1, 1, 1};",
12317                getLLVMStyleWithColumns(38));
12318   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12319                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12320                getLLVMStyleWithColumns(43));
12321   verifyFormat(
12322       "static unsigned SomeValues[10][3] = {\n"
12323       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12324       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12325   verifyFormat("static auto fields = new vector<string>{\n"
12326                "    \"aaaaaaaaaaaaa\",\n"
12327                "    \"aaaaaaaaaaaaa\",\n"
12328                "    \"aaaaaaaaaaaa\",\n"
12329                "    \"aaaaaaaaaaaaaa\",\n"
12330                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12331                "    \"aaaaaaaaaaaa\",\n"
12332                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12333                "};");
12334   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12335   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12336                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12337                "                 3, cccccccccccccccccccccc};",
12338                getLLVMStyleWithColumns(60));
12339 
12340   // Trailing commas.
12341   verifyFormat("vector<int> x = {\n"
12342                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12343                "};",
12344                getLLVMStyleWithColumns(39));
12345   verifyFormat("vector<int> x = {\n"
12346                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12347                "};",
12348                getLLVMStyleWithColumns(39));
12349   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12350                "                 1, 1, 1, 1,\n"
12351                "                 /**/ /**/};",
12352                getLLVMStyleWithColumns(39));
12353 
12354   // Trailing comment in the first line.
12355   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12356                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12357                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12358                "    11111111,   22222222,   333333333,   44444444};");
12359   // Trailing comment in the last line.
12360   verifyFormat("int aaaaa[] = {\n"
12361                "    1, 2, 3, // comment\n"
12362                "    4, 5, 6  // comment\n"
12363                "};");
12364 
12365   // With nested lists, we should either format one item per line or all nested
12366   // lists one on line.
12367   // FIXME: For some nested lists, we can do better.
12368   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12369                "        {aaaaaaaaaaaaaaaaaaa},\n"
12370                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12371                "        {aaaaaaaaaaaaaaaaa}};",
12372                getLLVMStyleWithColumns(60));
12373   verifyFormat(
12374       "SomeStruct my_struct_array = {\n"
12375       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12376       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12377       "    {aaa, aaa},\n"
12378       "    {aaa, aaa},\n"
12379       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12380       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12381       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12382 
12383   // No column layout should be used here.
12384   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12385                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12386 
12387   verifyNoCrash("a<,");
12388 
12389   // No braced initializer here.
12390   verifyFormat("void f() {\n"
12391                "  struct Dummy {};\n"
12392                "  f(v);\n"
12393                "}");
12394 
12395   // Long lists should be formatted in columns even if they are nested.
12396   verifyFormat(
12397       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12398       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12399       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12400       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12401       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12402       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12403 
12404   // Allow "single-column" layout even if that violates the column limit. There
12405   // isn't going to be a better way.
12406   verifyFormat("std::vector<int> a = {\n"
12407                "    aaaaaaaa,\n"
12408                "    aaaaaaaa,\n"
12409                "    aaaaaaaa,\n"
12410                "    aaaaaaaa,\n"
12411                "    aaaaaaaaaa,\n"
12412                "    aaaaaaaa,\n"
12413                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12414                getLLVMStyleWithColumns(30));
12415   verifyFormat("vector<int> aaaa = {\n"
12416                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12417                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12418                "    aaaaaa.aaaaaaa,\n"
12419                "    aaaaaa.aaaaaaa,\n"
12420                "    aaaaaa.aaaaaaa,\n"
12421                "    aaaaaa.aaaaaaa,\n"
12422                "};");
12423 
12424   // Don't create hanging lists.
12425   verifyFormat("someFunction(Param, {List1, List2,\n"
12426                "                     List3});",
12427                getLLVMStyleWithColumns(35));
12428   verifyFormat("someFunction(Param, Param,\n"
12429                "             {List1, List2,\n"
12430                "              List3});",
12431                getLLVMStyleWithColumns(35));
12432   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12433                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12434 }
12435 
12436 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12437   FormatStyle DoNotMerge = getLLVMStyle();
12438   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12439 
12440   verifyFormat("void f() { return 42; }");
12441   verifyFormat("void f() {\n"
12442                "  return 42;\n"
12443                "}",
12444                DoNotMerge);
12445   verifyFormat("void f() {\n"
12446                "  // Comment\n"
12447                "}");
12448   verifyFormat("{\n"
12449                "#error {\n"
12450                "  int a;\n"
12451                "}");
12452   verifyFormat("{\n"
12453                "  int a;\n"
12454                "#error {\n"
12455                "}");
12456   verifyFormat("void f() {} // comment");
12457   verifyFormat("void f() { int a; } // comment");
12458   verifyFormat("void f() {\n"
12459                "} // comment",
12460                DoNotMerge);
12461   verifyFormat("void f() {\n"
12462                "  int a;\n"
12463                "} // comment",
12464                DoNotMerge);
12465   verifyFormat("void f() {\n"
12466                "} // comment",
12467                getLLVMStyleWithColumns(15));
12468 
12469   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12470   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12471 
12472   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12473   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12474   verifyFormat("class C {\n"
12475                "  C()\n"
12476                "      : iiiiiiii(nullptr),\n"
12477                "        kkkkkkk(nullptr),\n"
12478                "        mmmmmmm(nullptr),\n"
12479                "        nnnnnnn(nullptr) {}\n"
12480                "};",
12481                getGoogleStyle());
12482 
12483   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12484   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12485   EXPECT_EQ("class C {\n"
12486             "  A() : b(0) {}\n"
12487             "};",
12488             format("class C{A():b(0){}};", NoColumnLimit));
12489   EXPECT_EQ("A()\n"
12490             "    : b(0) {\n"
12491             "}",
12492             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12493 
12494   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12495   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12496       FormatStyle::SFS_None;
12497   EXPECT_EQ("A()\n"
12498             "    : b(0) {\n"
12499             "}",
12500             format("A():b(0){}", DoNotMergeNoColumnLimit));
12501   EXPECT_EQ("A()\n"
12502             "    : b(0) {\n"
12503             "}",
12504             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12505 
12506   verifyFormat("#define A          \\\n"
12507                "  void f() {       \\\n"
12508                "    int i;         \\\n"
12509                "  }",
12510                getLLVMStyleWithColumns(20));
12511   verifyFormat("#define A           \\\n"
12512                "  void f() { int i; }",
12513                getLLVMStyleWithColumns(21));
12514   verifyFormat("#define A            \\\n"
12515                "  void f() {         \\\n"
12516                "    int i;           \\\n"
12517                "  }                  \\\n"
12518                "  int j;",
12519                getLLVMStyleWithColumns(22));
12520   verifyFormat("#define A             \\\n"
12521                "  void f() { int i; } \\\n"
12522                "  int j;",
12523                getLLVMStyleWithColumns(23));
12524 }
12525 
12526 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12527   FormatStyle MergeEmptyOnly = getLLVMStyle();
12528   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12529   verifyFormat("class C {\n"
12530                "  int f() {}\n"
12531                "};",
12532                MergeEmptyOnly);
12533   verifyFormat("class C {\n"
12534                "  int f() {\n"
12535                "    return 42;\n"
12536                "  }\n"
12537                "};",
12538                MergeEmptyOnly);
12539   verifyFormat("int f() {}", MergeEmptyOnly);
12540   verifyFormat("int f() {\n"
12541                "  return 42;\n"
12542                "}",
12543                MergeEmptyOnly);
12544 
12545   // Also verify behavior when BraceWrapping.AfterFunction = true
12546   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12547   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12548   verifyFormat("int f() {}", MergeEmptyOnly);
12549   verifyFormat("class C {\n"
12550                "  int f() {}\n"
12551                "};",
12552                MergeEmptyOnly);
12553 }
12554 
12555 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12556   FormatStyle MergeInlineOnly = getLLVMStyle();
12557   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12558   verifyFormat("class C {\n"
12559                "  int f() { return 42; }\n"
12560                "};",
12561                MergeInlineOnly);
12562   verifyFormat("int f() {\n"
12563                "  return 42;\n"
12564                "}",
12565                MergeInlineOnly);
12566 
12567   // SFS_Inline implies SFS_Empty
12568   verifyFormat("class C {\n"
12569                "  int f() {}\n"
12570                "};",
12571                MergeInlineOnly);
12572   verifyFormat("int f() {}", MergeInlineOnly);
12573 
12574   // Also verify behavior when BraceWrapping.AfterFunction = true
12575   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12576   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12577   verifyFormat("class C {\n"
12578                "  int f() { return 42; }\n"
12579                "};",
12580                MergeInlineOnly);
12581   verifyFormat("int f()\n"
12582                "{\n"
12583                "  return 42;\n"
12584                "}",
12585                MergeInlineOnly);
12586 
12587   // SFS_Inline implies SFS_Empty
12588   verifyFormat("int f() {}", MergeInlineOnly);
12589   verifyFormat("class C {\n"
12590                "  int f() {}\n"
12591                "};",
12592                MergeInlineOnly);
12593 
12594   MergeInlineOnly.BraceWrapping.AfterClass = true;
12595   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12596   verifyFormat("class C\n"
12597                "{\n"
12598                "  int f() { return 42; }\n"
12599                "};",
12600                MergeInlineOnly);
12601   verifyFormat("struct C\n"
12602                "{\n"
12603                "  int f() { return 42; }\n"
12604                "};",
12605                MergeInlineOnly);
12606   verifyFormat("int f()\n"
12607                "{\n"
12608                "  return 42;\n"
12609                "}",
12610                MergeInlineOnly);
12611   verifyFormat("int f() {}", MergeInlineOnly);
12612   verifyFormat("class C\n"
12613                "{\n"
12614                "  int f() { return 42; }\n"
12615                "};",
12616                MergeInlineOnly);
12617   verifyFormat("struct C\n"
12618                "{\n"
12619                "  int f() { return 42; }\n"
12620                "};",
12621                MergeInlineOnly);
12622   verifyFormat("struct C\n"
12623                "// comment\n"
12624                "/* comment */\n"
12625                "// comment\n"
12626                "{\n"
12627                "  int f() { return 42; }\n"
12628                "};",
12629                MergeInlineOnly);
12630   verifyFormat("/* comment */ struct C\n"
12631                "{\n"
12632                "  int f() { return 42; }\n"
12633                "};",
12634                MergeInlineOnly);
12635 }
12636 
12637 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12638   FormatStyle MergeInlineOnly = getLLVMStyle();
12639   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12640       FormatStyle::SFS_InlineOnly;
12641   verifyFormat("class C {\n"
12642                "  int f() { return 42; }\n"
12643                "};",
12644                MergeInlineOnly);
12645   verifyFormat("int f() {\n"
12646                "  return 42;\n"
12647                "}",
12648                MergeInlineOnly);
12649 
12650   // SFS_InlineOnly does not imply SFS_Empty
12651   verifyFormat("class C {\n"
12652                "  int f() {}\n"
12653                "};",
12654                MergeInlineOnly);
12655   verifyFormat("int f() {\n"
12656                "}",
12657                MergeInlineOnly);
12658 
12659   // Also verify behavior when BraceWrapping.AfterFunction = true
12660   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12661   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12662   verifyFormat("class C {\n"
12663                "  int f() { return 42; }\n"
12664                "};",
12665                MergeInlineOnly);
12666   verifyFormat("int f()\n"
12667                "{\n"
12668                "  return 42;\n"
12669                "}",
12670                MergeInlineOnly);
12671 
12672   // SFS_InlineOnly does not imply SFS_Empty
12673   verifyFormat("int f()\n"
12674                "{\n"
12675                "}",
12676                MergeInlineOnly);
12677   verifyFormat("class C {\n"
12678                "  int f() {}\n"
12679                "};",
12680                MergeInlineOnly);
12681 }
12682 
12683 TEST_F(FormatTest, SplitEmptyFunction) {
12684   FormatStyle Style = getLLVMStyleWithColumns(40);
12685   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12686   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12687   Style.BraceWrapping.AfterFunction = true;
12688   Style.BraceWrapping.SplitEmptyFunction = false;
12689 
12690   verifyFormat("int f()\n"
12691                "{}",
12692                Style);
12693   verifyFormat("int f()\n"
12694                "{\n"
12695                "  return 42;\n"
12696                "}",
12697                Style);
12698   verifyFormat("int f()\n"
12699                "{\n"
12700                "  // some comment\n"
12701                "}",
12702                Style);
12703 
12704   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12705   verifyFormat("int f() {}", Style);
12706   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12707                "{}",
12708                Style);
12709   verifyFormat("int f()\n"
12710                "{\n"
12711                "  return 0;\n"
12712                "}",
12713                Style);
12714 
12715   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12716   verifyFormat("class Foo {\n"
12717                "  int f() {}\n"
12718                "};\n",
12719                Style);
12720   verifyFormat("class Foo {\n"
12721                "  int f() { return 0; }\n"
12722                "};\n",
12723                Style);
12724   verifyFormat("class Foo {\n"
12725                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12726                "  {}\n"
12727                "};\n",
12728                Style);
12729   verifyFormat("class Foo {\n"
12730                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12731                "  {\n"
12732                "    return 0;\n"
12733                "  }\n"
12734                "};\n",
12735                Style);
12736 
12737   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12738   verifyFormat("int f() {}", Style);
12739   verifyFormat("int f() { return 0; }", Style);
12740   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12741                "{}",
12742                Style);
12743   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12744                "{\n"
12745                "  return 0;\n"
12746                "}",
12747                Style);
12748 }
12749 
12750 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12751   FormatStyle Style = getLLVMStyleWithColumns(40);
12752   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12753   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12754   Style.BraceWrapping.AfterFunction = true;
12755   Style.BraceWrapping.SplitEmptyFunction = true;
12756   Style.BraceWrapping.SplitEmptyRecord = false;
12757 
12758   verifyFormat("class C {};", Style);
12759   verifyFormat("struct C {};", Style);
12760   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12761                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12762                "{\n"
12763                "}",
12764                Style);
12765   verifyFormat("class C {\n"
12766                "  C()\n"
12767                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12768                "        bbbbbbbbbbbbbbbbbbb()\n"
12769                "  {\n"
12770                "  }\n"
12771                "  void\n"
12772                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12773                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12774                "  {\n"
12775                "  }\n"
12776                "};",
12777                Style);
12778 }
12779 
12780 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12781   FormatStyle Style = getLLVMStyle();
12782   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12783   verifyFormat("#ifdef A\n"
12784                "int f() {}\n"
12785                "#else\n"
12786                "int g() {}\n"
12787                "#endif",
12788                Style);
12789 }
12790 
12791 TEST_F(FormatTest, SplitEmptyClass) {
12792   FormatStyle Style = getLLVMStyle();
12793   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12794   Style.BraceWrapping.AfterClass = true;
12795   Style.BraceWrapping.SplitEmptyRecord = false;
12796 
12797   verifyFormat("class Foo\n"
12798                "{};",
12799                Style);
12800   verifyFormat("/* something */ class Foo\n"
12801                "{};",
12802                Style);
12803   verifyFormat("template <typename X> class Foo\n"
12804                "{};",
12805                Style);
12806   verifyFormat("class Foo\n"
12807                "{\n"
12808                "  Foo();\n"
12809                "};",
12810                Style);
12811   verifyFormat("typedef class Foo\n"
12812                "{\n"
12813                "} Foo_t;",
12814                Style);
12815 
12816   Style.BraceWrapping.SplitEmptyRecord = true;
12817   Style.BraceWrapping.AfterStruct = true;
12818   verifyFormat("class rep\n"
12819                "{\n"
12820                "};",
12821                Style);
12822   verifyFormat("struct rep\n"
12823                "{\n"
12824                "};",
12825                Style);
12826   verifyFormat("template <typename T> class rep\n"
12827                "{\n"
12828                "};",
12829                Style);
12830   verifyFormat("template <typename T> struct rep\n"
12831                "{\n"
12832                "};",
12833                Style);
12834   verifyFormat("class rep\n"
12835                "{\n"
12836                "  int x;\n"
12837                "};",
12838                Style);
12839   verifyFormat("struct rep\n"
12840                "{\n"
12841                "  int x;\n"
12842                "};",
12843                Style);
12844   verifyFormat("template <typename T> class rep\n"
12845                "{\n"
12846                "  int x;\n"
12847                "};",
12848                Style);
12849   verifyFormat("template <typename T> struct rep\n"
12850                "{\n"
12851                "  int x;\n"
12852                "};",
12853                Style);
12854   verifyFormat("template <typename T> class rep // Foo\n"
12855                "{\n"
12856                "  int x;\n"
12857                "};",
12858                Style);
12859   verifyFormat("template <typename T> struct rep // Bar\n"
12860                "{\n"
12861                "  int x;\n"
12862                "};",
12863                Style);
12864 
12865   verifyFormat("template <typename T> class rep<T>\n"
12866                "{\n"
12867                "  int x;\n"
12868                "};",
12869                Style);
12870 
12871   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12872                "{\n"
12873                "  int x;\n"
12874                "};",
12875                Style);
12876   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12877                "{\n"
12878                "};",
12879                Style);
12880 
12881   verifyFormat("#include \"stdint.h\"\n"
12882                "namespace rep {}",
12883                Style);
12884   verifyFormat("#include <stdint.h>\n"
12885                "namespace rep {}",
12886                Style);
12887   verifyFormat("#include <stdint.h>\n"
12888                "namespace rep {}",
12889                "#include <stdint.h>\n"
12890                "namespace rep {\n"
12891                "\n"
12892                "\n"
12893                "}",
12894                Style);
12895 }
12896 
12897 TEST_F(FormatTest, SplitEmptyStruct) {
12898   FormatStyle Style = getLLVMStyle();
12899   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12900   Style.BraceWrapping.AfterStruct = true;
12901   Style.BraceWrapping.SplitEmptyRecord = false;
12902 
12903   verifyFormat("struct Foo\n"
12904                "{};",
12905                Style);
12906   verifyFormat("/* something */ struct Foo\n"
12907                "{};",
12908                Style);
12909   verifyFormat("template <typename X> struct Foo\n"
12910                "{};",
12911                Style);
12912   verifyFormat("struct Foo\n"
12913                "{\n"
12914                "  Foo();\n"
12915                "};",
12916                Style);
12917   verifyFormat("typedef struct Foo\n"
12918                "{\n"
12919                "} Foo_t;",
12920                Style);
12921   // typedef struct Bar {} Bar_t;
12922 }
12923 
12924 TEST_F(FormatTest, SplitEmptyUnion) {
12925   FormatStyle Style = getLLVMStyle();
12926   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12927   Style.BraceWrapping.AfterUnion = true;
12928   Style.BraceWrapping.SplitEmptyRecord = false;
12929 
12930   verifyFormat("union Foo\n"
12931                "{};",
12932                Style);
12933   verifyFormat("/* something */ union Foo\n"
12934                "{};",
12935                Style);
12936   verifyFormat("union Foo\n"
12937                "{\n"
12938                "  A,\n"
12939                "};",
12940                Style);
12941   verifyFormat("typedef union Foo\n"
12942                "{\n"
12943                "} Foo_t;",
12944                Style);
12945 }
12946 
12947 TEST_F(FormatTest, SplitEmptyNamespace) {
12948   FormatStyle Style = getLLVMStyle();
12949   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12950   Style.BraceWrapping.AfterNamespace = true;
12951   Style.BraceWrapping.SplitEmptyNamespace = false;
12952 
12953   verifyFormat("namespace Foo\n"
12954                "{};",
12955                Style);
12956   verifyFormat("/* something */ namespace Foo\n"
12957                "{};",
12958                Style);
12959   verifyFormat("inline namespace Foo\n"
12960                "{};",
12961                Style);
12962   verifyFormat("/* something */ inline namespace Foo\n"
12963                "{};",
12964                Style);
12965   verifyFormat("export namespace Foo\n"
12966                "{};",
12967                Style);
12968   verifyFormat("namespace Foo\n"
12969                "{\n"
12970                "void Bar();\n"
12971                "};",
12972                Style);
12973 }
12974 
12975 TEST_F(FormatTest, NeverMergeShortRecords) {
12976   FormatStyle Style = getLLVMStyle();
12977 
12978   verifyFormat("class Foo {\n"
12979                "  Foo();\n"
12980                "};",
12981                Style);
12982   verifyFormat("typedef class Foo {\n"
12983                "  Foo();\n"
12984                "} Foo_t;",
12985                Style);
12986   verifyFormat("struct Foo {\n"
12987                "  Foo();\n"
12988                "};",
12989                Style);
12990   verifyFormat("typedef struct Foo {\n"
12991                "  Foo();\n"
12992                "} Foo_t;",
12993                Style);
12994   verifyFormat("union Foo {\n"
12995                "  A,\n"
12996                "};",
12997                Style);
12998   verifyFormat("typedef union Foo {\n"
12999                "  A,\n"
13000                "} Foo_t;",
13001                Style);
13002   verifyFormat("namespace Foo {\n"
13003                "void Bar();\n"
13004                "};",
13005                Style);
13006 
13007   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13008   Style.BraceWrapping.AfterClass = true;
13009   Style.BraceWrapping.AfterStruct = true;
13010   Style.BraceWrapping.AfterUnion = true;
13011   Style.BraceWrapping.AfterNamespace = true;
13012   verifyFormat("class Foo\n"
13013                "{\n"
13014                "  Foo();\n"
13015                "};",
13016                Style);
13017   verifyFormat("typedef class Foo\n"
13018                "{\n"
13019                "  Foo();\n"
13020                "} Foo_t;",
13021                Style);
13022   verifyFormat("struct Foo\n"
13023                "{\n"
13024                "  Foo();\n"
13025                "};",
13026                Style);
13027   verifyFormat("typedef struct Foo\n"
13028                "{\n"
13029                "  Foo();\n"
13030                "} Foo_t;",
13031                Style);
13032   verifyFormat("union Foo\n"
13033                "{\n"
13034                "  A,\n"
13035                "};",
13036                Style);
13037   verifyFormat("typedef union Foo\n"
13038                "{\n"
13039                "  A,\n"
13040                "} Foo_t;",
13041                Style);
13042   verifyFormat("namespace Foo\n"
13043                "{\n"
13044                "void Bar();\n"
13045                "};",
13046                Style);
13047 }
13048 
13049 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13050   // Elaborate type variable declarations.
13051   verifyFormat("struct foo a = {bar};\nint n;");
13052   verifyFormat("class foo a = {bar};\nint n;");
13053   verifyFormat("union foo a = {bar};\nint n;");
13054 
13055   // Elaborate types inside function definitions.
13056   verifyFormat("struct foo f() {}\nint n;");
13057   verifyFormat("class foo f() {}\nint n;");
13058   verifyFormat("union foo f() {}\nint n;");
13059 
13060   // Templates.
13061   verifyFormat("template <class X> void f() {}\nint n;");
13062   verifyFormat("template <struct X> void f() {}\nint n;");
13063   verifyFormat("template <union X> void f() {}\nint n;");
13064 
13065   // Actual definitions...
13066   verifyFormat("struct {\n} n;");
13067   verifyFormat(
13068       "template <template <class T, class Y>, class Z> class X {\n} n;");
13069   verifyFormat("union Z {\n  int n;\n} x;");
13070   verifyFormat("class MACRO Z {\n} n;");
13071   verifyFormat("class MACRO(X) Z {\n} n;");
13072   verifyFormat("class __attribute__(X) Z {\n} n;");
13073   verifyFormat("class __declspec(X) Z {\n} n;");
13074   verifyFormat("class A##B##C {\n} n;");
13075   verifyFormat("class alignas(16) Z {\n} n;");
13076   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13077   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13078 
13079   // Redefinition from nested context:
13080   verifyFormat("class A::B::C {\n} n;");
13081 
13082   // Template definitions.
13083   verifyFormat(
13084       "template <typename F>\n"
13085       "Matcher(const Matcher<F> &Other,\n"
13086       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13087       "                             !is_same<F, T>::value>::type * = 0)\n"
13088       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13089 
13090   // FIXME: This is still incorrectly handled at the formatter side.
13091   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13092   verifyFormat("int i = SomeFunction(a<b, a> b);");
13093 
13094   // FIXME:
13095   // This now gets parsed incorrectly as class definition.
13096   // verifyFormat("class A<int> f() {\n}\nint n;");
13097 
13098   // Elaborate types where incorrectly parsing the structural element would
13099   // break the indent.
13100   verifyFormat("if (true)\n"
13101                "  class X x;\n"
13102                "else\n"
13103                "  f();\n");
13104 
13105   // This is simply incomplete. Formatting is not important, but must not crash.
13106   verifyFormat("class A:");
13107 }
13108 
13109 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13110   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13111             format("#error Leave     all         white!!!!! space* alone!\n"));
13112   EXPECT_EQ(
13113       "#warning Leave     all         white!!!!! space* alone!\n",
13114       format("#warning Leave     all         white!!!!! space* alone!\n"));
13115   EXPECT_EQ("#error 1", format("  #  error   1"));
13116   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13117 }
13118 
13119 TEST_F(FormatTest, FormatHashIfExpressions) {
13120   verifyFormat("#if AAAA && BBBB");
13121   verifyFormat("#if (AAAA && BBBB)");
13122   verifyFormat("#elif (AAAA && BBBB)");
13123   // FIXME: Come up with a better indentation for #elif.
13124   verifyFormat(
13125       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13126       "    defined(BBBBBBBB)\n"
13127       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13128       "    defined(BBBBBBBB)\n"
13129       "#endif",
13130       getLLVMStyleWithColumns(65));
13131 }
13132 
13133 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13134   FormatStyle AllowsMergedIf = getGoogleStyle();
13135   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13136       FormatStyle::SIS_WithoutElse;
13137   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13138   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13139   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13140   EXPECT_EQ("if (true) return 42;",
13141             format("if (true)\nreturn 42;", AllowsMergedIf));
13142   FormatStyle ShortMergedIf = AllowsMergedIf;
13143   ShortMergedIf.ColumnLimit = 25;
13144   verifyFormat("#define A \\\n"
13145                "  if (true) return 42;",
13146                ShortMergedIf);
13147   verifyFormat("#define A \\\n"
13148                "  f();    \\\n"
13149                "  if (true)\n"
13150                "#define B",
13151                ShortMergedIf);
13152   verifyFormat("#define A \\\n"
13153                "  f();    \\\n"
13154                "  if (true)\n"
13155                "g();",
13156                ShortMergedIf);
13157   verifyFormat("{\n"
13158                "#ifdef A\n"
13159                "  // Comment\n"
13160                "  if (true) continue;\n"
13161                "#endif\n"
13162                "  // Comment\n"
13163                "  if (true) continue;\n"
13164                "}",
13165                ShortMergedIf);
13166   ShortMergedIf.ColumnLimit = 33;
13167   verifyFormat("#define A \\\n"
13168                "  if constexpr (true) return 42;",
13169                ShortMergedIf);
13170   verifyFormat("#define A \\\n"
13171                "  if CONSTEXPR (true) return 42;",
13172                ShortMergedIf);
13173   ShortMergedIf.ColumnLimit = 29;
13174   verifyFormat("#define A                   \\\n"
13175                "  if (aaaaaaaaaa) return 1; \\\n"
13176                "  return 2;",
13177                ShortMergedIf);
13178   ShortMergedIf.ColumnLimit = 28;
13179   verifyFormat("#define A         \\\n"
13180                "  if (aaaaaaaaaa) \\\n"
13181                "    return 1;     \\\n"
13182                "  return 2;",
13183                ShortMergedIf);
13184   verifyFormat("#define A                \\\n"
13185                "  if constexpr (aaaaaaa) \\\n"
13186                "    return 1;            \\\n"
13187                "  return 2;",
13188                ShortMergedIf);
13189   verifyFormat("#define A                \\\n"
13190                "  if CONSTEXPR (aaaaaaa) \\\n"
13191                "    return 1;            \\\n"
13192                "  return 2;",
13193                ShortMergedIf);
13194 }
13195 
13196 TEST_F(FormatTest, FormatStarDependingOnContext) {
13197   verifyFormat("void f(int *a);");
13198   verifyFormat("void f() { f(fint * b); }");
13199   verifyFormat("class A {\n  void f(int *a);\n};");
13200   verifyFormat("class A {\n  int *a;\n};");
13201   verifyFormat("namespace a {\n"
13202                "namespace b {\n"
13203                "class A {\n"
13204                "  void f() {}\n"
13205                "  int *a;\n"
13206                "};\n"
13207                "} // namespace b\n"
13208                "} // namespace a");
13209 }
13210 
13211 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13212   verifyFormat("while");
13213   verifyFormat("operator");
13214 }
13215 
13216 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13217   // This code would be painfully slow to format if we didn't skip it.
13218   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
13219                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13220                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13221                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13222                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13223                    "A(1, 1)\n"
13224                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13225                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13226                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13227                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13228                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13229                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13230                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13231                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13232                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13233                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13234   // Deeply nested part is untouched, rest is formatted.
13235   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13236             format(std::string("int    i;\n") + Code + "int    j;\n",
13237                    getLLVMStyle(), SC_ExpectIncomplete));
13238 }
13239 
13240 //===----------------------------------------------------------------------===//
13241 // Objective-C tests.
13242 //===----------------------------------------------------------------------===//
13243 
13244 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13245   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13246   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13247             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13248   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13249   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13250   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13251             format("-(NSInteger)Method3:(id)anObject;"));
13252   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13253             format("-(NSInteger)Method4:(id)anObject;"));
13254   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13255             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13256   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13257             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13258   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13259             "forAllCells:(BOOL)flag;",
13260             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13261                    "forAllCells:(BOOL)flag;"));
13262 
13263   // Very long objectiveC method declaration.
13264   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13265                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13266   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13267                "                    inRange:(NSRange)range\n"
13268                "                   outRange:(NSRange)out_range\n"
13269                "                  outRange1:(NSRange)out_range1\n"
13270                "                  outRange2:(NSRange)out_range2\n"
13271                "                  outRange3:(NSRange)out_range3\n"
13272                "                  outRange4:(NSRange)out_range4\n"
13273                "                  outRange5:(NSRange)out_range5\n"
13274                "                  outRange6:(NSRange)out_range6\n"
13275                "                  outRange7:(NSRange)out_range7\n"
13276                "                  outRange8:(NSRange)out_range8\n"
13277                "                  outRange9:(NSRange)out_range9;");
13278 
13279   // When the function name has to be wrapped.
13280   FormatStyle Style = getLLVMStyle();
13281   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13282   // and always indents instead.
13283   Style.IndentWrappedFunctionNames = false;
13284   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13285                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13286                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13287                "}",
13288                Style);
13289   Style.IndentWrappedFunctionNames = true;
13290   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13291                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13292                "               anotherName:(NSString)dddddddddddddd {\n"
13293                "}",
13294                Style);
13295 
13296   verifyFormat("- (int)sum:(vector<int>)numbers;");
13297   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13298   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13299   // protocol lists (but not for template classes):
13300   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13301 
13302   verifyFormat("- (int (*)())foo:(int (*)())f;");
13303   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13304 
13305   // If there's no return type (very rare in practice!), LLVM and Google style
13306   // agree.
13307   verifyFormat("- foo;");
13308   verifyFormat("- foo:(int)f;");
13309   verifyGoogleFormat("- foo:(int)foo;");
13310 }
13311 
13312 TEST_F(FormatTest, BreaksStringLiterals) {
13313   EXPECT_EQ("\"some text \"\n"
13314             "\"other\";",
13315             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13316   EXPECT_EQ("\"some text \"\n"
13317             "\"other\";",
13318             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13319   EXPECT_EQ(
13320       "#define A  \\\n"
13321       "  \"some \"  \\\n"
13322       "  \"text \"  \\\n"
13323       "  \"other\";",
13324       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13325   EXPECT_EQ(
13326       "#define A  \\\n"
13327       "  \"so \"    \\\n"
13328       "  \"text \"  \\\n"
13329       "  \"other\";",
13330       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13331 
13332   EXPECT_EQ("\"some text\"",
13333             format("\"some text\"", getLLVMStyleWithColumns(1)));
13334   EXPECT_EQ("\"some text\"",
13335             format("\"some text\"", getLLVMStyleWithColumns(11)));
13336   EXPECT_EQ("\"some \"\n"
13337             "\"text\"",
13338             format("\"some text\"", getLLVMStyleWithColumns(10)));
13339   EXPECT_EQ("\"some \"\n"
13340             "\"text\"",
13341             format("\"some text\"", getLLVMStyleWithColumns(7)));
13342   EXPECT_EQ("\"some\"\n"
13343             "\" tex\"\n"
13344             "\"t\"",
13345             format("\"some text\"", getLLVMStyleWithColumns(6)));
13346   EXPECT_EQ("\"some\"\n"
13347             "\" tex\"\n"
13348             "\" and\"",
13349             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13350   EXPECT_EQ("\"some\"\n"
13351             "\"/tex\"\n"
13352             "\"/and\"",
13353             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13354 
13355   EXPECT_EQ("variable =\n"
13356             "    \"long string \"\n"
13357             "    \"literal\";",
13358             format("variable = \"long string literal\";",
13359                    getLLVMStyleWithColumns(20)));
13360 
13361   EXPECT_EQ("variable = f(\n"
13362             "    \"long string \"\n"
13363             "    \"literal\",\n"
13364             "    short,\n"
13365             "    loooooooooooooooooooong);",
13366             format("variable = f(\"long string literal\", short, "
13367                    "loooooooooooooooooooong);",
13368                    getLLVMStyleWithColumns(20)));
13369 
13370   EXPECT_EQ(
13371       "f(g(\"long string \"\n"
13372       "    \"literal\"),\n"
13373       "  b);",
13374       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13375   EXPECT_EQ("f(g(\"long string \"\n"
13376             "    \"literal\",\n"
13377             "    a),\n"
13378             "  b);",
13379             format("f(g(\"long string literal\", a), b);",
13380                    getLLVMStyleWithColumns(20)));
13381   EXPECT_EQ(
13382       "f(\"one two\".split(\n"
13383       "    variable));",
13384       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13385   EXPECT_EQ("f(\"one two three four five six \"\n"
13386             "  \"seven\".split(\n"
13387             "      really_looooong_variable));",
13388             format("f(\"one two three four five six seven\"."
13389                    "split(really_looooong_variable));",
13390                    getLLVMStyleWithColumns(33)));
13391 
13392   EXPECT_EQ("f(\"some \"\n"
13393             "  \"text\",\n"
13394             "  other);",
13395             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13396 
13397   // Only break as a last resort.
13398   verifyFormat(
13399       "aaaaaaaaaaaaaaaaaaaa(\n"
13400       "    aaaaaaaaaaaaaaaaaaaa,\n"
13401       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13402 
13403   EXPECT_EQ("\"splitmea\"\n"
13404             "\"trandomp\"\n"
13405             "\"oint\"",
13406             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13407 
13408   EXPECT_EQ("\"split/\"\n"
13409             "\"pathat/\"\n"
13410             "\"slashes\"",
13411             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13412 
13413   EXPECT_EQ("\"split/\"\n"
13414             "\"pathat/\"\n"
13415             "\"slashes\"",
13416             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13417   EXPECT_EQ("\"split at \"\n"
13418             "\"spaces/at/\"\n"
13419             "\"slashes.at.any$\"\n"
13420             "\"non-alphanumeric%\"\n"
13421             "\"1111111111characte\"\n"
13422             "\"rs\"",
13423             format("\"split at "
13424                    "spaces/at/"
13425                    "slashes.at."
13426                    "any$non-"
13427                    "alphanumeric%"
13428                    "1111111111characte"
13429                    "rs\"",
13430                    getLLVMStyleWithColumns(20)));
13431 
13432   // Verify that splitting the strings understands
13433   // Style::AlwaysBreakBeforeMultilineStrings.
13434   EXPECT_EQ("aaaaaaaaaaaa(\n"
13435             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13436             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13437             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13438                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13439                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13440                    getGoogleStyle()));
13441   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13442             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13443             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13444                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13445                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13446                    getGoogleStyle()));
13447   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13448             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13449             format("llvm::outs() << "
13450                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13451                    "aaaaaaaaaaaaaaaaaaa\";"));
13452   EXPECT_EQ("ffff(\n"
13453             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13454             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13455             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13456                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13457                    getGoogleStyle()));
13458 
13459   FormatStyle Style = getLLVMStyleWithColumns(12);
13460   Style.BreakStringLiterals = false;
13461   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13462 
13463   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13464   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13465   EXPECT_EQ("#define A \\\n"
13466             "  \"some \" \\\n"
13467             "  \"text \" \\\n"
13468             "  \"other\";",
13469             format("#define A \"some text other\";", AlignLeft));
13470 }
13471 
13472 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13473   EXPECT_EQ("C a = \"some more \"\n"
13474             "      \"text\";",
13475             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13476 }
13477 
13478 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13479   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13480   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13481   EXPECT_EQ("int i = a(b());",
13482             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13483 }
13484 
13485 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13486   EXPECT_EQ(
13487       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13488       "(\n"
13489       "    \"x\t\");",
13490       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13491              "aaaaaaa("
13492              "\"x\t\");"));
13493 }
13494 
13495 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13496   EXPECT_EQ(
13497       "u8\"utf8 string \"\n"
13498       "u8\"literal\";",
13499       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13500   EXPECT_EQ(
13501       "u\"utf16 string \"\n"
13502       "u\"literal\";",
13503       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13504   EXPECT_EQ(
13505       "U\"utf32 string \"\n"
13506       "U\"literal\";",
13507       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13508   EXPECT_EQ("L\"wide string \"\n"
13509             "L\"literal\";",
13510             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13511   EXPECT_EQ("@\"NSString \"\n"
13512             "@\"literal\";",
13513             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13514   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13515 
13516   // This input makes clang-format try to split the incomplete unicode escape
13517   // sequence, which used to lead to a crasher.
13518   verifyNoCrash(
13519       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13520       getLLVMStyleWithColumns(60));
13521 }
13522 
13523 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13524   FormatStyle Style = getGoogleStyleWithColumns(15);
13525   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13526   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13527   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13528   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13529   EXPECT_EQ("u8R\"x(raw literal)x\";",
13530             format("u8R\"x(raw literal)x\";", Style));
13531 }
13532 
13533 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13534   FormatStyle Style = getLLVMStyleWithColumns(20);
13535   EXPECT_EQ(
13536       "_T(\"aaaaaaaaaaaaaa\")\n"
13537       "_T(\"aaaaaaaaaaaaaa\")\n"
13538       "_T(\"aaaaaaaaaaaa\")",
13539       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13540   EXPECT_EQ("f(x,\n"
13541             "  _T(\"aaaaaaaaaaaa\")\n"
13542             "  _T(\"aaa\"),\n"
13543             "  z);",
13544             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13545 
13546   // FIXME: Handle embedded spaces in one iteration.
13547   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13548   //            "_T(\"aaaaaaaaaaaaa\")\n"
13549   //            "_T(\"aaaaaaaaaaaaa\")\n"
13550   //            "_T(\"a\")",
13551   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13552   //                   getLLVMStyleWithColumns(20)));
13553   EXPECT_EQ(
13554       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13555       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13556   EXPECT_EQ("f(\n"
13557             "#if !TEST\n"
13558             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13559             "#endif\n"
13560             ");",
13561             format("f(\n"
13562                    "#if !TEST\n"
13563                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13564                    "#endif\n"
13565                    ");"));
13566   EXPECT_EQ("f(\n"
13567             "\n"
13568             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13569             format("f(\n"
13570                    "\n"
13571                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13572   // Regression test for accessing tokens past the end of a vector in the
13573   // TokenLexer.
13574   verifyNoCrash(R"(_T(
13575 "
13576 )
13577 )");
13578 }
13579 
13580 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13581   // In a function call with two operands, the second can be broken with no line
13582   // break before it.
13583   EXPECT_EQ(
13584       "func(a, \"long long \"\n"
13585       "        \"long long\");",
13586       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13587   // In a function call with three operands, the second must be broken with a
13588   // line break before it.
13589   EXPECT_EQ("func(a,\n"
13590             "     \"long long long \"\n"
13591             "     \"long\",\n"
13592             "     c);",
13593             format("func(a, \"long long long long\", c);",
13594                    getLLVMStyleWithColumns(24)));
13595   // In a function call with three operands, the third must be broken with a
13596   // line break before it.
13597   EXPECT_EQ("func(a, b,\n"
13598             "     \"long long long \"\n"
13599             "     \"long\");",
13600             format("func(a, b, \"long long long long\");",
13601                    getLLVMStyleWithColumns(24)));
13602   // In a function call with three operands, both the second and the third must
13603   // be broken with a line break before them.
13604   EXPECT_EQ("func(a,\n"
13605             "     \"long long long \"\n"
13606             "     \"long\",\n"
13607             "     \"long long long \"\n"
13608             "     \"long\");",
13609             format("func(a, \"long long long long\", \"long long long long\");",
13610                    getLLVMStyleWithColumns(24)));
13611   // In a chain of << with two operands, the second can be broken with no line
13612   // break before it.
13613   EXPECT_EQ("a << \"line line \"\n"
13614             "     \"line\";",
13615             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13616   // In a chain of << with three operands, the second can be broken with no line
13617   // break before it.
13618   EXPECT_EQ(
13619       "abcde << \"line \"\n"
13620       "         \"line line\"\n"
13621       "      << c;",
13622       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13623   // In a chain of << with three operands, the third must be broken with a line
13624   // break before it.
13625   EXPECT_EQ(
13626       "a << b\n"
13627       "  << \"line line \"\n"
13628       "     \"line\";",
13629       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13630   // In a chain of << with three operands, the second can be broken with no line
13631   // break before it and the third must be broken with a line break before it.
13632   EXPECT_EQ("abcd << \"line line \"\n"
13633             "        \"line\"\n"
13634             "     << \"line line \"\n"
13635             "        \"line\";",
13636             format("abcd << \"line line line\" << \"line line line\";",
13637                    getLLVMStyleWithColumns(20)));
13638   // In a chain of binary operators with two operands, the second can be broken
13639   // with no line break before it.
13640   EXPECT_EQ(
13641       "abcd + \"line line \"\n"
13642       "       \"line line\";",
13643       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13644   // In a chain of binary operators with three operands, the second must be
13645   // broken with a line break before it.
13646   EXPECT_EQ("abcd +\n"
13647             "    \"line line \"\n"
13648             "    \"line line\" +\n"
13649             "    e;",
13650             format("abcd + \"line line line line\" + e;",
13651                    getLLVMStyleWithColumns(20)));
13652   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13653   // the first must be broken with a line break before it.
13654   FormatStyle Style = getLLVMStyleWithColumns(25);
13655   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13656   EXPECT_EQ("someFunction(\n"
13657             "    \"long long long \"\n"
13658             "    \"long\",\n"
13659             "    a);",
13660             format("someFunction(\"long long long long\", a);", Style));
13661 }
13662 
13663 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13664   EXPECT_EQ(
13665       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13666       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13667       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13668       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13669              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13670              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13671 }
13672 
13673 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13674   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13675             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13676   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13677             "multiline raw string literal xxxxxxxxxxxxxx\n"
13678             ")x\",\n"
13679             "              a),\n"
13680             "            b);",
13681             format("fffffffffff(g(R\"x(\n"
13682                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13683                    ")x\", a), b);",
13684                    getGoogleStyleWithColumns(20)));
13685   EXPECT_EQ("fffffffffff(\n"
13686             "    g(R\"x(qqq\n"
13687             "multiline raw string literal xxxxxxxxxxxxxx\n"
13688             ")x\",\n"
13689             "      a),\n"
13690             "    b);",
13691             format("fffffffffff(g(R\"x(qqq\n"
13692                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13693                    ")x\", a), b);",
13694                    getGoogleStyleWithColumns(20)));
13695 
13696   EXPECT_EQ("fffffffffff(R\"x(\n"
13697             "multiline raw string literal xxxxxxxxxxxxxx\n"
13698             ")x\");",
13699             format("fffffffffff(R\"x(\n"
13700                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13701                    ")x\");",
13702                    getGoogleStyleWithColumns(20)));
13703   EXPECT_EQ("fffffffffff(R\"x(\n"
13704             "multiline raw string literal xxxxxxxxxxxxxx\n"
13705             ")x\" + bbbbbb);",
13706             format("fffffffffff(R\"x(\n"
13707                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13708                    ")x\" +   bbbbbb);",
13709                    getGoogleStyleWithColumns(20)));
13710   EXPECT_EQ("fffffffffff(\n"
13711             "    R\"x(\n"
13712             "multiline raw string literal xxxxxxxxxxxxxx\n"
13713             ")x\" +\n"
13714             "    bbbbbb);",
13715             format("fffffffffff(\n"
13716                    " R\"x(\n"
13717                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13718                    ")x\" + bbbbbb);",
13719                    getGoogleStyleWithColumns(20)));
13720   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13721             format("fffffffffff(\n"
13722                    " R\"(single line raw string)\" + bbbbbb);"));
13723 }
13724 
13725 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13726   verifyFormat("string a = \"unterminated;");
13727   EXPECT_EQ("function(\"unterminated,\n"
13728             "         OtherParameter);",
13729             format("function(  \"unterminated,\n"
13730                    "    OtherParameter);"));
13731 }
13732 
13733 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13734   FormatStyle Style = getLLVMStyle();
13735   Style.Standard = FormatStyle::LS_Cpp03;
13736   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13737             format("#define x(_a) printf(\"foo\"_a);", Style));
13738 }
13739 
13740 TEST_F(FormatTest, CppLexVersion) {
13741   FormatStyle Style = getLLVMStyle();
13742   // Formatting of x * y differs if x is a type.
13743   verifyFormat("void foo() { MACRO(a * b); }", Style);
13744   verifyFormat("void foo() { MACRO(int *b); }", Style);
13745 
13746   // LLVM style uses latest lexer.
13747   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13748   Style.Standard = FormatStyle::LS_Cpp17;
13749   // But in c++17, char8_t isn't a keyword.
13750   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13751 }
13752 
13753 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13754 
13755 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13756   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13757             "             \"ddeeefff\");",
13758             format("someFunction(\"aaabbbcccdddeeefff\");",
13759                    getLLVMStyleWithColumns(25)));
13760   EXPECT_EQ("someFunction1234567890(\n"
13761             "    \"aaabbbcccdddeeefff\");",
13762             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13763                    getLLVMStyleWithColumns(26)));
13764   EXPECT_EQ("someFunction1234567890(\n"
13765             "    \"aaabbbcccdddeeeff\"\n"
13766             "    \"f\");",
13767             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13768                    getLLVMStyleWithColumns(25)));
13769   EXPECT_EQ("someFunction1234567890(\n"
13770             "    \"aaabbbcccdddeeeff\"\n"
13771             "    \"f\");",
13772             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13773                    getLLVMStyleWithColumns(24)));
13774   EXPECT_EQ("someFunction(\n"
13775             "    \"aaabbbcc ddde \"\n"
13776             "    \"efff\");",
13777             format("someFunction(\"aaabbbcc ddde efff\");",
13778                    getLLVMStyleWithColumns(25)));
13779   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13780             "             \"ddeeefff\");",
13781             format("someFunction(\"aaabbbccc ddeeefff\");",
13782                    getLLVMStyleWithColumns(25)));
13783   EXPECT_EQ("someFunction1234567890(\n"
13784             "    \"aaabb \"\n"
13785             "    \"cccdddeeefff\");",
13786             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13787                    getLLVMStyleWithColumns(25)));
13788   EXPECT_EQ("#define A          \\\n"
13789             "  string s =       \\\n"
13790             "      \"123456789\"  \\\n"
13791             "      \"0\";         \\\n"
13792             "  int i;",
13793             format("#define A string s = \"1234567890\"; int i;",
13794                    getLLVMStyleWithColumns(20)));
13795   EXPECT_EQ("someFunction(\n"
13796             "    \"aaabbbcc \"\n"
13797             "    \"dddeeefff\");",
13798             format("someFunction(\"aaabbbcc dddeeefff\");",
13799                    getLLVMStyleWithColumns(25)));
13800 }
13801 
13802 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13803   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13804   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13805   EXPECT_EQ("\"test\"\n"
13806             "\"\\n\"",
13807             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13808   EXPECT_EQ("\"tes\\\\\"\n"
13809             "\"n\"",
13810             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
13811   EXPECT_EQ("\"\\\\\\\\\"\n"
13812             "\"\\n\"",
13813             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
13814   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
13815   EXPECT_EQ("\"\\uff01\"\n"
13816             "\"test\"",
13817             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
13818   EXPECT_EQ("\"\\Uff01ff02\"",
13819             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
13820   EXPECT_EQ("\"\\x000000000001\"\n"
13821             "\"next\"",
13822             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
13823   EXPECT_EQ("\"\\x000000000001next\"",
13824             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
13825   EXPECT_EQ("\"\\x000000000001\"",
13826             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
13827   EXPECT_EQ("\"test\"\n"
13828             "\"\\000000\"\n"
13829             "\"000001\"",
13830             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
13831   EXPECT_EQ("\"test\\000\"\n"
13832             "\"00000000\"\n"
13833             "\"1\"",
13834             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
13835 }
13836 
13837 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
13838   verifyFormat("void f() {\n"
13839                "  return g() {}\n"
13840                "  void h() {}");
13841   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
13842                "g();\n"
13843                "}");
13844 }
13845 
13846 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
13847   verifyFormat(
13848       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
13849 }
13850 
13851 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
13852   verifyFormat("class X {\n"
13853                "  void f() {\n"
13854                "  }\n"
13855                "};",
13856                getLLVMStyleWithColumns(12));
13857 }
13858 
13859 TEST_F(FormatTest, ConfigurableIndentWidth) {
13860   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
13861   EightIndent.IndentWidth = 8;
13862   EightIndent.ContinuationIndentWidth = 8;
13863   verifyFormat("void f() {\n"
13864                "        someFunction();\n"
13865                "        if (true) {\n"
13866                "                f();\n"
13867                "        }\n"
13868                "}",
13869                EightIndent);
13870   verifyFormat("class X {\n"
13871                "        void f() {\n"
13872                "        }\n"
13873                "};",
13874                EightIndent);
13875   verifyFormat("int x[] = {\n"
13876                "        call(),\n"
13877                "        call()};",
13878                EightIndent);
13879 }
13880 
13881 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
13882   verifyFormat("double\n"
13883                "f();",
13884                getLLVMStyleWithColumns(8));
13885 }
13886 
13887 TEST_F(FormatTest, ConfigurableUseOfTab) {
13888   FormatStyle Tab = getLLVMStyleWithColumns(42);
13889   Tab.IndentWidth = 8;
13890   Tab.UseTab = FormatStyle::UT_Always;
13891   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13892 
13893   EXPECT_EQ("if (aaaaaaaa && // q\n"
13894             "    bb)\t\t// w\n"
13895             "\t;",
13896             format("if (aaaaaaaa &&// q\n"
13897                    "bb)// w\n"
13898                    ";",
13899                    Tab));
13900   EXPECT_EQ("if (aaa && bbb) // w\n"
13901             "\t;",
13902             format("if(aaa&&bbb)// w\n"
13903                    ";",
13904                    Tab));
13905 
13906   verifyFormat("class X {\n"
13907                "\tvoid f() {\n"
13908                "\t\tsomeFunction(parameter1,\n"
13909                "\t\t\t     parameter2);\n"
13910                "\t}\n"
13911                "};",
13912                Tab);
13913   verifyFormat("#define A                        \\\n"
13914                "\tvoid f() {               \\\n"
13915                "\t\tsomeFunction(    \\\n"
13916                "\t\t    parameter1,  \\\n"
13917                "\t\t    parameter2); \\\n"
13918                "\t}",
13919                Tab);
13920   verifyFormat("int a;\t      // x\n"
13921                "int bbbbbbbb; // x\n",
13922                Tab);
13923 
13924   Tab.TabWidth = 4;
13925   Tab.IndentWidth = 8;
13926   verifyFormat("class TabWidth4Indent8 {\n"
13927                "\t\tvoid f() {\n"
13928                "\t\t\t\tsomeFunction(parameter1,\n"
13929                "\t\t\t\t\t\t\t parameter2);\n"
13930                "\t\t}\n"
13931                "};",
13932                Tab);
13933 
13934   Tab.TabWidth = 4;
13935   Tab.IndentWidth = 4;
13936   verifyFormat("class TabWidth4Indent4 {\n"
13937                "\tvoid f() {\n"
13938                "\t\tsomeFunction(parameter1,\n"
13939                "\t\t\t\t\t parameter2);\n"
13940                "\t}\n"
13941                "};",
13942                Tab);
13943 
13944   Tab.TabWidth = 8;
13945   Tab.IndentWidth = 4;
13946   verifyFormat("class TabWidth8Indent4 {\n"
13947                "    void f() {\n"
13948                "\tsomeFunction(parameter1,\n"
13949                "\t\t     parameter2);\n"
13950                "    }\n"
13951                "};",
13952                Tab);
13953 
13954   Tab.TabWidth = 8;
13955   Tab.IndentWidth = 8;
13956   EXPECT_EQ("/*\n"
13957             "\t      a\t\tcomment\n"
13958             "\t      in multiple lines\n"
13959             "       */",
13960             format("   /*\t \t \n"
13961                    " \t \t a\t\tcomment\t \t\n"
13962                    " \t \t in multiple lines\t\n"
13963                    " \t  */",
13964                    Tab));
13965 
13966   Tab.UseTab = FormatStyle::UT_ForIndentation;
13967   verifyFormat("{\n"
13968                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13969                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13970                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13971                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13972                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13973                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13974                "};",
13975                Tab);
13976   verifyFormat("enum AA {\n"
13977                "\ta1, // Force multiple lines\n"
13978                "\ta2,\n"
13979                "\ta3\n"
13980                "};",
13981                Tab);
13982   EXPECT_EQ("if (aaaaaaaa && // q\n"
13983             "    bb)         // w\n"
13984             "\t;",
13985             format("if (aaaaaaaa &&// q\n"
13986                    "bb)// w\n"
13987                    ";",
13988                    Tab));
13989   verifyFormat("class X {\n"
13990                "\tvoid f() {\n"
13991                "\t\tsomeFunction(parameter1,\n"
13992                "\t\t             parameter2);\n"
13993                "\t}\n"
13994                "};",
13995                Tab);
13996   verifyFormat("{\n"
13997                "\tQ(\n"
13998                "\t    {\n"
13999                "\t\t    int a;\n"
14000                "\t\t    someFunction(aaaaaaaa,\n"
14001                "\t\t                 bbbbbbb);\n"
14002                "\t    },\n"
14003                "\t    p);\n"
14004                "}",
14005                Tab);
14006   EXPECT_EQ("{\n"
14007             "\t/* aaaa\n"
14008             "\t   bbbb */\n"
14009             "}",
14010             format("{\n"
14011                    "/* aaaa\n"
14012                    "   bbbb */\n"
14013                    "}",
14014                    Tab));
14015   EXPECT_EQ("{\n"
14016             "\t/*\n"
14017             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14018             "\t  bbbbbbbbbbbbb\n"
14019             "\t*/\n"
14020             "}",
14021             format("{\n"
14022                    "/*\n"
14023                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14024                    "*/\n"
14025                    "}",
14026                    Tab));
14027   EXPECT_EQ("{\n"
14028             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14029             "\t// bbbbbbbbbbbbb\n"
14030             "}",
14031             format("{\n"
14032                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14033                    "}",
14034                    Tab));
14035   EXPECT_EQ("{\n"
14036             "\t/*\n"
14037             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14038             "\t  bbbbbbbbbbbbb\n"
14039             "\t*/\n"
14040             "}",
14041             format("{\n"
14042                    "\t/*\n"
14043                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14044                    "\t*/\n"
14045                    "}",
14046                    Tab));
14047   EXPECT_EQ("{\n"
14048             "\t/*\n"
14049             "\n"
14050             "\t*/\n"
14051             "}",
14052             format("{\n"
14053                    "\t/*\n"
14054                    "\n"
14055                    "\t*/\n"
14056                    "}",
14057                    Tab));
14058   EXPECT_EQ("{\n"
14059             "\t/*\n"
14060             " asdf\n"
14061             "\t*/\n"
14062             "}",
14063             format("{\n"
14064                    "\t/*\n"
14065                    " asdf\n"
14066                    "\t*/\n"
14067                    "}",
14068                    Tab));
14069 
14070   verifyFormat("void f() {\n"
14071                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14072                "\t            : bbbbbbbbbbbbbbbbbb\n"
14073                "}",
14074                Tab);
14075   FormatStyle TabNoBreak = Tab;
14076   TabNoBreak.BreakBeforeTernaryOperators = false;
14077   verifyFormat("void f() {\n"
14078                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14079                "\t              bbbbbbbbbbbbbbbbbb\n"
14080                "}",
14081                TabNoBreak);
14082   verifyFormat("void f() {\n"
14083                "\treturn true ?\n"
14084                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14085                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14086                "}",
14087                TabNoBreak);
14088 
14089   Tab.UseTab = FormatStyle::UT_Never;
14090   EXPECT_EQ("/*\n"
14091             "              a\t\tcomment\n"
14092             "              in multiple lines\n"
14093             "       */",
14094             format("   /*\t \t \n"
14095                    " \t \t a\t\tcomment\t \t\n"
14096                    " \t \t in multiple lines\t\n"
14097                    " \t  */",
14098                    Tab));
14099   EXPECT_EQ("/* some\n"
14100             "   comment */",
14101             format(" \t \t /* some\n"
14102                    " \t \t    comment */",
14103                    Tab));
14104   EXPECT_EQ("int a; /* some\n"
14105             "   comment */",
14106             format(" \t \t int a; /* some\n"
14107                    " \t \t    comment */",
14108                    Tab));
14109 
14110   EXPECT_EQ("int a; /* some\n"
14111             "comment */",
14112             format(" \t \t int\ta; /* some\n"
14113                    " \t \t    comment */",
14114                    Tab));
14115   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14116             "    comment */",
14117             format(" \t \t f(\"\t\t\"); /* some\n"
14118                    " \t \t    comment */",
14119                    Tab));
14120   EXPECT_EQ("{\n"
14121             "        /*\n"
14122             "         * Comment\n"
14123             "         */\n"
14124             "        int i;\n"
14125             "}",
14126             format("{\n"
14127                    "\t/*\n"
14128                    "\t * Comment\n"
14129                    "\t */\n"
14130                    "\t int i;\n"
14131                    "}",
14132                    Tab));
14133 
14134   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14135   Tab.TabWidth = 8;
14136   Tab.IndentWidth = 8;
14137   EXPECT_EQ("if (aaaaaaaa && // q\n"
14138             "    bb)         // w\n"
14139             "\t;",
14140             format("if (aaaaaaaa &&// q\n"
14141                    "bb)// w\n"
14142                    ";",
14143                    Tab));
14144   EXPECT_EQ("if (aaa && bbb) // w\n"
14145             "\t;",
14146             format("if(aaa&&bbb)// w\n"
14147                    ";",
14148                    Tab));
14149   verifyFormat("class X {\n"
14150                "\tvoid f() {\n"
14151                "\t\tsomeFunction(parameter1,\n"
14152                "\t\t\t     parameter2);\n"
14153                "\t}\n"
14154                "};",
14155                Tab);
14156   verifyFormat("#define A                        \\\n"
14157                "\tvoid f() {               \\\n"
14158                "\t\tsomeFunction(    \\\n"
14159                "\t\t    parameter1,  \\\n"
14160                "\t\t    parameter2); \\\n"
14161                "\t}",
14162                Tab);
14163   Tab.TabWidth = 4;
14164   Tab.IndentWidth = 8;
14165   verifyFormat("class TabWidth4Indent8 {\n"
14166                "\t\tvoid f() {\n"
14167                "\t\t\t\tsomeFunction(parameter1,\n"
14168                "\t\t\t\t\t\t\t parameter2);\n"
14169                "\t\t}\n"
14170                "};",
14171                Tab);
14172   Tab.TabWidth = 4;
14173   Tab.IndentWidth = 4;
14174   verifyFormat("class TabWidth4Indent4 {\n"
14175                "\tvoid f() {\n"
14176                "\t\tsomeFunction(parameter1,\n"
14177                "\t\t\t\t\t parameter2);\n"
14178                "\t}\n"
14179                "};",
14180                Tab);
14181   Tab.TabWidth = 8;
14182   Tab.IndentWidth = 4;
14183   verifyFormat("class TabWidth8Indent4 {\n"
14184                "    void f() {\n"
14185                "\tsomeFunction(parameter1,\n"
14186                "\t\t     parameter2);\n"
14187                "    }\n"
14188                "};",
14189                Tab);
14190   Tab.TabWidth = 8;
14191   Tab.IndentWidth = 8;
14192   EXPECT_EQ("/*\n"
14193             "\t      a\t\tcomment\n"
14194             "\t      in multiple lines\n"
14195             "       */",
14196             format("   /*\t \t \n"
14197                    " \t \t a\t\tcomment\t \t\n"
14198                    " \t \t in multiple lines\t\n"
14199                    " \t  */",
14200                    Tab));
14201   verifyFormat("{\n"
14202                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14203                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14204                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14205                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14206                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14207                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14208                "};",
14209                Tab);
14210   verifyFormat("enum AA {\n"
14211                "\ta1, // Force multiple lines\n"
14212                "\ta2,\n"
14213                "\ta3\n"
14214                "};",
14215                Tab);
14216   EXPECT_EQ("if (aaaaaaaa && // q\n"
14217             "    bb)         // w\n"
14218             "\t;",
14219             format("if (aaaaaaaa &&// q\n"
14220                    "bb)// w\n"
14221                    ";",
14222                    Tab));
14223   verifyFormat("class X {\n"
14224                "\tvoid f() {\n"
14225                "\t\tsomeFunction(parameter1,\n"
14226                "\t\t\t     parameter2);\n"
14227                "\t}\n"
14228                "};",
14229                Tab);
14230   verifyFormat("{\n"
14231                "\tQ(\n"
14232                "\t    {\n"
14233                "\t\t    int a;\n"
14234                "\t\t    someFunction(aaaaaaaa,\n"
14235                "\t\t\t\t bbbbbbb);\n"
14236                "\t    },\n"
14237                "\t    p);\n"
14238                "}",
14239                Tab);
14240   EXPECT_EQ("{\n"
14241             "\t/* aaaa\n"
14242             "\t   bbbb */\n"
14243             "}",
14244             format("{\n"
14245                    "/* aaaa\n"
14246                    "   bbbb */\n"
14247                    "}",
14248                    Tab));
14249   EXPECT_EQ("{\n"
14250             "\t/*\n"
14251             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14252             "\t  bbbbbbbbbbbbb\n"
14253             "\t*/\n"
14254             "}",
14255             format("{\n"
14256                    "/*\n"
14257                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14258                    "*/\n"
14259                    "}",
14260                    Tab));
14261   EXPECT_EQ("{\n"
14262             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14263             "\t// bbbbbbbbbbbbb\n"
14264             "}",
14265             format("{\n"
14266                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14267                    "}",
14268                    Tab));
14269   EXPECT_EQ("{\n"
14270             "\t/*\n"
14271             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14272             "\t  bbbbbbbbbbbbb\n"
14273             "\t*/\n"
14274             "}",
14275             format("{\n"
14276                    "\t/*\n"
14277                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14278                    "\t*/\n"
14279                    "}",
14280                    Tab));
14281   EXPECT_EQ("{\n"
14282             "\t/*\n"
14283             "\n"
14284             "\t*/\n"
14285             "}",
14286             format("{\n"
14287                    "\t/*\n"
14288                    "\n"
14289                    "\t*/\n"
14290                    "}",
14291                    Tab));
14292   EXPECT_EQ("{\n"
14293             "\t/*\n"
14294             " asdf\n"
14295             "\t*/\n"
14296             "}",
14297             format("{\n"
14298                    "\t/*\n"
14299                    " asdf\n"
14300                    "\t*/\n"
14301                    "}",
14302                    Tab));
14303   EXPECT_EQ("/* some\n"
14304             "   comment */",
14305             format(" \t \t /* some\n"
14306                    " \t \t    comment */",
14307                    Tab));
14308   EXPECT_EQ("int a; /* some\n"
14309             "   comment */",
14310             format(" \t \t int a; /* some\n"
14311                    " \t \t    comment */",
14312                    Tab));
14313   EXPECT_EQ("int a; /* some\n"
14314             "comment */",
14315             format(" \t \t int\ta; /* some\n"
14316                    " \t \t    comment */",
14317                    Tab));
14318   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14319             "    comment */",
14320             format(" \t \t f(\"\t\t\"); /* some\n"
14321                    " \t \t    comment */",
14322                    Tab));
14323   EXPECT_EQ("{\n"
14324             "\t/*\n"
14325             "\t * Comment\n"
14326             "\t */\n"
14327             "\tint i;\n"
14328             "}",
14329             format("{\n"
14330                    "\t/*\n"
14331                    "\t * Comment\n"
14332                    "\t */\n"
14333                    "\t int i;\n"
14334                    "}",
14335                    Tab));
14336   Tab.TabWidth = 2;
14337   Tab.IndentWidth = 2;
14338   EXPECT_EQ("{\n"
14339             "\t/* aaaa\n"
14340             "\t\t bbbb */\n"
14341             "}",
14342             format("{\n"
14343                    "/* aaaa\n"
14344                    "\t bbbb */\n"
14345                    "}",
14346                    Tab));
14347   EXPECT_EQ("{\n"
14348             "\t/*\n"
14349             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14350             "\t\tbbbbbbbbbbbbb\n"
14351             "\t*/\n"
14352             "}",
14353             format("{\n"
14354                    "/*\n"
14355                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14356                    "*/\n"
14357                    "}",
14358                    Tab));
14359   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14360   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14361   Tab.TabWidth = 4;
14362   Tab.IndentWidth = 4;
14363   verifyFormat("class Assign {\n"
14364                "\tvoid f() {\n"
14365                "\t\tint         x      = 123;\n"
14366                "\t\tint         random = 4;\n"
14367                "\t\tstd::string alphabet =\n"
14368                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14369                "\t}\n"
14370                "};",
14371                Tab);
14372 
14373   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14374   Tab.TabWidth = 8;
14375   Tab.IndentWidth = 8;
14376   EXPECT_EQ("if (aaaaaaaa && // q\n"
14377             "    bb)         // w\n"
14378             "\t;",
14379             format("if (aaaaaaaa &&// q\n"
14380                    "bb)// w\n"
14381                    ";",
14382                    Tab));
14383   EXPECT_EQ("if (aaa && bbb) // w\n"
14384             "\t;",
14385             format("if(aaa&&bbb)// w\n"
14386                    ";",
14387                    Tab));
14388   verifyFormat("class X {\n"
14389                "\tvoid f() {\n"
14390                "\t\tsomeFunction(parameter1,\n"
14391                "\t\t             parameter2);\n"
14392                "\t}\n"
14393                "};",
14394                Tab);
14395   verifyFormat("#define A                        \\\n"
14396                "\tvoid f() {               \\\n"
14397                "\t\tsomeFunction(    \\\n"
14398                "\t\t    parameter1,  \\\n"
14399                "\t\t    parameter2); \\\n"
14400                "\t}",
14401                Tab);
14402   Tab.TabWidth = 4;
14403   Tab.IndentWidth = 8;
14404   verifyFormat("class TabWidth4Indent8 {\n"
14405                "\t\tvoid f() {\n"
14406                "\t\t\t\tsomeFunction(parameter1,\n"
14407                "\t\t\t\t             parameter2);\n"
14408                "\t\t}\n"
14409                "};",
14410                Tab);
14411   Tab.TabWidth = 4;
14412   Tab.IndentWidth = 4;
14413   verifyFormat("class TabWidth4Indent4 {\n"
14414                "\tvoid f() {\n"
14415                "\t\tsomeFunction(parameter1,\n"
14416                "\t\t             parameter2);\n"
14417                "\t}\n"
14418                "};",
14419                Tab);
14420   Tab.TabWidth = 8;
14421   Tab.IndentWidth = 4;
14422   verifyFormat("class TabWidth8Indent4 {\n"
14423                "    void f() {\n"
14424                "\tsomeFunction(parameter1,\n"
14425                "\t             parameter2);\n"
14426                "    }\n"
14427                "};",
14428                Tab);
14429   Tab.TabWidth = 8;
14430   Tab.IndentWidth = 8;
14431   EXPECT_EQ("/*\n"
14432             "              a\t\tcomment\n"
14433             "              in multiple lines\n"
14434             "       */",
14435             format("   /*\t \t \n"
14436                    " \t \t a\t\tcomment\t \t\n"
14437                    " \t \t in multiple lines\t\n"
14438                    " \t  */",
14439                    Tab));
14440   verifyFormat("{\n"
14441                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14442                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14443                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14444                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14445                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14446                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14447                "};",
14448                Tab);
14449   verifyFormat("enum AA {\n"
14450                "\ta1, // Force multiple lines\n"
14451                "\ta2,\n"
14452                "\ta3\n"
14453                "};",
14454                Tab);
14455   EXPECT_EQ("if (aaaaaaaa && // q\n"
14456             "    bb)         // w\n"
14457             "\t;",
14458             format("if (aaaaaaaa &&// q\n"
14459                    "bb)// w\n"
14460                    ";",
14461                    Tab));
14462   verifyFormat("class X {\n"
14463                "\tvoid f() {\n"
14464                "\t\tsomeFunction(parameter1,\n"
14465                "\t\t             parameter2);\n"
14466                "\t}\n"
14467                "};",
14468                Tab);
14469   verifyFormat("{\n"
14470                "\tQ(\n"
14471                "\t    {\n"
14472                "\t\t    int a;\n"
14473                "\t\t    someFunction(aaaaaaaa,\n"
14474                "\t\t                 bbbbbbb);\n"
14475                "\t    },\n"
14476                "\t    p);\n"
14477                "}",
14478                Tab);
14479   EXPECT_EQ("{\n"
14480             "\t/* aaaa\n"
14481             "\t   bbbb */\n"
14482             "}",
14483             format("{\n"
14484                    "/* aaaa\n"
14485                    "   bbbb */\n"
14486                    "}",
14487                    Tab));
14488   EXPECT_EQ("{\n"
14489             "\t/*\n"
14490             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14491             "\t  bbbbbbbbbbbbb\n"
14492             "\t*/\n"
14493             "}",
14494             format("{\n"
14495                    "/*\n"
14496                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14497                    "*/\n"
14498                    "}",
14499                    Tab));
14500   EXPECT_EQ("{\n"
14501             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14502             "\t// bbbbbbbbbbbbb\n"
14503             "}",
14504             format("{\n"
14505                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14506                    "}",
14507                    Tab));
14508   EXPECT_EQ("{\n"
14509             "\t/*\n"
14510             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14511             "\t  bbbbbbbbbbbbb\n"
14512             "\t*/\n"
14513             "}",
14514             format("{\n"
14515                    "\t/*\n"
14516                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14517                    "\t*/\n"
14518                    "}",
14519                    Tab));
14520   EXPECT_EQ("{\n"
14521             "\t/*\n"
14522             "\n"
14523             "\t*/\n"
14524             "}",
14525             format("{\n"
14526                    "\t/*\n"
14527                    "\n"
14528                    "\t*/\n"
14529                    "}",
14530                    Tab));
14531   EXPECT_EQ("{\n"
14532             "\t/*\n"
14533             " asdf\n"
14534             "\t*/\n"
14535             "}",
14536             format("{\n"
14537                    "\t/*\n"
14538                    " asdf\n"
14539                    "\t*/\n"
14540                    "}",
14541                    Tab));
14542   EXPECT_EQ("/* some\n"
14543             "   comment */",
14544             format(" \t \t /* some\n"
14545                    " \t \t    comment */",
14546                    Tab));
14547   EXPECT_EQ("int a; /* some\n"
14548             "   comment */",
14549             format(" \t \t int a; /* some\n"
14550                    " \t \t    comment */",
14551                    Tab));
14552   EXPECT_EQ("int a; /* some\n"
14553             "comment */",
14554             format(" \t \t int\ta; /* some\n"
14555                    " \t \t    comment */",
14556                    Tab));
14557   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14558             "    comment */",
14559             format(" \t \t f(\"\t\t\"); /* some\n"
14560                    " \t \t    comment */",
14561                    Tab));
14562   EXPECT_EQ("{\n"
14563             "\t/*\n"
14564             "\t * Comment\n"
14565             "\t */\n"
14566             "\tint i;\n"
14567             "}",
14568             format("{\n"
14569                    "\t/*\n"
14570                    "\t * Comment\n"
14571                    "\t */\n"
14572                    "\t int i;\n"
14573                    "}",
14574                    Tab));
14575   Tab.TabWidth = 2;
14576   Tab.IndentWidth = 2;
14577   EXPECT_EQ("{\n"
14578             "\t/* aaaa\n"
14579             "\t   bbbb */\n"
14580             "}",
14581             format("{\n"
14582                    "/* aaaa\n"
14583                    "   bbbb */\n"
14584                    "}",
14585                    Tab));
14586   EXPECT_EQ("{\n"
14587             "\t/*\n"
14588             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14589             "\t  bbbbbbbbbbbbb\n"
14590             "\t*/\n"
14591             "}",
14592             format("{\n"
14593                    "/*\n"
14594                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14595                    "*/\n"
14596                    "}",
14597                    Tab));
14598   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14599   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14600   Tab.TabWidth = 4;
14601   Tab.IndentWidth = 4;
14602   verifyFormat("class Assign {\n"
14603                "\tvoid f() {\n"
14604                "\t\tint         x      = 123;\n"
14605                "\t\tint         random = 4;\n"
14606                "\t\tstd::string alphabet =\n"
14607                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14608                "\t}\n"
14609                "};",
14610                Tab);
14611   Tab.AlignOperands = FormatStyle::OAS_Align;
14612   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14613                "                 cccccccccccccccccccc;",
14614                Tab);
14615   // no alignment
14616   verifyFormat("int aaaaaaaaaa =\n"
14617                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14618                Tab);
14619   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14620                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14621                "                        : 333333333333333;",
14622                Tab);
14623   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14624   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14625   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14626                "               + cccccccccccccccccccc;",
14627                Tab);
14628 }
14629 
14630 TEST_F(FormatTest, ZeroTabWidth) {
14631   FormatStyle Tab = getLLVMStyleWithColumns(42);
14632   Tab.IndentWidth = 8;
14633   Tab.UseTab = FormatStyle::UT_Never;
14634   Tab.TabWidth = 0;
14635   EXPECT_EQ("void a(){\n"
14636             "    // line starts with '\t'\n"
14637             "};",
14638             format("void a(){\n"
14639                    "\t// line starts with '\t'\n"
14640                    "};",
14641                    Tab));
14642 
14643   EXPECT_EQ("void a(){\n"
14644             "    // line starts with '\t'\n"
14645             "};",
14646             format("void a(){\n"
14647                    "\t\t// line starts with '\t'\n"
14648                    "};",
14649                    Tab));
14650 
14651   Tab.UseTab = FormatStyle::UT_ForIndentation;
14652   EXPECT_EQ("void a(){\n"
14653             "    // line starts with '\t'\n"
14654             "};",
14655             format("void a(){\n"
14656                    "\t// line starts with '\t'\n"
14657                    "};",
14658                    Tab));
14659 
14660   EXPECT_EQ("void a(){\n"
14661             "    // line starts with '\t'\n"
14662             "};",
14663             format("void a(){\n"
14664                    "\t\t// line starts with '\t'\n"
14665                    "};",
14666                    Tab));
14667 
14668   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14669   EXPECT_EQ("void a(){\n"
14670             "    // line starts with '\t'\n"
14671             "};",
14672             format("void a(){\n"
14673                    "\t// line starts with '\t'\n"
14674                    "};",
14675                    Tab));
14676 
14677   EXPECT_EQ("void a(){\n"
14678             "    // line starts with '\t'\n"
14679             "};",
14680             format("void a(){\n"
14681                    "\t\t// line starts with '\t'\n"
14682                    "};",
14683                    Tab));
14684 
14685   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14686   EXPECT_EQ("void a(){\n"
14687             "    // line starts with '\t'\n"
14688             "};",
14689             format("void a(){\n"
14690                    "\t// line starts with '\t'\n"
14691                    "};",
14692                    Tab));
14693 
14694   EXPECT_EQ("void a(){\n"
14695             "    // line starts with '\t'\n"
14696             "};",
14697             format("void a(){\n"
14698                    "\t\t// line starts with '\t'\n"
14699                    "};",
14700                    Tab));
14701 
14702   Tab.UseTab = FormatStyle::UT_Always;
14703   EXPECT_EQ("void a(){\n"
14704             "// line starts with '\t'\n"
14705             "};",
14706             format("void a(){\n"
14707                    "\t// line starts with '\t'\n"
14708                    "};",
14709                    Tab));
14710 
14711   EXPECT_EQ("void a(){\n"
14712             "// line starts with '\t'\n"
14713             "};",
14714             format("void a(){\n"
14715                    "\t\t// line starts with '\t'\n"
14716                    "};",
14717                    Tab));
14718 }
14719 
14720 TEST_F(FormatTest, CalculatesOriginalColumn) {
14721   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14722             "q\"; /* some\n"
14723             "       comment */",
14724             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14725                    "q\"; /* some\n"
14726                    "       comment */",
14727                    getLLVMStyle()));
14728   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14729             "/* some\n"
14730             "   comment */",
14731             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14732                    " /* some\n"
14733                    "    comment */",
14734                    getLLVMStyle()));
14735   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14736             "qqq\n"
14737             "/* some\n"
14738             "   comment */",
14739             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14740                    "qqq\n"
14741                    " /* some\n"
14742                    "    comment */",
14743                    getLLVMStyle()));
14744   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14745             "wwww; /* some\n"
14746             "         comment */",
14747             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14748                    "wwww; /* some\n"
14749                    "         comment */",
14750                    getLLVMStyle()));
14751 }
14752 
14753 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14754   FormatStyle NoSpace = getLLVMStyle();
14755   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14756 
14757   verifyFormat("while(true)\n"
14758                "  continue;",
14759                NoSpace);
14760   verifyFormat("for(;;)\n"
14761                "  continue;",
14762                NoSpace);
14763   verifyFormat("if(true)\n"
14764                "  f();\n"
14765                "else if(true)\n"
14766                "  f();",
14767                NoSpace);
14768   verifyFormat("do {\n"
14769                "  do_something();\n"
14770                "} while(something());",
14771                NoSpace);
14772   verifyFormat("switch(x) {\n"
14773                "default:\n"
14774                "  break;\n"
14775                "}",
14776                NoSpace);
14777   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14778   verifyFormat("size_t x = sizeof(x);", NoSpace);
14779   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14780   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14781   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14782   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14783   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14784   verifyFormat("alignas(128) char a[128];", NoSpace);
14785   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14786   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14787   verifyFormat("int f() throw(Deprecated);", NoSpace);
14788   verifyFormat("typedef void (*cb)(int);", NoSpace);
14789   verifyFormat("T A::operator()();", NoSpace);
14790   verifyFormat("X A::operator++(T);", NoSpace);
14791   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14792 
14793   FormatStyle Space = getLLVMStyle();
14794   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14795 
14796   verifyFormat("int f ();", Space);
14797   verifyFormat("void f (int a, T b) {\n"
14798                "  while (true)\n"
14799                "    continue;\n"
14800                "}",
14801                Space);
14802   verifyFormat("if (true)\n"
14803                "  f ();\n"
14804                "else if (true)\n"
14805                "  f ();",
14806                Space);
14807   verifyFormat("do {\n"
14808                "  do_something ();\n"
14809                "} while (something ());",
14810                Space);
14811   verifyFormat("switch (x) {\n"
14812                "default:\n"
14813                "  break;\n"
14814                "}",
14815                Space);
14816   verifyFormat("A::A () : a (1) {}", Space);
14817   verifyFormat("void f () __attribute__ ((asdf));", Space);
14818   verifyFormat("*(&a + 1);\n"
14819                "&((&a)[1]);\n"
14820                "a[(b + c) * d];\n"
14821                "(((a + 1) * 2) + 3) * 4;",
14822                Space);
14823   verifyFormat("#define A(x) x", Space);
14824   verifyFormat("#define A (x) x", Space);
14825   verifyFormat("#if defined(x)\n"
14826                "#endif",
14827                Space);
14828   verifyFormat("auto i = std::make_unique<int> (5);", Space);
14829   verifyFormat("size_t x = sizeof (x);", Space);
14830   verifyFormat("auto f (int x) -> decltype (x);", Space);
14831   verifyFormat("auto f (int x) -> typeof (x);", Space);
14832   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
14833   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
14834   verifyFormat("int f (T x) noexcept (x.create ());", Space);
14835   verifyFormat("alignas (128) char a[128];", Space);
14836   verifyFormat("size_t x = alignof (MyType);", Space);
14837   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
14838   verifyFormat("int f () throw (Deprecated);", Space);
14839   verifyFormat("typedef void (*cb) (int);", Space);
14840   // FIXME these tests regressed behaviour.
14841   // verifyFormat("T A::operator() ();", Space);
14842   // verifyFormat("X A::operator++ (T);", Space);
14843   verifyFormat("auto lambda = [] () { return 0; };", Space);
14844   verifyFormat("int x = int (y);", Space);
14845 
14846   FormatStyle SomeSpace = getLLVMStyle();
14847   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
14848 
14849   verifyFormat("[]() -> float {}", SomeSpace);
14850   verifyFormat("[] (auto foo) {}", SomeSpace);
14851   verifyFormat("[foo]() -> int {}", SomeSpace);
14852   verifyFormat("int f();", SomeSpace);
14853   verifyFormat("void f (int a, T b) {\n"
14854                "  while (true)\n"
14855                "    continue;\n"
14856                "}",
14857                SomeSpace);
14858   verifyFormat("if (true)\n"
14859                "  f();\n"
14860                "else if (true)\n"
14861                "  f();",
14862                SomeSpace);
14863   verifyFormat("do {\n"
14864                "  do_something();\n"
14865                "} while (something());",
14866                SomeSpace);
14867   verifyFormat("switch (x) {\n"
14868                "default:\n"
14869                "  break;\n"
14870                "}",
14871                SomeSpace);
14872   verifyFormat("A::A() : a (1) {}", SomeSpace);
14873   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
14874   verifyFormat("*(&a + 1);\n"
14875                "&((&a)[1]);\n"
14876                "a[(b + c) * d];\n"
14877                "(((a + 1) * 2) + 3) * 4;",
14878                SomeSpace);
14879   verifyFormat("#define A(x) x", SomeSpace);
14880   verifyFormat("#define A (x) x", SomeSpace);
14881   verifyFormat("#if defined(x)\n"
14882                "#endif",
14883                SomeSpace);
14884   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
14885   verifyFormat("size_t x = sizeof (x);", SomeSpace);
14886   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
14887   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
14888   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
14889   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
14890   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
14891   verifyFormat("alignas (128) char a[128];", SomeSpace);
14892   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
14893   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14894                SomeSpace);
14895   verifyFormat("int f() throw (Deprecated);", SomeSpace);
14896   verifyFormat("typedef void (*cb) (int);", SomeSpace);
14897   verifyFormat("T A::operator()();", SomeSpace);
14898   // FIXME these tests regressed behaviour.
14899   // verifyFormat("X A::operator++ (T);", SomeSpace);
14900   verifyFormat("int x = int (y);", SomeSpace);
14901   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
14902 
14903   FormatStyle SpaceControlStatements = getLLVMStyle();
14904   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14905   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
14906 
14907   verifyFormat("while (true)\n"
14908                "  continue;",
14909                SpaceControlStatements);
14910   verifyFormat("if (true)\n"
14911                "  f();\n"
14912                "else if (true)\n"
14913                "  f();",
14914                SpaceControlStatements);
14915   verifyFormat("for (;;) {\n"
14916                "  do_something();\n"
14917                "}",
14918                SpaceControlStatements);
14919   verifyFormat("do {\n"
14920                "  do_something();\n"
14921                "} while (something());",
14922                SpaceControlStatements);
14923   verifyFormat("switch (x) {\n"
14924                "default:\n"
14925                "  break;\n"
14926                "}",
14927                SpaceControlStatements);
14928 
14929   FormatStyle SpaceFuncDecl = getLLVMStyle();
14930   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14931   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
14932 
14933   verifyFormat("int f ();", SpaceFuncDecl);
14934   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
14935   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
14936   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
14937   verifyFormat("#define A(x) x", SpaceFuncDecl);
14938   verifyFormat("#define A (x) x", SpaceFuncDecl);
14939   verifyFormat("#if defined(x)\n"
14940                "#endif",
14941                SpaceFuncDecl);
14942   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
14943   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
14944   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
14945   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
14946   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
14947   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
14948   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
14949   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
14950   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
14951   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14952                SpaceFuncDecl);
14953   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
14954   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
14955   // FIXME these tests regressed behaviour.
14956   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
14957   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
14958   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
14959   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
14960   verifyFormat("int x = int(y);", SpaceFuncDecl);
14961   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14962                SpaceFuncDecl);
14963 
14964   FormatStyle SpaceFuncDef = getLLVMStyle();
14965   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14966   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
14967 
14968   verifyFormat("int f();", SpaceFuncDef);
14969   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
14970   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
14971   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
14972   verifyFormat("#define A(x) x", SpaceFuncDef);
14973   verifyFormat("#define A (x) x", SpaceFuncDef);
14974   verifyFormat("#if defined(x)\n"
14975                "#endif",
14976                SpaceFuncDef);
14977   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
14978   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
14979   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
14980   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
14981   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
14982   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
14983   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
14984   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
14985   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
14986   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14987                SpaceFuncDef);
14988   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
14989   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
14990   verifyFormat("T A::operator()();", SpaceFuncDef);
14991   verifyFormat("X A::operator++(T);", SpaceFuncDef);
14992   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
14993   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
14994   verifyFormat("int x = int(y);", SpaceFuncDef);
14995   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14996                SpaceFuncDef);
14997 
14998   FormatStyle SpaceIfMacros = getLLVMStyle();
14999   SpaceIfMacros.IfMacros.clear();
15000   SpaceIfMacros.IfMacros.push_back("MYIF");
15001   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15002   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15003   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15004   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15005   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15006 
15007   FormatStyle SpaceForeachMacros = getLLVMStyle();
15008   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15009             FormatStyle::SBS_Never);
15010   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15011   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15012   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15013   verifyFormat("for (;;) {\n"
15014                "}",
15015                SpaceForeachMacros);
15016   verifyFormat("foreach (Item *item, itemlist) {\n"
15017                "}",
15018                SpaceForeachMacros);
15019   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15020                "}",
15021                SpaceForeachMacros);
15022   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15023                "}",
15024                SpaceForeachMacros);
15025   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15026 
15027   FormatStyle SomeSpace2 = getLLVMStyle();
15028   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15029   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15030   verifyFormat("[]() -> float {}", SomeSpace2);
15031   verifyFormat("[] (auto foo) {}", SomeSpace2);
15032   verifyFormat("[foo]() -> int {}", SomeSpace2);
15033   verifyFormat("int f();", SomeSpace2);
15034   verifyFormat("void f (int a, T b) {\n"
15035                "  while (true)\n"
15036                "    continue;\n"
15037                "}",
15038                SomeSpace2);
15039   verifyFormat("if (true)\n"
15040                "  f();\n"
15041                "else if (true)\n"
15042                "  f();",
15043                SomeSpace2);
15044   verifyFormat("do {\n"
15045                "  do_something();\n"
15046                "} while (something());",
15047                SomeSpace2);
15048   verifyFormat("switch (x) {\n"
15049                "default:\n"
15050                "  break;\n"
15051                "}",
15052                SomeSpace2);
15053   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15054   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15055   verifyFormat("*(&a + 1);\n"
15056                "&((&a)[1]);\n"
15057                "a[(b + c) * d];\n"
15058                "(((a + 1) * 2) + 3) * 4;",
15059                SomeSpace2);
15060   verifyFormat("#define A(x) x", SomeSpace2);
15061   verifyFormat("#define A (x) x", SomeSpace2);
15062   verifyFormat("#if defined(x)\n"
15063                "#endif",
15064                SomeSpace2);
15065   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15066   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15067   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15068   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15069   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15070   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15071   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15072   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15073   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15074   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15075                SomeSpace2);
15076   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15077   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15078   verifyFormat("T A::operator()();", SomeSpace2);
15079   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15080   verifyFormat("int x = int (y);", SomeSpace2);
15081   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15082 
15083   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15084   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15085   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15086       .AfterOverloadedOperator = true;
15087 
15088   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15089   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15090   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15091   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15092 
15093   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15094       .AfterOverloadedOperator = false;
15095 
15096   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15097   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15098   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15099   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15100 
15101   auto SpaceAfterRequires = getLLVMStyle();
15102   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15103   EXPECT_FALSE(
15104       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15105   EXPECT_FALSE(
15106       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15107   verifyFormat("void f(auto x)\n"
15108                "  requires requires(int i) { x + i; }\n"
15109                "{}",
15110                SpaceAfterRequires);
15111   verifyFormat("void f(auto x)\n"
15112                "  requires(requires(int i) { x + i; })\n"
15113                "{}",
15114                SpaceAfterRequires);
15115   verifyFormat("if (requires(int i) { x + i; })\n"
15116                "  return;",
15117                SpaceAfterRequires);
15118   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15119   verifyFormat("template <typename T>\n"
15120                "  requires(Foo<T>)\n"
15121                "class Bar;",
15122                SpaceAfterRequires);
15123 
15124   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15125   verifyFormat("void f(auto x)\n"
15126                "  requires requires(int i) { x + i; }\n"
15127                "{}",
15128                SpaceAfterRequires);
15129   verifyFormat("void f(auto x)\n"
15130                "  requires (requires(int i) { x + i; })\n"
15131                "{}",
15132                SpaceAfterRequires);
15133   verifyFormat("if (requires(int i) { x + i; })\n"
15134                "  return;",
15135                SpaceAfterRequires);
15136   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15137   verifyFormat("template <typename T>\n"
15138                "  requires (Foo<T>)\n"
15139                "class Bar;",
15140                SpaceAfterRequires);
15141 
15142   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15143   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15144   verifyFormat("void f(auto x)\n"
15145                "  requires requires (int i) { x + i; }\n"
15146                "{}",
15147                SpaceAfterRequires);
15148   verifyFormat("void f(auto x)\n"
15149                "  requires(requires (int i) { x + i; })\n"
15150                "{}",
15151                SpaceAfterRequires);
15152   verifyFormat("if (requires (int i) { x + i; })\n"
15153                "  return;",
15154                SpaceAfterRequires);
15155   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15156   verifyFormat("template <typename T>\n"
15157                "  requires(Foo<T>)\n"
15158                "class Bar;",
15159                SpaceAfterRequires);
15160 
15161   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15162   verifyFormat("void f(auto x)\n"
15163                "  requires requires (int i) { x + i; }\n"
15164                "{}",
15165                SpaceAfterRequires);
15166   verifyFormat("void f(auto x)\n"
15167                "  requires (requires (int i) { x + i; })\n"
15168                "{}",
15169                SpaceAfterRequires);
15170   verifyFormat("if (requires (int i) { x + i; })\n"
15171                "  return;",
15172                SpaceAfterRequires);
15173   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15174   verifyFormat("template <typename T>\n"
15175                "  requires (Foo<T>)\n"
15176                "class Bar;",
15177                SpaceAfterRequires);
15178 }
15179 
15180 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15181   FormatStyle Spaces = getLLVMStyle();
15182   Spaces.SpaceAfterLogicalNot = true;
15183 
15184   verifyFormat("bool x = ! y", Spaces);
15185   verifyFormat("if (! isFailure())", Spaces);
15186   verifyFormat("if (! (a && b))", Spaces);
15187   verifyFormat("\"Error!\"", Spaces);
15188   verifyFormat("! ! x", Spaces);
15189 }
15190 
15191 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15192   FormatStyle Spaces = getLLVMStyle();
15193 
15194   Spaces.SpacesInParentheses = true;
15195   verifyFormat("do_something( ::globalVar );", Spaces);
15196   verifyFormat("call( x, y, z );", Spaces);
15197   verifyFormat("call();", Spaces);
15198   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15199   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15200                Spaces);
15201   verifyFormat("while ( (bool)1 )\n"
15202                "  continue;",
15203                Spaces);
15204   verifyFormat("for ( ;; )\n"
15205                "  continue;",
15206                Spaces);
15207   verifyFormat("if ( true )\n"
15208                "  f();\n"
15209                "else if ( true )\n"
15210                "  f();",
15211                Spaces);
15212   verifyFormat("do {\n"
15213                "  do_something( (int)i );\n"
15214                "} while ( something() );",
15215                Spaces);
15216   verifyFormat("switch ( x ) {\n"
15217                "default:\n"
15218                "  break;\n"
15219                "}",
15220                Spaces);
15221 
15222   Spaces.SpacesInParentheses = false;
15223   Spaces.SpacesInCStyleCastParentheses = true;
15224   verifyFormat("Type *A = ( Type * )P;", Spaces);
15225   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15226   verifyFormat("x = ( int32 )y;", Spaces);
15227   verifyFormat("int a = ( int )(2.0f);", Spaces);
15228   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15229   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15230   verifyFormat("#define x (( int )-1)", Spaces);
15231 
15232   // Run the first set of tests again with:
15233   Spaces.SpacesInParentheses = false;
15234   Spaces.SpaceInEmptyParentheses = true;
15235   Spaces.SpacesInCStyleCastParentheses = true;
15236   verifyFormat("call(x, y, z);", Spaces);
15237   verifyFormat("call( );", Spaces);
15238   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15239   verifyFormat("while (( bool )1)\n"
15240                "  continue;",
15241                Spaces);
15242   verifyFormat("for (;;)\n"
15243                "  continue;",
15244                Spaces);
15245   verifyFormat("if (true)\n"
15246                "  f( );\n"
15247                "else if (true)\n"
15248                "  f( );",
15249                Spaces);
15250   verifyFormat("do {\n"
15251                "  do_something(( int )i);\n"
15252                "} while (something( ));",
15253                Spaces);
15254   verifyFormat("switch (x) {\n"
15255                "default:\n"
15256                "  break;\n"
15257                "}",
15258                Spaces);
15259 
15260   // Run the first set of tests again with:
15261   Spaces.SpaceAfterCStyleCast = true;
15262   verifyFormat("call(x, y, z);", Spaces);
15263   verifyFormat("call( );", Spaces);
15264   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15265   verifyFormat("while (( bool ) 1)\n"
15266                "  continue;",
15267                Spaces);
15268   verifyFormat("for (;;)\n"
15269                "  continue;",
15270                Spaces);
15271   verifyFormat("if (true)\n"
15272                "  f( );\n"
15273                "else if (true)\n"
15274                "  f( );",
15275                Spaces);
15276   verifyFormat("do {\n"
15277                "  do_something(( int ) i);\n"
15278                "} while (something( ));",
15279                Spaces);
15280   verifyFormat("switch (x) {\n"
15281                "default:\n"
15282                "  break;\n"
15283                "}",
15284                Spaces);
15285   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15286   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15287   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15288   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15289   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15290 
15291   // Run subset of tests again with:
15292   Spaces.SpacesInCStyleCastParentheses = false;
15293   Spaces.SpaceAfterCStyleCast = true;
15294   verifyFormat("while ((bool) 1)\n"
15295                "  continue;",
15296                Spaces);
15297   verifyFormat("do {\n"
15298                "  do_something((int) i);\n"
15299                "} while (something( ));",
15300                Spaces);
15301 
15302   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15303   verifyFormat("size_t idx = (size_t) a;", Spaces);
15304   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15305   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15306   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15307   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15308   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15309   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15310   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15311   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15312   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15313   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15314   Spaces.ColumnLimit = 80;
15315   Spaces.IndentWidth = 4;
15316   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15317   verifyFormat("void foo( ) {\n"
15318                "    size_t foo = (*(function))(\n"
15319                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15320                "BarrrrrrrrrrrrLong,\n"
15321                "        FoooooooooLooooong);\n"
15322                "}",
15323                Spaces);
15324   Spaces.SpaceAfterCStyleCast = false;
15325   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15326   verifyFormat("size_t idx = (size_t)a;", Spaces);
15327   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15328   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15329   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15330   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15331   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15332 
15333   verifyFormat("void foo( ) {\n"
15334                "    size_t foo = (*(function))(\n"
15335                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15336                "BarrrrrrrrrrrrLong,\n"
15337                "        FoooooooooLooooong);\n"
15338                "}",
15339                Spaces);
15340 }
15341 
15342 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15343   verifyFormat("int a[5];");
15344   verifyFormat("a[3] += 42;");
15345 
15346   FormatStyle Spaces = getLLVMStyle();
15347   Spaces.SpacesInSquareBrackets = true;
15348   // Not lambdas.
15349   verifyFormat("int a[ 5 ];", Spaces);
15350   verifyFormat("a[ 3 ] += 42;", Spaces);
15351   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15352   verifyFormat("double &operator[](int i) { return 0; }\n"
15353                "int i;",
15354                Spaces);
15355   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15356   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15357   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15358   // Lambdas.
15359   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15360   verifyFormat("return [ i, args... ] {};", Spaces);
15361   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15362   verifyFormat("int foo = [ = ]() {};", Spaces);
15363   verifyFormat("int foo = [ & ]() {};", Spaces);
15364   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15365   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15366 }
15367 
15368 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15369   FormatStyle NoSpaceStyle = getLLVMStyle();
15370   verifyFormat("int a[5];", NoSpaceStyle);
15371   verifyFormat("a[3] += 42;", NoSpaceStyle);
15372 
15373   verifyFormat("int a[1];", NoSpaceStyle);
15374   verifyFormat("int 1 [a];", NoSpaceStyle);
15375   verifyFormat("int a[1][2];", NoSpaceStyle);
15376   verifyFormat("a[7] = 5;", NoSpaceStyle);
15377   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15378   verifyFormat("f([] {})", NoSpaceStyle);
15379 
15380   FormatStyle Space = getLLVMStyle();
15381   Space.SpaceBeforeSquareBrackets = true;
15382   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15383   verifyFormat("return [i, args...] {};", Space);
15384 
15385   verifyFormat("int a [5];", Space);
15386   verifyFormat("a [3] += 42;", Space);
15387   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15388   verifyFormat("double &operator[](int i) { return 0; }\n"
15389                "int i;",
15390                Space);
15391   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15392   verifyFormat("int i = a [a][a]->f();", Space);
15393   verifyFormat("int i = (*b) [a]->f();", Space);
15394 
15395   verifyFormat("int a [1];", Space);
15396   verifyFormat("int 1 [a];", Space);
15397   verifyFormat("int a [1][2];", Space);
15398   verifyFormat("a [7] = 5;", Space);
15399   verifyFormat("int a = (f()) [23];", Space);
15400   verifyFormat("f([] {})", Space);
15401 }
15402 
15403 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15404   verifyFormat("int a = 5;");
15405   verifyFormat("a += 42;");
15406   verifyFormat("a or_eq 8;");
15407 
15408   FormatStyle Spaces = getLLVMStyle();
15409   Spaces.SpaceBeforeAssignmentOperators = false;
15410   verifyFormat("int a= 5;", Spaces);
15411   verifyFormat("a+= 42;", Spaces);
15412   verifyFormat("a or_eq 8;", Spaces);
15413 }
15414 
15415 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15416   verifyFormat("class Foo : public Bar {};");
15417   verifyFormat("Foo::Foo() : foo(1) {}");
15418   verifyFormat("for (auto a : b) {\n}");
15419   verifyFormat("int x = a ? b : c;");
15420   verifyFormat("{\n"
15421                "label0:\n"
15422                "  int x = 0;\n"
15423                "}");
15424   verifyFormat("switch (x) {\n"
15425                "case 1:\n"
15426                "default:\n"
15427                "}");
15428   verifyFormat("switch (allBraces) {\n"
15429                "case 1: {\n"
15430                "  break;\n"
15431                "}\n"
15432                "case 2: {\n"
15433                "  [[fallthrough]];\n"
15434                "}\n"
15435                "default: {\n"
15436                "  break;\n"
15437                "}\n"
15438                "}");
15439 
15440   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15441   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15442   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15443   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15444   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15445   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15446   verifyFormat("{\n"
15447                "label1:\n"
15448                "  int x = 0;\n"
15449                "}",
15450                CtorInitializerStyle);
15451   verifyFormat("switch (x) {\n"
15452                "case 1:\n"
15453                "default:\n"
15454                "}",
15455                CtorInitializerStyle);
15456   verifyFormat("switch (allBraces) {\n"
15457                "case 1: {\n"
15458                "  break;\n"
15459                "}\n"
15460                "case 2: {\n"
15461                "  [[fallthrough]];\n"
15462                "}\n"
15463                "default: {\n"
15464                "  break;\n"
15465                "}\n"
15466                "}",
15467                CtorInitializerStyle);
15468   CtorInitializerStyle.BreakConstructorInitializers =
15469       FormatStyle::BCIS_AfterColon;
15470   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15471                "    aaaaaaaaaaaaaaaa(1),\n"
15472                "    bbbbbbbbbbbbbbbb(2) {}",
15473                CtorInitializerStyle);
15474   CtorInitializerStyle.BreakConstructorInitializers =
15475       FormatStyle::BCIS_BeforeComma;
15476   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15477                "    : aaaaaaaaaaaaaaaa(1)\n"
15478                "    , bbbbbbbbbbbbbbbb(2) {}",
15479                CtorInitializerStyle);
15480   CtorInitializerStyle.BreakConstructorInitializers =
15481       FormatStyle::BCIS_BeforeColon;
15482   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15483                "    : aaaaaaaaaaaaaaaa(1),\n"
15484                "      bbbbbbbbbbbbbbbb(2) {}",
15485                CtorInitializerStyle);
15486   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15487   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15488                ": aaaaaaaaaaaaaaaa(1),\n"
15489                "  bbbbbbbbbbbbbbbb(2) {}",
15490                CtorInitializerStyle);
15491 
15492   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15493   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15494   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15495   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15496   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15497   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15498   verifyFormat("{\n"
15499                "label2:\n"
15500                "  int x = 0;\n"
15501                "}",
15502                InheritanceStyle);
15503   verifyFormat("switch (x) {\n"
15504                "case 1:\n"
15505                "default:\n"
15506                "}",
15507                InheritanceStyle);
15508   verifyFormat("switch (allBraces) {\n"
15509                "case 1: {\n"
15510                "  break;\n"
15511                "}\n"
15512                "case 2: {\n"
15513                "  [[fallthrough]];\n"
15514                "}\n"
15515                "default: {\n"
15516                "  break;\n"
15517                "}\n"
15518                "}",
15519                InheritanceStyle);
15520   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15521   verifyFormat("class Foooooooooooooooooooooo\n"
15522                "    : public aaaaaaaaaaaaaaaaaa,\n"
15523                "      public bbbbbbbbbbbbbbbbbb {\n"
15524                "}",
15525                InheritanceStyle);
15526   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15527   verifyFormat("class Foooooooooooooooooooooo:\n"
15528                "    public aaaaaaaaaaaaaaaaaa,\n"
15529                "    public bbbbbbbbbbbbbbbbbb {\n"
15530                "}",
15531                InheritanceStyle);
15532   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15533   verifyFormat("class Foooooooooooooooooooooo\n"
15534                "    : public aaaaaaaaaaaaaaaaaa\n"
15535                "    , public bbbbbbbbbbbbbbbbbb {\n"
15536                "}",
15537                InheritanceStyle);
15538   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15539   verifyFormat("class Foooooooooooooooooooooo\n"
15540                "    : public aaaaaaaaaaaaaaaaaa,\n"
15541                "      public bbbbbbbbbbbbbbbbbb {\n"
15542                "}",
15543                InheritanceStyle);
15544   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15545   verifyFormat("class Foooooooooooooooooooooo\n"
15546                ": public aaaaaaaaaaaaaaaaaa,\n"
15547                "  public bbbbbbbbbbbbbbbbbb {}",
15548                InheritanceStyle);
15549 
15550   FormatStyle ForLoopStyle = getLLVMStyle();
15551   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15552   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15553   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15554   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15555   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15556   verifyFormat("{\n"
15557                "label2:\n"
15558                "  int x = 0;\n"
15559                "}",
15560                ForLoopStyle);
15561   verifyFormat("switch (x) {\n"
15562                "case 1:\n"
15563                "default:\n"
15564                "}",
15565                ForLoopStyle);
15566   verifyFormat("switch (allBraces) {\n"
15567                "case 1: {\n"
15568                "  break;\n"
15569                "}\n"
15570                "case 2: {\n"
15571                "  [[fallthrough]];\n"
15572                "}\n"
15573                "default: {\n"
15574                "  break;\n"
15575                "}\n"
15576                "}",
15577                ForLoopStyle);
15578 
15579   FormatStyle CaseStyle = getLLVMStyle();
15580   CaseStyle.SpaceBeforeCaseColon = true;
15581   verifyFormat("class Foo : public Bar {};", CaseStyle);
15582   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15583   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15584   verifyFormat("int x = a ? b : c;", CaseStyle);
15585   verifyFormat("switch (x) {\n"
15586                "case 1 :\n"
15587                "default :\n"
15588                "}",
15589                CaseStyle);
15590   verifyFormat("switch (allBraces) {\n"
15591                "case 1 : {\n"
15592                "  break;\n"
15593                "}\n"
15594                "case 2 : {\n"
15595                "  [[fallthrough]];\n"
15596                "}\n"
15597                "default : {\n"
15598                "  break;\n"
15599                "}\n"
15600                "}",
15601                CaseStyle);
15602 
15603   FormatStyle NoSpaceStyle = getLLVMStyle();
15604   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
15605   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15606   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15607   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15608   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15609   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15610   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15611   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15612   verifyFormat("{\n"
15613                "label3:\n"
15614                "  int x = 0;\n"
15615                "}",
15616                NoSpaceStyle);
15617   verifyFormat("switch (x) {\n"
15618                "case 1:\n"
15619                "default:\n"
15620                "}",
15621                NoSpaceStyle);
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                NoSpaceStyle);
15634 
15635   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15636   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15637   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15638   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15639   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15640   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15641   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15642   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15643   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15644   verifyFormat("{\n"
15645                "label3:\n"
15646                "  int x = 0;\n"
15647                "}",
15648                InvertedSpaceStyle);
15649   verifyFormat("switch (x) {\n"
15650                "case 1 :\n"
15651                "case 2 : {\n"
15652                "  break;\n"
15653                "}\n"
15654                "default :\n"
15655                "  break;\n"
15656                "}",
15657                InvertedSpaceStyle);
15658   verifyFormat("switch (allBraces) {\n"
15659                "case 1 : {\n"
15660                "  break;\n"
15661                "}\n"
15662                "case 2 : {\n"
15663                "  [[fallthrough]];\n"
15664                "}\n"
15665                "default : {\n"
15666                "  break;\n"
15667                "}\n"
15668                "}",
15669                InvertedSpaceStyle);
15670 }
15671 
15672 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15673   FormatStyle Style = getLLVMStyle();
15674 
15675   Style.PointerAlignment = FormatStyle::PAS_Left;
15676   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15677   verifyFormat("void* const* x = NULL;", Style);
15678 
15679 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15680   do {                                                                         \
15681     Style.PointerAlignment = FormatStyle::Pointers;                            \
15682     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15683     verifyFormat(Code, Style);                                                 \
15684   } while (false)
15685 
15686   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15687   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15688   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15689 
15690   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15691   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15692   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15693 
15694   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15695   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15696   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15697 
15698   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15699   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15700   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15701 
15702   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15703   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15704                         SAPQ_Default);
15705   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15706                         SAPQ_Default);
15707 
15708   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15709   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15710                         SAPQ_Before);
15711   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15712                         SAPQ_Before);
15713 
15714   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15715   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15716   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15717                         SAPQ_After);
15718 
15719   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15720   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15721   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15722 
15723 #undef verifyQualifierSpaces
15724 
15725   FormatStyle Spaces = getLLVMStyle();
15726   Spaces.AttributeMacros.push_back("qualified");
15727   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15728   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15729   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15730   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15731   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15732   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15733   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15734   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15735   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15736   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15737   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15738   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15739   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15740 
15741   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15742   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15743   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15744   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15745   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15746   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15747   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15748   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15749   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15750   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15751   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15752   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15753   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15754   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15755   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15756 
15757   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15758   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15759   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15760   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15761   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15762   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15763   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15764   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15765 }
15766 
15767 TEST_F(FormatTest, AlignConsecutiveMacros) {
15768   FormatStyle Style = getLLVMStyle();
15769   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15770   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15771   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15772 
15773   verifyFormat("#define a 3\n"
15774                "#define bbbb 4\n"
15775                "#define ccc (5)",
15776                Style);
15777 
15778   verifyFormat("#define f(x) (x * x)\n"
15779                "#define fff(x, y, z) (x * y + z)\n"
15780                "#define ffff(x, y) (x - y)",
15781                Style);
15782 
15783   verifyFormat("#define foo(x, y) (x + y)\n"
15784                "#define bar (5, 6)(2 + 2)",
15785                Style);
15786 
15787   verifyFormat("#define a 3\n"
15788                "#define bbbb 4\n"
15789                "#define ccc (5)\n"
15790                "#define f(x) (x * x)\n"
15791                "#define fff(x, y, z) (x * y + z)\n"
15792                "#define ffff(x, y) (x - y)",
15793                Style);
15794 
15795   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15796   verifyFormat("#define a    3\n"
15797                "#define bbbb 4\n"
15798                "#define ccc  (5)",
15799                Style);
15800 
15801   verifyFormat("#define f(x)         (x * x)\n"
15802                "#define fff(x, y, z) (x * y + z)\n"
15803                "#define ffff(x, y)   (x - y)",
15804                Style);
15805 
15806   verifyFormat("#define foo(x, y) (x + y)\n"
15807                "#define bar       (5, 6)(2 + 2)",
15808                Style);
15809 
15810   verifyFormat("#define a            3\n"
15811                "#define bbbb         4\n"
15812                "#define ccc          (5)\n"
15813                "#define f(x)         (x * x)\n"
15814                "#define fff(x, y, z) (x * y + z)\n"
15815                "#define ffff(x, y)   (x - y)",
15816                Style);
15817 
15818   verifyFormat("#define a         5\n"
15819                "#define foo(x, y) (x + y)\n"
15820                "#define CCC       (6)\n"
15821                "auto lambda = []() {\n"
15822                "  auto  ii = 0;\n"
15823                "  float j  = 0;\n"
15824                "  return 0;\n"
15825                "};\n"
15826                "int   i  = 0;\n"
15827                "float i2 = 0;\n"
15828                "auto  v  = type{\n"
15829                "    i = 1,   //\n"
15830                "    (i = 2), //\n"
15831                "    i = 3    //\n"
15832                "};",
15833                Style);
15834 
15835   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15836   Style.ColumnLimit = 20;
15837 
15838   verifyFormat("#define a          \\\n"
15839                "  \"aabbbbbbbbbbbb\"\n"
15840                "#define D          \\\n"
15841                "  \"aabbbbbbbbbbbb\" \\\n"
15842                "  \"ccddeeeeeeeee\"\n"
15843                "#define B          \\\n"
15844                "  \"QQQQQQQQQQQQQ\"  \\\n"
15845                "  \"FFFFFFFFFFFFF\"  \\\n"
15846                "  \"LLLLLLLL\"\n",
15847                Style);
15848 
15849   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15850   verifyFormat("#define a          \\\n"
15851                "  \"aabbbbbbbbbbbb\"\n"
15852                "#define D          \\\n"
15853                "  \"aabbbbbbbbbbbb\" \\\n"
15854                "  \"ccddeeeeeeeee\"\n"
15855                "#define B          \\\n"
15856                "  \"QQQQQQQQQQQQQ\"  \\\n"
15857                "  \"FFFFFFFFFFFFF\"  \\\n"
15858                "  \"LLLLLLLL\"\n",
15859                Style);
15860 
15861   // Test across comments
15862   Style.MaxEmptyLinesToKeep = 10;
15863   Style.ReflowComments = false;
15864   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
15865   EXPECT_EQ("#define a    3\n"
15866             "// line comment\n"
15867             "#define bbbb 4\n"
15868             "#define ccc  (5)",
15869             format("#define a 3\n"
15870                    "// line comment\n"
15871                    "#define bbbb 4\n"
15872                    "#define ccc (5)",
15873                    Style));
15874 
15875   EXPECT_EQ("#define a    3\n"
15876             "/* block comment */\n"
15877             "#define bbbb 4\n"
15878             "#define ccc  (5)",
15879             format("#define a  3\n"
15880                    "/* block comment */\n"
15881                    "#define bbbb 4\n"
15882                    "#define ccc (5)",
15883                    Style));
15884 
15885   EXPECT_EQ("#define a    3\n"
15886             "/* multi-line *\n"
15887             " * block comment */\n"
15888             "#define bbbb 4\n"
15889             "#define ccc  (5)",
15890             format("#define a 3\n"
15891                    "/* multi-line *\n"
15892                    " * block comment */\n"
15893                    "#define bbbb 4\n"
15894                    "#define ccc (5)",
15895                    Style));
15896 
15897   EXPECT_EQ("#define a    3\n"
15898             "// multi-line line comment\n"
15899             "//\n"
15900             "#define bbbb 4\n"
15901             "#define ccc  (5)",
15902             format("#define a  3\n"
15903                    "// multi-line line comment\n"
15904                    "//\n"
15905                    "#define bbbb 4\n"
15906                    "#define ccc (5)",
15907                    Style));
15908 
15909   EXPECT_EQ("#define a 3\n"
15910             "// empty lines still break.\n"
15911             "\n"
15912             "#define bbbb 4\n"
15913             "#define ccc  (5)",
15914             format("#define a     3\n"
15915                    "// empty lines still break.\n"
15916                    "\n"
15917                    "#define bbbb     4\n"
15918                    "#define ccc  (5)",
15919                    Style));
15920 
15921   // Test across empty lines
15922   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
15923   EXPECT_EQ("#define a    3\n"
15924             "\n"
15925             "#define bbbb 4\n"
15926             "#define ccc  (5)",
15927             format("#define a 3\n"
15928                    "\n"
15929                    "#define bbbb 4\n"
15930                    "#define ccc (5)",
15931                    Style));
15932 
15933   EXPECT_EQ("#define a    3\n"
15934             "\n"
15935             "\n"
15936             "\n"
15937             "#define bbbb 4\n"
15938             "#define ccc  (5)",
15939             format("#define a        3\n"
15940                    "\n"
15941                    "\n"
15942                    "\n"
15943                    "#define bbbb 4\n"
15944                    "#define ccc (5)",
15945                    Style));
15946 
15947   EXPECT_EQ("#define a 3\n"
15948             "// comments should break alignment\n"
15949             "//\n"
15950             "#define bbbb 4\n"
15951             "#define ccc  (5)",
15952             format("#define a        3\n"
15953                    "// comments should break alignment\n"
15954                    "//\n"
15955                    "#define bbbb 4\n"
15956                    "#define ccc (5)",
15957                    Style));
15958 
15959   // Test across empty lines and comments
15960   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
15961   verifyFormat("#define a    3\n"
15962                "\n"
15963                "// line comment\n"
15964                "#define bbbb 4\n"
15965                "#define ccc  (5)",
15966                Style);
15967 
15968   EXPECT_EQ("#define a    3\n"
15969             "\n"
15970             "\n"
15971             "/* multi-line *\n"
15972             " * block comment */\n"
15973             "\n"
15974             "\n"
15975             "#define bbbb 4\n"
15976             "#define ccc  (5)",
15977             format("#define a 3\n"
15978                    "\n"
15979                    "\n"
15980                    "/* multi-line *\n"
15981                    " * block comment */\n"
15982                    "\n"
15983                    "\n"
15984                    "#define bbbb 4\n"
15985                    "#define ccc (5)",
15986                    Style));
15987 
15988   EXPECT_EQ("#define a    3\n"
15989             "\n"
15990             "\n"
15991             "/* multi-line *\n"
15992             " * block comment */\n"
15993             "\n"
15994             "\n"
15995             "#define bbbb 4\n"
15996             "#define ccc  (5)",
15997             format("#define a 3\n"
15998                    "\n"
15999                    "\n"
16000                    "/* multi-line *\n"
16001                    " * block comment */\n"
16002                    "\n"
16003                    "\n"
16004                    "#define bbbb 4\n"
16005                    "#define ccc       (5)",
16006                    Style));
16007 }
16008 
16009 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16010   FormatStyle Alignment = getLLVMStyle();
16011   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16012   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
16013 
16014   Alignment.MaxEmptyLinesToKeep = 10;
16015   /* Test alignment across empty lines */
16016   EXPECT_EQ("int a           = 5;\n"
16017             "\n"
16018             "int oneTwoThree = 123;",
16019             format("int a       = 5;\n"
16020                    "\n"
16021                    "int oneTwoThree= 123;",
16022                    Alignment));
16023   EXPECT_EQ("int a           = 5;\n"
16024             "int one         = 1;\n"
16025             "\n"
16026             "int oneTwoThree = 123;",
16027             format("int a = 5;\n"
16028                    "int one = 1;\n"
16029                    "\n"
16030                    "int oneTwoThree = 123;",
16031                    Alignment));
16032   EXPECT_EQ("int a           = 5;\n"
16033             "int one         = 1;\n"
16034             "\n"
16035             "int oneTwoThree = 123;\n"
16036             "int oneTwo      = 12;",
16037             format("int a = 5;\n"
16038                    "int one = 1;\n"
16039                    "\n"
16040                    "int oneTwoThree = 123;\n"
16041                    "int oneTwo = 12;",
16042                    Alignment));
16043 
16044   /* Test across comments */
16045   EXPECT_EQ("int a = 5;\n"
16046             "/* block comment */\n"
16047             "int oneTwoThree = 123;",
16048             format("int a = 5;\n"
16049                    "/* block comment */\n"
16050                    "int oneTwoThree=123;",
16051                    Alignment));
16052 
16053   EXPECT_EQ("int a = 5;\n"
16054             "// line comment\n"
16055             "int oneTwoThree = 123;",
16056             format("int a = 5;\n"
16057                    "// line comment\n"
16058                    "int oneTwoThree=123;",
16059                    Alignment));
16060 
16061   /* Test across comments and newlines */
16062   EXPECT_EQ("int a = 5;\n"
16063             "\n"
16064             "/* block comment */\n"
16065             "int oneTwoThree = 123;",
16066             format("int a = 5;\n"
16067                    "\n"
16068                    "/* block comment */\n"
16069                    "int oneTwoThree=123;",
16070                    Alignment));
16071 
16072   EXPECT_EQ("int a = 5;\n"
16073             "\n"
16074             "// line comment\n"
16075             "int oneTwoThree = 123;",
16076             format("int a = 5;\n"
16077                    "\n"
16078                    "// line comment\n"
16079                    "int oneTwoThree=123;",
16080                    Alignment));
16081 }
16082 
16083 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16084   FormatStyle Alignment = getLLVMStyle();
16085   Alignment.AlignConsecutiveDeclarations =
16086       FormatStyle::ACS_AcrossEmptyLinesAndComments;
16087   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16088 
16089   Alignment.MaxEmptyLinesToKeep = 10;
16090   /* Test alignment across empty lines */
16091   EXPECT_EQ("int         a = 5;\n"
16092             "\n"
16093             "float const oneTwoThree = 123;",
16094             format("int a = 5;\n"
16095                    "\n"
16096                    "float const oneTwoThree = 123;",
16097                    Alignment));
16098   EXPECT_EQ("int         a = 5;\n"
16099             "float const one = 1;\n"
16100             "\n"
16101             "int         oneTwoThree = 123;",
16102             format("int a = 5;\n"
16103                    "float const one = 1;\n"
16104                    "\n"
16105                    "int oneTwoThree = 123;",
16106                    Alignment));
16107 
16108   /* Test across comments */
16109   EXPECT_EQ("float const a = 5;\n"
16110             "/* block comment */\n"
16111             "int         oneTwoThree = 123;",
16112             format("float const a = 5;\n"
16113                    "/* block comment */\n"
16114                    "int oneTwoThree=123;",
16115                    Alignment));
16116 
16117   EXPECT_EQ("float const a = 5;\n"
16118             "// line comment\n"
16119             "int         oneTwoThree = 123;",
16120             format("float const a = 5;\n"
16121                    "// line comment\n"
16122                    "int oneTwoThree=123;",
16123                    Alignment));
16124 
16125   /* Test across comments and newlines */
16126   EXPECT_EQ("float const a = 5;\n"
16127             "\n"
16128             "/* block comment */\n"
16129             "int         oneTwoThree = 123;",
16130             format("float const a = 5;\n"
16131                    "\n"
16132                    "/* block comment */\n"
16133                    "int         oneTwoThree=123;",
16134                    Alignment));
16135 
16136   EXPECT_EQ("float const a = 5;\n"
16137             "\n"
16138             "// line comment\n"
16139             "int         oneTwoThree = 123;",
16140             format("float const a = 5;\n"
16141                    "\n"
16142                    "// line comment\n"
16143                    "int oneTwoThree=123;",
16144                    Alignment));
16145 }
16146 
16147 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16148   FormatStyle Alignment = getLLVMStyle();
16149   Alignment.AlignConsecutiveBitFields =
16150       FormatStyle::ACS_AcrossEmptyLinesAndComments;
16151 
16152   Alignment.MaxEmptyLinesToKeep = 10;
16153   /* Test alignment across empty lines */
16154   EXPECT_EQ("int a            : 5;\n"
16155             "\n"
16156             "int longbitfield : 6;",
16157             format("int a : 5;\n"
16158                    "\n"
16159                    "int longbitfield : 6;",
16160                    Alignment));
16161   EXPECT_EQ("int a            : 5;\n"
16162             "int one          : 1;\n"
16163             "\n"
16164             "int longbitfield : 6;",
16165             format("int a : 5;\n"
16166                    "int one : 1;\n"
16167                    "\n"
16168                    "int longbitfield : 6;",
16169                    Alignment));
16170 
16171   /* Test across comments */
16172   EXPECT_EQ("int a            : 5;\n"
16173             "/* block comment */\n"
16174             "int longbitfield : 6;",
16175             format("int a : 5;\n"
16176                    "/* block comment */\n"
16177                    "int longbitfield : 6;",
16178                    Alignment));
16179   EXPECT_EQ("int a            : 5;\n"
16180             "int one          : 1;\n"
16181             "// line comment\n"
16182             "int longbitfield : 6;",
16183             format("int a : 5;\n"
16184                    "int one : 1;\n"
16185                    "// line comment\n"
16186                    "int longbitfield : 6;",
16187                    Alignment));
16188 
16189   /* Test across comments and newlines */
16190   EXPECT_EQ("int a            : 5;\n"
16191             "/* block comment */\n"
16192             "\n"
16193             "int longbitfield : 6;",
16194             format("int a : 5;\n"
16195                    "/* block comment */\n"
16196                    "\n"
16197                    "int longbitfield : 6;",
16198                    Alignment));
16199   EXPECT_EQ("int a            : 5;\n"
16200             "int one          : 1;\n"
16201             "\n"
16202             "// line comment\n"
16203             "\n"
16204             "int longbitfield : 6;",
16205             format("int a : 5;\n"
16206                    "int one : 1;\n"
16207                    "\n"
16208                    "// line comment \n"
16209                    "\n"
16210                    "int longbitfield : 6;",
16211                    Alignment));
16212 }
16213 
16214 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16215   FormatStyle Alignment = getLLVMStyle();
16216   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16217   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
16218 
16219   Alignment.MaxEmptyLinesToKeep = 10;
16220   /* Test alignment across empty lines */
16221   EXPECT_EQ("int a = 5;\n"
16222             "\n"
16223             "int oneTwoThree = 123;",
16224             format("int a       = 5;\n"
16225                    "\n"
16226                    "int oneTwoThree= 123;",
16227                    Alignment));
16228   EXPECT_EQ("int a   = 5;\n"
16229             "int one = 1;\n"
16230             "\n"
16231             "int oneTwoThree = 123;",
16232             format("int a = 5;\n"
16233                    "int one = 1;\n"
16234                    "\n"
16235                    "int oneTwoThree = 123;",
16236                    Alignment));
16237 
16238   /* Test across comments */
16239   EXPECT_EQ("int a           = 5;\n"
16240             "/* block comment */\n"
16241             "int oneTwoThree = 123;",
16242             format("int a = 5;\n"
16243                    "/* block comment */\n"
16244                    "int oneTwoThree=123;",
16245                    Alignment));
16246 
16247   EXPECT_EQ("int a           = 5;\n"
16248             "// line comment\n"
16249             "int oneTwoThree = 123;",
16250             format("int a = 5;\n"
16251                    "// line comment\n"
16252                    "int oneTwoThree=123;",
16253                    Alignment));
16254 
16255   EXPECT_EQ("int a           = 5;\n"
16256             "/*\n"
16257             " * multi-line block comment\n"
16258             " */\n"
16259             "int oneTwoThree = 123;",
16260             format("int a = 5;\n"
16261                    "/*\n"
16262                    " * multi-line block comment\n"
16263                    " */\n"
16264                    "int oneTwoThree=123;",
16265                    Alignment));
16266 
16267   EXPECT_EQ("int a           = 5;\n"
16268             "//\n"
16269             "// multi-line line comment\n"
16270             "//\n"
16271             "int oneTwoThree = 123;",
16272             format("int a = 5;\n"
16273                    "//\n"
16274                    "// multi-line line comment\n"
16275                    "//\n"
16276                    "int oneTwoThree=123;",
16277                    Alignment));
16278 
16279   /* Test across comments and newlines */
16280   EXPECT_EQ("int a = 5;\n"
16281             "\n"
16282             "/* block comment */\n"
16283             "int oneTwoThree = 123;",
16284             format("int a = 5;\n"
16285                    "\n"
16286                    "/* block comment */\n"
16287                    "int oneTwoThree=123;",
16288                    Alignment));
16289 
16290   EXPECT_EQ("int a = 5;\n"
16291             "\n"
16292             "// line comment\n"
16293             "int oneTwoThree = 123;",
16294             format("int a = 5;\n"
16295                    "\n"
16296                    "// line comment\n"
16297                    "int oneTwoThree=123;",
16298                    Alignment));
16299 }
16300 
16301 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16302   FormatStyle Alignment = getLLVMStyle();
16303   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16304   Alignment.AlignConsecutiveAssignments =
16305       FormatStyle::ACS_AcrossEmptyLinesAndComments;
16306   verifyFormat("int a           = 5;\n"
16307                "int oneTwoThree = 123;",
16308                Alignment);
16309   verifyFormat("int a           = method();\n"
16310                "int oneTwoThree = 133;",
16311                Alignment);
16312   verifyFormat("a &= 5;\n"
16313                "bcd *= 5;\n"
16314                "ghtyf += 5;\n"
16315                "dvfvdb -= 5;\n"
16316                "a /= 5;\n"
16317                "vdsvsv %= 5;\n"
16318                "sfdbddfbdfbb ^= 5;\n"
16319                "dvsdsv |= 5;\n"
16320                "int dsvvdvsdvvv = 123;",
16321                Alignment);
16322   verifyFormat("int i = 1, j = 10;\n"
16323                "something = 2000;",
16324                Alignment);
16325   verifyFormat("something = 2000;\n"
16326                "int i = 1, j = 10;\n",
16327                Alignment);
16328   verifyFormat("something = 2000;\n"
16329                "another   = 911;\n"
16330                "int i = 1, j = 10;\n"
16331                "oneMore = 1;\n"
16332                "i       = 2;",
16333                Alignment);
16334   verifyFormat("int a   = 5;\n"
16335                "int one = 1;\n"
16336                "method();\n"
16337                "int oneTwoThree = 123;\n"
16338                "int oneTwo      = 12;",
16339                Alignment);
16340   verifyFormat("int oneTwoThree = 123;\n"
16341                "int oneTwo      = 12;\n"
16342                "method();\n",
16343                Alignment);
16344   verifyFormat("int oneTwoThree = 123; // comment\n"
16345                "int oneTwo      = 12;  // comment",
16346                Alignment);
16347 
16348   // Bug 25167
16349   /* Uncomment when fixed
16350     verifyFormat("#if A\n"
16351                  "#else\n"
16352                  "int aaaaaaaa = 12;\n"
16353                  "#endif\n"
16354                  "#if B\n"
16355                  "#else\n"
16356                  "int a = 12;\n"
16357                  "#endif\n",
16358                  Alignment);
16359     verifyFormat("enum foo {\n"
16360                  "#if A\n"
16361                  "#else\n"
16362                  "  aaaaaaaa = 12;\n"
16363                  "#endif\n"
16364                  "#if B\n"
16365                  "#else\n"
16366                  "  a = 12;\n"
16367                  "#endif\n"
16368                  "};\n",
16369                  Alignment);
16370   */
16371 
16372   Alignment.MaxEmptyLinesToKeep = 10;
16373   /* Test alignment across empty lines */
16374   EXPECT_EQ("int a           = 5;\n"
16375             "\n"
16376             "int oneTwoThree = 123;",
16377             format("int a       = 5;\n"
16378                    "\n"
16379                    "int oneTwoThree= 123;",
16380                    Alignment));
16381   EXPECT_EQ("int a           = 5;\n"
16382             "int one         = 1;\n"
16383             "\n"
16384             "int oneTwoThree = 123;",
16385             format("int a = 5;\n"
16386                    "int one = 1;\n"
16387                    "\n"
16388                    "int oneTwoThree = 123;",
16389                    Alignment));
16390   EXPECT_EQ("int a           = 5;\n"
16391             "int one         = 1;\n"
16392             "\n"
16393             "int oneTwoThree = 123;\n"
16394             "int oneTwo      = 12;",
16395             format("int a = 5;\n"
16396                    "int one = 1;\n"
16397                    "\n"
16398                    "int oneTwoThree = 123;\n"
16399                    "int oneTwo = 12;",
16400                    Alignment));
16401 
16402   /* Test across comments */
16403   EXPECT_EQ("int a           = 5;\n"
16404             "/* block comment */\n"
16405             "int oneTwoThree = 123;",
16406             format("int a = 5;\n"
16407                    "/* block comment */\n"
16408                    "int oneTwoThree=123;",
16409                    Alignment));
16410 
16411   EXPECT_EQ("int a           = 5;\n"
16412             "// line comment\n"
16413             "int oneTwoThree = 123;",
16414             format("int a = 5;\n"
16415                    "// line comment\n"
16416                    "int oneTwoThree=123;",
16417                    Alignment));
16418 
16419   /* Test across comments and newlines */
16420   EXPECT_EQ("int a           = 5;\n"
16421             "\n"
16422             "/* block comment */\n"
16423             "int oneTwoThree = 123;",
16424             format("int a = 5;\n"
16425                    "\n"
16426                    "/* block comment */\n"
16427                    "int oneTwoThree=123;",
16428                    Alignment));
16429 
16430   EXPECT_EQ("int a           = 5;\n"
16431             "\n"
16432             "// line comment\n"
16433             "int oneTwoThree = 123;",
16434             format("int a = 5;\n"
16435                    "\n"
16436                    "// line comment\n"
16437                    "int oneTwoThree=123;",
16438                    Alignment));
16439 
16440   EXPECT_EQ("int a           = 5;\n"
16441             "//\n"
16442             "// multi-line line comment\n"
16443             "//\n"
16444             "int oneTwoThree = 123;",
16445             format("int a = 5;\n"
16446                    "//\n"
16447                    "// multi-line line comment\n"
16448                    "//\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             "/* block comment */\n"
16467             "\n"
16468             "\n"
16469             "\n"
16470             "int oneTwoThree = 123;",
16471             format("int a = 5;\n"
16472                    "\n"
16473                    "/* block comment */\n"
16474                    "\n"
16475                    "\n"
16476                    "\n"
16477                    "int oneTwoThree=123;",
16478                    Alignment));
16479 
16480   EXPECT_EQ("int a           = 5;\n"
16481             "\n"
16482             "// line comment\n"
16483             "\n"
16484             "\n"
16485             "\n"
16486             "int oneTwoThree = 123;",
16487             format("int a = 5;\n"
16488                    "\n"
16489                    "// line comment\n"
16490                    "\n"
16491                    "\n"
16492                    "\n"
16493                    "int oneTwoThree=123;",
16494                    Alignment));
16495 
16496   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16497   verifyFormat("#define A \\\n"
16498                "  int aaaa       = 12; \\\n"
16499                "  int b          = 23; \\\n"
16500                "  int ccc        = 234; \\\n"
16501                "  int dddddddddd = 2345;",
16502                Alignment);
16503   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16504   verifyFormat("#define A               \\\n"
16505                "  int aaaa       = 12;  \\\n"
16506                "  int b          = 23;  \\\n"
16507                "  int ccc        = 234; \\\n"
16508                "  int dddddddddd = 2345;",
16509                Alignment);
16510   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16511   verifyFormat("#define A                                                      "
16512                "                \\\n"
16513                "  int aaaa       = 12;                                         "
16514                "                \\\n"
16515                "  int b          = 23;                                         "
16516                "                \\\n"
16517                "  int ccc        = 234;                                        "
16518                "                \\\n"
16519                "  int dddddddddd = 2345;",
16520                Alignment);
16521   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16522                "k = 4, int l = 5,\n"
16523                "                  int m = 6) {\n"
16524                "  int j      = 10;\n"
16525                "  otherThing = 1;\n"
16526                "}",
16527                Alignment);
16528   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16529                "  int i   = 1;\n"
16530                "  int j   = 2;\n"
16531                "  int big = 10000;\n"
16532                "}",
16533                Alignment);
16534   verifyFormat("class C {\n"
16535                "public:\n"
16536                "  int i            = 1;\n"
16537                "  virtual void f() = 0;\n"
16538                "};",
16539                Alignment);
16540   verifyFormat("int i = 1;\n"
16541                "if (SomeType t = getSomething()) {\n"
16542                "}\n"
16543                "int j   = 2;\n"
16544                "int big = 10000;",
16545                Alignment);
16546   verifyFormat("int j = 7;\n"
16547                "for (int k = 0; k < N; ++k) {\n"
16548                "}\n"
16549                "int j   = 2;\n"
16550                "int big = 10000;\n"
16551                "}",
16552                Alignment);
16553   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16554   verifyFormat("int i = 1;\n"
16555                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16556                "    = someLooooooooooooooooongFunction();\n"
16557                "int j = 2;",
16558                Alignment);
16559   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16560   verifyFormat("int i = 1;\n"
16561                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16562                "    someLooooooooooooooooongFunction();\n"
16563                "int j = 2;",
16564                Alignment);
16565 
16566   verifyFormat("auto lambda = []() {\n"
16567                "  auto i = 0;\n"
16568                "  return 0;\n"
16569                "};\n"
16570                "int i  = 0;\n"
16571                "auto v = type{\n"
16572                "    i = 1,   //\n"
16573                "    (i = 2), //\n"
16574                "    i = 3    //\n"
16575                "};",
16576                Alignment);
16577 
16578   verifyFormat(
16579       "int i      = 1;\n"
16580       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16581       "                          loooooooooooooooooooooongParameterB);\n"
16582       "int j      = 2;",
16583       Alignment);
16584 
16585   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16586                "          typename B   = very_long_type_name_1,\n"
16587                "          typename T_2 = very_long_type_name_2>\n"
16588                "auto foo() {}\n",
16589                Alignment);
16590   verifyFormat("int a, b = 1;\n"
16591                "int c  = 2;\n"
16592                "int dd = 3;\n",
16593                Alignment);
16594   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16595                "float b[1][] = {{3.f}};\n",
16596                Alignment);
16597   verifyFormat("for (int i = 0; i < 1; i++)\n"
16598                "  int x = 1;\n",
16599                Alignment);
16600   verifyFormat("for (i = 0; i < 1; i++)\n"
16601                "  x = 1;\n"
16602                "y = 1;\n",
16603                Alignment);
16604 
16605   Alignment.ReflowComments = true;
16606   Alignment.ColumnLimit = 50;
16607   EXPECT_EQ("int x   = 0;\n"
16608             "int yy  = 1; /// specificlennospace\n"
16609             "int zzz = 2;\n",
16610             format("int x   = 0;\n"
16611                    "int yy  = 1; ///specificlennospace\n"
16612                    "int zzz = 2;\n",
16613                    Alignment));
16614 }
16615 
16616 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16617   FormatStyle Alignment = getLLVMStyle();
16618   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16619   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16620   verifyFormat("int a = 5;\n"
16621                "int oneTwoThree = 123;",
16622                Alignment);
16623   verifyFormat("int a = 5;\n"
16624                "int oneTwoThree = 123;",
16625                Alignment);
16626 
16627   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16628   verifyFormat("int a           = 5;\n"
16629                "int oneTwoThree = 123;",
16630                Alignment);
16631   verifyFormat("int a           = method();\n"
16632                "int oneTwoThree = 133;",
16633                Alignment);
16634   verifyFormat("a &= 5;\n"
16635                "bcd *= 5;\n"
16636                "ghtyf += 5;\n"
16637                "dvfvdb -= 5;\n"
16638                "a /= 5;\n"
16639                "vdsvsv %= 5;\n"
16640                "sfdbddfbdfbb ^= 5;\n"
16641                "dvsdsv |= 5;\n"
16642                "int dsvvdvsdvvv = 123;",
16643                Alignment);
16644   verifyFormat("int i = 1, j = 10;\n"
16645                "something = 2000;",
16646                Alignment);
16647   verifyFormat("something = 2000;\n"
16648                "int i = 1, j = 10;\n",
16649                Alignment);
16650   verifyFormat("something = 2000;\n"
16651                "another   = 911;\n"
16652                "int i = 1, j = 10;\n"
16653                "oneMore = 1;\n"
16654                "i       = 2;",
16655                Alignment);
16656   verifyFormat("int a   = 5;\n"
16657                "int one = 1;\n"
16658                "method();\n"
16659                "int oneTwoThree = 123;\n"
16660                "int oneTwo      = 12;",
16661                Alignment);
16662   verifyFormat("int oneTwoThree = 123;\n"
16663                "int oneTwo      = 12;\n"
16664                "method();\n",
16665                Alignment);
16666   verifyFormat("int oneTwoThree = 123; // comment\n"
16667                "int oneTwo      = 12;  // comment",
16668                Alignment);
16669   verifyFormat("int f()         = default;\n"
16670                "int &operator() = default;\n"
16671                "int &operator=() {",
16672                Alignment);
16673   verifyFormat("int f()         = delete;\n"
16674                "int &operator() = delete;\n"
16675                "int &operator=() {",
16676                Alignment);
16677   verifyFormat("int f()         = default; // comment\n"
16678                "int &operator() = default; // comment\n"
16679                "int &operator=() {",
16680                Alignment);
16681   verifyFormat("int f()         = default;\n"
16682                "int &operator() = default;\n"
16683                "int &operator==() {",
16684                Alignment);
16685   verifyFormat("int f()         = default;\n"
16686                "int &operator() = default;\n"
16687                "int &operator<=() {",
16688                Alignment);
16689   verifyFormat("int f()         = default;\n"
16690                "int &operator() = default;\n"
16691                "int &operator!=() {",
16692                Alignment);
16693   verifyFormat("int f()         = default;\n"
16694                "int &operator() = default;\n"
16695                "int &operator=();",
16696                Alignment);
16697   verifyFormat("int f()         = delete;\n"
16698                "int &operator() = delete;\n"
16699                "int &operator=();",
16700                Alignment);
16701   verifyFormat("/* long long padding */ int f() = default;\n"
16702                "int &operator()                 = default;\n"
16703                "int &operator/**/ =();",
16704                Alignment);
16705   // https://llvm.org/PR33697
16706   FormatStyle AlignmentWithPenalty = getLLVMStyle();
16707   AlignmentWithPenalty.AlignConsecutiveAssignments =
16708       FormatStyle::ACS_Consecutive;
16709   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
16710   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
16711                "  void f() = delete;\n"
16712                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
16713                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
16714                "};\n",
16715                AlignmentWithPenalty);
16716 
16717   // Bug 25167
16718   /* Uncomment when fixed
16719     verifyFormat("#if A\n"
16720                  "#else\n"
16721                  "int aaaaaaaa = 12;\n"
16722                  "#endif\n"
16723                  "#if B\n"
16724                  "#else\n"
16725                  "int a = 12;\n"
16726                  "#endif\n",
16727                  Alignment);
16728     verifyFormat("enum foo {\n"
16729                  "#if A\n"
16730                  "#else\n"
16731                  "  aaaaaaaa = 12;\n"
16732                  "#endif\n"
16733                  "#if B\n"
16734                  "#else\n"
16735                  "  a = 12;\n"
16736                  "#endif\n"
16737                  "};\n",
16738                  Alignment);
16739   */
16740 
16741   EXPECT_EQ("int a = 5;\n"
16742             "\n"
16743             "int oneTwoThree = 123;",
16744             format("int a       = 5;\n"
16745                    "\n"
16746                    "int oneTwoThree= 123;",
16747                    Alignment));
16748   EXPECT_EQ("int a   = 5;\n"
16749             "int one = 1;\n"
16750             "\n"
16751             "int oneTwoThree = 123;",
16752             format("int a = 5;\n"
16753                    "int one = 1;\n"
16754                    "\n"
16755                    "int oneTwoThree = 123;",
16756                    Alignment));
16757   EXPECT_EQ("int a   = 5;\n"
16758             "int one = 1;\n"
16759             "\n"
16760             "int oneTwoThree = 123;\n"
16761             "int oneTwo      = 12;",
16762             format("int a = 5;\n"
16763                    "int one = 1;\n"
16764                    "\n"
16765                    "int oneTwoThree = 123;\n"
16766                    "int oneTwo = 12;",
16767                    Alignment));
16768   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16769   verifyFormat("#define A \\\n"
16770                "  int aaaa       = 12; \\\n"
16771                "  int b          = 23; \\\n"
16772                "  int ccc        = 234; \\\n"
16773                "  int dddddddddd = 2345;",
16774                Alignment);
16775   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16776   verifyFormat("#define A               \\\n"
16777                "  int aaaa       = 12;  \\\n"
16778                "  int b          = 23;  \\\n"
16779                "  int ccc        = 234; \\\n"
16780                "  int dddddddddd = 2345;",
16781                Alignment);
16782   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16783   verifyFormat("#define A                                                      "
16784                "                \\\n"
16785                "  int aaaa       = 12;                                         "
16786                "                \\\n"
16787                "  int b          = 23;                                         "
16788                "                \\\n"
16789                "  int ccc        = 234;                                        "
16790                "                \\\n"
16791                "  int dddddddddd = 2345;",
16792                Alignment);
16793   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16794                "k = 4, int l = 5,\n"
16795                "                  int m = 6) {\n"
16796                "  int j      = 10;\n"
16797                "  otherThing = 1;\n"
16798                "}",
16799                Alignment);
16800   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16801                "  int i   = 1;\n"
16802                "  int j   = 2;\n"
16803                "  int big = 10000;\n"
16804                "}",
16805                Alignment);
16806   verifyFormat("class C {\n"
16807                "public:\n"
16808                "  int i            = 1;\n"
16809                "  virtual void f() = 0;\n"
16810                "};",
16811                Alignment);
16812   verifyFormat("int i = 1;\n"
16813                "if (SomeType t = getSomething()) {\n"
16814                "}\n"
16815                "int j   = 2;\n"
16816                "int big = 10000;",
16817                Alignment);
16818   verifyFormat("int j = 7;\n"
16819                "for (int k = 0; k < N; ++k) {\n"
16820                "}\n"
16821                "int j   = 2;\n"
16822                "int big = 10000;\n"
16823                "}",
16824                Alignment);
16825   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16826   verifyFormat("int i = 1;\n"
16827                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16828                "    = someLooooooooooooooooongFunction();\n"
16829                "int j = 2;",
16830                Alignment);
16831   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16832   verifyFormat("int i = 1;\n"
16833                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16834                "    someLooooooooooooooooongFunction();\n"
16835                "int j = 2;",
16836                Alignment);
16837 
16838   verifyFormat("auto lambda = []() {\n"
16839                "  auto i = 0;\n"
16840                "  return 0;\n"
16841                "};\n"
16842                "int i  = 0;\n"
16843                "auto v = type{\n"
16844                "    i = 1,   //\n"
16845                "    (i = 2), //\n"
16846                "    i = 3    //\n"
16847                "};",
16848                Alignment);
16849 
16850   verifyFormat(
16851       "int i      = 1;\n"
16852       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16853       "                          loooooooooooooooooooooongParameterB);\n"
16854       "int j      = 2;",
16855       Alignment);
16856 
16857   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16858                "          typename B   = very_long_type_name_1,\n"
16859                "          typename T_2 = very_long_type_name_2>\n"
16860                "auto foo() {}\n",
16861                Alignment);
16862   verifyFormat("int a, b = 1;\n"
16863                "int c  = 2;\n"
16864                "int dd = 3;\n",
16865                Alignment);
16866   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16867                "float b[1][] = {{3.f}};\n",
16868                Alignment);
16869   verifyFormat("for (int i = 0; i < 1; i++)\n"
16870                "  int x = 1;\n",
16871                Alignment);
16872   verifyFormat("for (i = 0; i < 1; i++)\n"
16873                "  x = 1;\n"
16874                "y = 1;\n",
16875                Alignment);
16876 
16877   EXPECT_EQ(Alignment.ReflowComments, true);
16878   Alignment.ColumnLimit = 50;
16879   EXPECT_EQ("int x   = 0;\n"
16880             "int yy  = 1; /// specificlennospace\n"
16881             "int zzz = 2;\n",
16882             format("int x   = 0;\n"
16883                    "int yy  = 1; ///specificlennospace\n"
16884                    "int zzz = 2;\n",
16885                    Alignment));
16886 
16887   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
16888                "auto b                     = [] {\n"
16889                "  f();\n"
16890                "  return;\n"
16891                "};",
16892                Alignment);
16893   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
16894                "auto b                     = g([] {\n"
16895                "  f();\n"
16896                "  return;\n"
16897                "});",
16898                Alignment);
16899   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
16900                "auto b                     = g(param, [] {\n"
16901                "  f();\n"
16902                "  return;\n"
16903                "});",
16904                Alignment);
16905   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
16906                "auto b                     = [] {\n"
16907                "  if (condition) {\n"
16908                "    return;\n"
16909                "  }\n"
16910                "};",
16911                Alignment);
16912 
16913   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
16914                "           ccc ? aaaaa : bbbbb,\n"
16915                "           dddddddddddddddddddddddddd);",
16916                Alignment);
16917   // FIXME: https://llvm.org/PR53497
16918   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
16919   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
16920   //              "    ccc ? aaaaa : bbbbb,\n"
16921   //              "    dddddddddddddddddddddddddd);",
16922   //              Alignment);
16923 }
16924 
16925 TEST_F(FormatTest, AlignConsecutiveBitFields) {
16926   FormatStyle Alignment = getLLVMStyle();
16927   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
16928   verifyFormat("int const a     : 5;\n"
16929                "int oneTwoThree : 23;",
16930                Alignment);
16931 
16932   // Initializers are allowed starting with c++2a
16933   verifyFormat("int const a     : 5 = 1;\n"
16934                "int oneTwoThree : 23 = 0;",
16935                Alignment);
16936 
16937   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16938   verifyFormat("int const a           : 5;\n"
16939                "int       oneTwoThree : 23;",
16940                Alignment);
16941 
16942   verifyFormat("int const a           : 5;  // comment\n"
16943                "int       oneTwoThree : 23; // comment",
16944                Alignment);
16945 
16946   verifyFormat("int const a           : 5 = 1;\n"
16947                "int       oneTwoThree : 23 = 0;",
16948                Alignment);
16949 
16950   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16951   verifyFormat("int const a           : 5  = 1;\n"
16952                "int       oneTwoThree : 23 = 0;",
16953                Alignment);
16954   verifyFormat("int const a           : 5  = {1};\n"
16955                "int       oneTwoThree : 23 = 0;",
16956                Alignment);
16957 
16958   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
16959   verifyFormat("int const a          :5;\n"
16960                "int       oneTwoThree:23;",
16961                Alignment);
16962 
16963   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
16964   verifyFormat("int const a           :5;\n"
16965                "int       oneTwoThree :23;",
16966                Alignment);
16967 
16968   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
16969   verifyFormat("int const a          : 5;\n"
16970                "int       oneTwoThree: 23;",
16971                Alignment);
16972 
16973   // Known limitations: ':' is only recognized as a bitfield colon when
16974   // followed by a number.
16975   /*
16976   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
16977                "int a           : 5;",
16978                Alignment);
16979   */
16980 }
16981 
16982 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
16983   FormatStyle Alignment = getLLVMStyle();
16984   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16985   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16986   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16987   verifyFormat("float const a = 5;\n"
16988                "int oneTwoThree = 123;",
16989                Alignment);
16990   verifyFormat("int a = 5;\n"
16991                "float const oneTwoThree = 123;",
16992                Alignment);
16993 
16994   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16995   verifyFormat("float const a = 5;\n"
16996                "int         oneTwoThree = 123;",
16997                Alignment);
16998   verifyFormat("int         a = method();\n"
16999                "float const oneTwoThree = 133;",
17000                Alignment);
17001   verifyFormat("int i = 1, j = 10;\n"
17002                "something = 2000;",
17003                Alignment);
17004   verifyFormat("something = 2000;\n"
17005                "int i = 1, j = 10;\n",
17006                Alignment);
17007   verifyFormat("float      something = 2000;\n"
17008                "double     another = 911;\n"
17009                "int        i = 1, j = 10;\n"
17010                "const int *oneMore = 1;\n"
17011                "unsigned   i = 2;",
17012                Alignment);
17013   verifyFormat("float a = 5;\n"
17014                "int   one = 1;\n"
17015                "method();\n"
17016                "const double       oneTwoThree = 123;\n"
17017                "const unsigned int oneTwo = 12;",
17018                Alignment);
17019   verifyFormat("int      oneTwoThree{0}; // comment\n"
17020                "unsigned oneTwo;         // comment",
17021                Alignment);
17022   verifyFormat("unsigned int       *a;\n"
17023                "int                *b;\n"
17024                "unsigned int Const *c;\n"
17025                "unsigned int const *d;\n"
17026                "unsigned int Const &e;\n"
17027                "unsigned int const &f;",
17028                Alignment);
17029   verifyFormat("Const unsigned int *c;\n"
17030                "const unsigned int *d;\n"
17031                "Const unsigned int &e;\n"
17032                "const unsigned int &f;\n"
17033                "const unsigned      g;\n"
17034                "Const unsigned      h;",
17035                Alignment);
17036   EXPECT_EQ("float const a = 5;\n"
17037             "\n"
17038             "int oneTwoThree = 123;",
17039             format("float const   a = 5;\n"
17040                    "\n"
17041                    "int           oneTwoThree= 123;",
17042                    Alignment));
17043   EXPECT_EQ("float a = 5;\n"
17044             "int   one = 1;\n"
17045             "\n"
17046             "unsigned oneTwoThree = 123;",
17047             format("float    a = 5;\n"
17048                    "int      one = 1;\n"
17049                    "\n"
17050                    "unsigned oneTwoThree = 123;",
17051                    Alignment));
17052   EXPECT_EQ("float a = 5;\n"
17053             "int   one = 1;\n"
17054             "\n"
17055             "unsigned oneTwoThree = 123;\n"
17056             "int      oneTwo = 12;",
17057             format("float    a = 5;\n"
17058                    "int one = 1;\n"
17059                    "\n"
17060                    "unsigned oneTwoThree = 123;\n"
17061                    "int oneTwo = 12;",
17062                    Alignment));
17063   // Function prototype alignment
17064   verifyFormat("int    a();\n"
17065                "double b();",
17066                Alignment);
17067   verifyFormat("int    a(int x);\n"
17068                "double b();",
17069                Alignment);
17070   unsigned OldColumnLimit = Alignment.ColumnLimit;
17071   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17072   // otherwise the function parameters will be re-flowed onto a single line.
17073   Alignment.ColumnLimit = 0;
17074   EXPECT_EQ("int    a(int   x,\n"
17075             "         float y);\n"
17076             "double b(int    x,\n"
17077             "         double y);",
17078             format("int a(int x,\n"
17079                    " float y);\n"
17080                    "double b(int x,\n"
17081                    " double y);",
17082                    Alignment));
17083   // This ensures that function parameters of function declarations are
17084   // correctly indented when their owning functions are indented.
17085   // The failure case here is for 'double y' to not be indented enough.
17086   EXPECT_EQ("double a(int x);\n"
17087             "int    b(int    y,\n"
17088             "         double z);",
17089             format("double a(int x);\n"
17090                    "int b(int y,\n"
17091                    " double z);",
17092                    Alignment));
17093   // Set ColumnLimit low so that we induce wrapping immediately after
17094   // the function name and opening paren.
17095   Alignment.ColumnLimit = 13;
17096   verifyFormat("int function(\n"
17097                "    int  x,\n"
17098                "    bool y);",
17099                Alignment);
17100   Alignment.ColumnLimit = OldColumnLimit;
17101   // Ensure function pointers don't screw up recursive alignment
17102   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17103                "double b();",
17104                Alignment);
17105   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17106   // Ensure recursive alignment is broken by function braces, so that the
17107   // "a = 1" does not align with subsequent assignments inside the function
17108   // body.
17109   verifyFormat("int func(int a = 1) {\n"
17110                "  int b  = 2;\n"
17111                "  int cc = 3;\n"
17112                "}",
17113                Alignment);
17114   verifyFormat("float      something = 2000;\n"
17115                "double     another   = 911;\n"
17116                "int        i = 1, j = 10;\n"
17117                "const int *oneMore = 1;\n"
17118                "unsigned   i       = 2;",
17119                Alignment);
17120   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17121                "unsigned oneTwo      = 0;   // comment",
17122                Alignment);
17123   // Make sure that scope is correctly tracked, in the absence of braces
17124   verifyFormat("for (int i = 0; i < n; i++)\n"
17125                "  j = i;\n"
17126                "double x = 1;\n",
17127                Alignment);
17128   verifyFormat("if (int i = 0)\n"
17129                "  j = i;\n"
17130                "double x = 1;\n",
17131                Alignment);
17132   // Ensure operator[] and operator() are comprehended
17133   verifyFormat("struct test {\n"
17134                "  long long int foo();\n"
17135                "  int           operator[](int a);\n"
17136                "  double        bar();\n"
17137                "};\n",
17138                Alignment);
17139   verifyFormat("struct test {\n"
17140                "  long long int foo();\n"
17141                "  int           operator()(int a);\n"
17142                "  double        bar();\n"
17143                "};\n",
17144                Alignment);
17145   // http://llvm.org/PR52914
17146   verifyFormat("char *a[]     = {\"a\", // comment\n"
17147                "                 \"bb\"};\n"
17148                "int   bbbbbbb = 0;",
17149                Alignment);
17150 
17151   // PAS_Right
17152   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17153             "  int const i   = 1;\n"
17154             "  int      *j   = 2;\n"
17155             "  int       big = 10000;\n"
17156             "\n"
17157             "  unsigned oneTwoThree = 123;\n"
17158             "  int      oneTwo      = 12;\n"
17159             "  method();\n"
17160             "  float k  = 2;\n"
17161             "  int   ll = 10000;\n"
17162             "}",
17163             format("void SomeFunction(int parameter= 0) {\n"
17164                    " int const  i= 1;\n"
17165                    "  int *j=2;\n"
17166                    " int big  =  10000;\n"
17167                    "\n"
17168                    "unsigned oneTwoThree  =123;\n"
17169                    "int oneTwo = 12;\n"
17170                    "  method();\n"
17171                    "float k= 2;\n"
17172                    "int ll=10000;\n"
17173                    "}",
17174                    Alignment));
17175   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17176             "  int const i   = 1;\n"
17177             "  int     **j   = 2, ***k;\n"
17178             "  int      &k   = i;\n"
17179             "  int     &&l   = i + j;\n"
17180             "  int       big = 10000;\n"
17181             "\n"
17182             "  unsigned oneTwoThree = 123;\n"
17183             "  int      oneTwo      = 12;\n"
17184             "  method();\n"
17185             "  float k  = 2;\n"
17186             "  int   ll = 10000;\n"
17187             "}",
17188             format("void SomeFunction(int parameter= 0) {\n"
17189                    " int const  i= 1;\n"
17190                    "  int **j=2,***k;\n"
17191                    "int &k=i;\n"
17192                    "int &&l=i+j;\n"
17193                    " int big  =  10000;\n"
17194                    "\n"
17195                    "unsigned oneTwoThree  =123;\n"
17196                    "int oneTwo = 12;\n"
17197                    "  method();\n"
17198                    "float k= 2;\n"
17199                    "int ll=10000;\n"
17200                    "}",
17201                    Alignment));
17202   // variables are aligned at their name, pointers are at the right most
17203   // position
17204   verifyFormat("int   *a;\n"
17205                "int  **b;\n"
17206                "int ***c;\n"
17207                "int    foobar;\n",
17208                Alignment);
17209 
17210   // PAS_Left
17211   FormatStyle AlignmentLeft = Alignment;
17212   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17213   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17214             "  int const i   = 1;\n"
17215             "  int*      j   = 2;\n"
17216             "  int       big = 10000;\n"
17217             "\n"
17218             "  unsigned oneTwoThree = 123;\n"
17219             "  int      oneTwo      = 12;\n"
17220             "  method();\n"
17221             "  float k  = 2;\n"
17222             "  int   ll = 10000;\n"
17223             "}",
17224             format("void SomeFunction(int parameter= 0) {\n"
17225                    " int const  i= 1;\n"
17226                    "  int *j=2;\n"
17227                    " int big  =  10000;\n"
17228                    "\n"
17229                    "unsigned oneTwoThree  =123;\n"
17230                    "int oneTwo = 12;\n"
17231                    "  method();\n"
17232                    "float k= 2;\n"
17233                    "int ll=10000;\n"
17234                    "}",
17235                    AlignmentLeft));
17236   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17237             "  int const i   = 1;\n"
17238             "  int**     j   = 2;\n"
17239             "  int&      k   = i;\n"
17240             "  int&&     l   = i + j;\n"
17241             "  int       big = 10000;\n"
17242             "\n"
17243             "  unsigned oneTwoThree = 123;\n"
17244             "  int      oneTwo      = 12;\n"
17245             "  method();\n"
17246             "  float k  = 2;\n"
17247             "  int   ll = 10000;\n"
17248             "}",
17249             format("void SomeFunction(int parameter= 0) {\n"
17250                    " int const  i= 1;\n"
17251                    "  int **j=2;\n"
17252                    "int &k=i;\n"
17253                    "int &&l=i+j;\n"
17254                    " int big  =  10000;\n"
17255                    "\n"
17256                    "unsigned oneTwoThree  =123;\n"
17257                    "int oneTwo = 12;\n"
17258                    "  method();\n"
17259                    "float k= 2;\n"
17260                    "int ll=10000;\n"
17261                    "}",
17262                    AlignmentLeft));
17263   // variables are aligned at their name, pointers are at the left most position
17264   verifyFormat("int*   a;\n"
17265                "int**  b;\n"
17266                "int*** c;\n"
17267                "int    foobar;\n",
17268                AlignmentLeft);
17269 
17270   // PAS_Middle
17271   FormatStyle AlignmentMiddle = Alignment;
17272   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17273   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17274             "  int const i   = 1;\n"
17275             "  int *     j   = 2;\n"
17276             "  int       big = 10000;\n"
17277             "\n"
17278             "  unsigned oneTwoThree = 123;\n"
17279             "  int      oneTwo      = 12;\n"
17280             "  method();\n"
17281             "  float k  = 2;\n"
17282             "  int   ll = 10000;\n"
17283             "}",
17284             format("void SomeFunction(int parameter= 0) {\n"
17285                    " int const  i= 1;\n"
17286                    "  int *j=2;\n"
17287                    " int big  =  10000;\n"
17288                    "\n"
17289                    "unsigned oneTwoThree  =123;\n"
17290                    "int oneTwo = 12;\n"
17291                    "  method();\n"
17292                    "float k= 2;\n"
17293                    "int ll=10000;\n"
17294                    "}",
17295                    AlignmentMiddle));
17296   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17297             "  int const i   = 1;\n"
17298             "  int **    j   = 2, ***k;\n"
17299             "  int &     k   = i;\n"
17300             "  int &&    l   = i + j;\n"
17301             "  int       big = 10000;\n"
17302             "\n"
17303             "  unsigned oneTwoThree = 123;\n"
17304             "  int      oneTwo      = 12;\n"
17305             "  method();\n"
17306             "  float k  = 2;\n"
17307             "  int   ll = 10000;\n"
17308             "}",
17309             format("void SomeFunction(int parameter= 0) {\n"
17310                    " int const  i= 1;\n"
17311                    "  int **j=2,***k;\n"
17312                    "int &k=i;\n"
17313                    "int &&l=i+j;\n"
17314                    " int big  =  10000;\n"
17315                    "\n"
17316                    "unsigned oneTwoThree  =123;\n"
17317                    "int oneTwo = 12;\n"
17318                    "  method();\n"
17319                    "float k= 2;\n"
17320                    "int ll=10000;\n"
17321                    "}",
17322                    AlignmentMiddle));
17323   // variables are aligned at their name, pointers are in the middle
17324   verifyFormat("int *   a;\n"
17325                "int *   b;\n"
17326                "int *** c;\n"
17327                "int     foobar;\n",
17328                AlignmentMiddle);
17329 
17330   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17331   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17332   verifyFormat("#define A \\\n"
17333                "  int       aaaa = 12; \\\n"
17334                "  float     b = 23; \\\n"
17335                "  const int ccc = 234; \\\n"
17336                "  unsigned  dddddddddd = 2345;",
17337                Alignment);
17338   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17339   verifyFormat("#define A              \\\n"
17340                "  int       aaaa = 12; \\\n"
17341                "  float     b = 23;    \\\n"
17342                "  const int ccc = 234; \\\n"
17343                "  unsigned  dddddddddd = 2345;",
17344                Alignment);
17345   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17346   Alignment.ColumnLimit = 30;
17347   verifyFormat("#define A                    \\\n"
17348                "  int       aaaa = 12;       \\\n"
17349                "  float     b = 23;          \\\n"
17350                "  const int ccc = 234;       \\\n"
17351                "  int       dddddddddd = 2345;",
17352                Alignment);
17353   Alignment.ColumnLimit = 80;
17354   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17355                "k = 4, int l = 5,\n"
17356                "                  int m = 6) {\n"
17357                "  const int j = 10;\n"
17358                "  otherThing = 1;\n"
17359                "}",
17360                Alignment);
17361   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17362                "  int const i = 1;\n"
17363                "  int      *j = 2;\n"
17364                "  int       big = 10000;\n"
17365                "}",
17366                Alignment);
17367   verifyFormat("class C {\n"
17368                "public:\n"
17369                "  int          i = 1;\n"
17370                "  virtual void f() = 0;\n"
17371                "};",
17372                Alignment);
17373   verifyFormat("float i = 1;\n"
17374                "if (SomeType t = getSomething()) {\n"
17375                "}\n"
17376                "const unsigned j = 2;\n"
17377                "int            big = 10000;",
17378                Alignment);
17379   verifyFormat("float j = 7;\n"
17380                "for (int k = 0; k < N; ++k) {\n"
17381                "}\n"
17382                "unsigned j = 2;\n"
17383                "int      big = 10000;\n"
17384                "}",
17385                Alignment);
17386   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17387   verifyFormat("float              i = 1;\n"
17388                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17389                "    = someLooooooooooooooooongFunction();\n"
17390                "int j = 2;",
17391                Alignment);
17392   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17393   verifyFormat("int                i = 1;\n"
17394                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17395                "    someLooooooooooooooooongFunction();\n"
17396                "int j = 2;",
17397                Alignment);
17398 
17399   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17400   verifyFormat("auto lambda = []() {\n"
17401                "  auto  ii = 0;\n"
17402                "  float j  = 0;\n"
17403                "  return 0;\n"
17404                "};\n"
17405                "int   i  = 0;\n"
17406                "float i2 = 0;\n"
17407                "auto  v  = type{\n"
17408                "    i = 1,   //\n"
17409                "    (i = 2), //\n"
17410                "    i = 3    //\n"
17411                "};",
17412                Alignment);
17413   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17414 
17415   verifyFormat(
17416       "int      i = 1;\n"
17417       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17418       "                          loooooooooooooooooooooongParameterB);\n"
17419       "int      j = 2;",
17420       Alignment);
17421 
17422   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17423   // We expect declarations and assignments to align, as long as it doesn't
17424   // exceed the column limit, starting a new alignment sequence whenever it
17425   // happens.
17426   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17427   Alignment.ColumnLimit = 30;
17428   verifyFormat("float    ii              = 1;\n"
17429                "unsigned j               = 2;\n"
17430                "int someVerylongVariable = 1;\n"
17431                "AnotherLongType  ll = 123456;\n"
17432                "VeryVeryLongType k  = 2;\n"
17433                "int              myvar = 1;",
17434                Alignment);
17435   Alignment.ColumnLimit = 80;
17436   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17437 
17438   verifyFormat(
17439       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17440       "          typename LongType, typename B>\n"
17441       "auto foo() {}\n",
17442       Alignment);
17443   verifyFormat("float a, b = 1;\n"
17444                "int   c = 2;\n"
17445                "int   dd = 3;\n",
17446                Alignment);
17447   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17448                "float b[1][] = {{3.f}};\n",
17449                Alignment);
17450   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17451   verifyFormat("float a, b = 1;\n"
17452                "int   c  = 2;\n"
17453                "int   dd = 3;\n",
17454                Alignment);
17455   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17456                "float b[1][] = {{3.f}};\n",
17457                Alignment);
17458   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17459 
17460   Alignment.ColumnLimit = 30;
17461   Alignment.BinPackParameters = false;
17462   verifyFormat("void foo(float     a,\n"
17463                "         float     b,\n"
17464                "         int       c,\n"
17465                "         uint32_t *d) {\n"
17466                "  int   *e = 0;\n"
17467                "  float  f = 0;\n"
17468                "  double g = 0;\n"
17469                "}\n"
17470                "void bar(ino_t     a,\n"
17471                "         int       b,\n"
17472                "         uint32_t *c,\n"
17473                "         bool      d) {}\n",
17474                Alignment);
17475   Alignment.BinPackParameters = true;
17476   Alignment.ColumnLimit = 80;
17477 
17478   // Bug 33507
17479   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17480   verifyFormat(
17481       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
17482       "  static const Version verVs2017;\n"
17483       "  return true;\n"
17484       "});\n",
17485       Alignment);
17486   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17487 
17488   // See llvm.org/PR35641
17489   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17490   verifyFormat("int func() { //\n"
17491                "  int      b;\n"
17492                "  unsigned c;\n"
17493                "}",
17494                Alignment);
17495 
17496   // See PR37175
17497   FormatStyle Style = getMozillaStyle();
17498   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17499   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
17500             "foo(int a);",
17501             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
17502 
17503   Alignment.PointerAlignment = FormatStyle::PAS_Left;
17504   verifyFormat("unsigned int*       a;\n"
17505                "int*                b;\n"
17506                "unsigned int Const* c;\n"
17507                "unsigned int const* d;\n"
17508                "unsigned int Const& e;\n"
17509                "unsigned int const& f;",
17510                Alignment);
17511   verifyFormat("Const unsigned int* c;\n"
17512                "const unsigned int* d;\n"
17513                "Const unsigned int& e;\n"
17514                "const unsigned int& f;\n"
17515                "const unsigned      g;\n"
17516                "Const unsigned      h;",
17517                Alignment);
17518 
17519   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
17520   verifyFormat("unsigned int *       a;\n"
17521                "int *                b;\n"
17522                "unsigned int Const * c;\n"
17523                "unsigned int const * d;\n"
17524                "unsigned int Const & e;\n"
17525                "unsigned int const & f;",
17526                Alignment);
17527   verifyFormat("Const unsigned int * c;\n"
17528                "const unsigned int * d;\n"
17529                "Const unsigned int & e;\n"
17530                "const unsigned int & f;\n"
17531                "const unsigned       g;\n"
17532                "Const unsigned       h;",
17533                Alignment);
17534 
17535   // See PR46529
17536   FormatStyle BracedAlign = getLLVMStyle();
17537   BracedAlign.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17538   verifyFormat("const auto result{[]() {\n"
17539                "  const auto something = 1;\n"
17540                "  return 2;\n"
17541                "}};",
17542                BracedAlign);
17543   verifyFormat("int foo{[]() {\n"
17544                "  int bar{0};\n"
17545                "  return 0;\n"
17546                "}()};",
17547                BracedAlign);
17548   BracedAlign.Cpp11BracedListStyle = false;
17549   verifyFormat("const auto result{ []() {\n"
17550                "  const auto something = 1;\n"
17551                "  return 2;\n"
17552                "} };",
17553                BracedAlign);
17554   verifyFormat("int foo{ []() {\n"
17555                "  int bar{ 0 };\n"
17556                "  return 0;\n"
17557                "}() };",
17558                BracedAlign);
17559 }
17560 
17561 TEST_F(FormatTest, AlignWithLineBreaks) {
17562   auto Style = getLLVMStyleWithColumns(120);
17563 
17564   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
17565   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
17566   verifyFormat("void foo() {\n"
17567                "  int myVar = 5;\n"
17568                "  double x = 3.14;\n"
17569                "  auto str = \"Hello \"\n"
17570                "             \"World\";\n"
17571                "  auto s = \"Hello \"\n"
17572                "           \"Again\";\n"
17573                "}",
17574                Style);
17575 
17576   // clang-format off
17577   verifyFormat("void foo() {\n"
17578                "  const int capacityBefore = Entries.capacity();\n"
17579                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17580                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17581                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17582                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17583                "}",
17584                Style);
17585   // clang-format on
17586 
17587   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17588   verifyFormat("void foo() {\n"
17589                "  int myVar = 5;\n"
17590                "  double x  = 3.14;\n"
17591                "  auto str  = \"Hello \"\n"
17592                "              \"World\";\n"
17593                "  auto s    = \"Hello \"\n"
17594                "              \"Again\";\n"
17595                "}",
17596                Style);
17597 
17598   // clang-format off
17599   verifyFormat("void foo() {\n"
17600                "  const int capacityBefore = Entries.capacity();\n"
17601                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17602                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17603                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17604                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17605                "}",
17606                Style);
17607   // clang-format on
17608 
17609   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17610   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17611   verifyFormat("void foo() {\n"
17612                "  int    myVar = 5;\n"
17613                "  double x = 3.14;\n"
17614                "  auto   str = \"Hello \"\n"
17615                "               \"World\";\n"
17616                "  auto   s = \"Hello \"\n"
17617                "             \"Again\";\n"
17618                "}",
17619                Style);
17620 
17621   // clang-format off
17622   verifyFormat("void foo() {\n"
17623                "  const int  capacityBefore = Entries.capacity();\n"
17624                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17625                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17626                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17627                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17628                "}",
17629                Style);
17630   // clang-format on
17631 
17632   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17633   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17634 
17635   verifyFormat("void foo() {\n"
17636                "  int    myVar = 5;\n"
17637                "  double x     = 3.14;\n"
17638                "  auto   str   = \"Hello \"\n"
17639                "                 \"World\";\n"
17640                "  auto   s     = \"Hello \"\n"
17641                "                 \"Again\";\n"
17642                "}",
17643                Style);
17644 
17645   // clang-format off
17646   verifyFormat("void foo() {\n"
17647                "  const int  capacityBefore = Entries.capacity();\n"
17648                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17649                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17650                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
17651                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
17652                "}",
17653                Style);
17654   // clang-format on
17655 
17656   Style = getLLVMStyleWithColumns(120);
17657   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17658   Style.ContinuationIndentWidth = 4;
17659   Style.IndentWidth = 4;
17660 
17661   // clang-format off
17662   verifyFormat("void SomeFunc() {\n"
17663                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17664                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17665                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17666                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17667                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
17668                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17669                "}",
17670                Style);
17671   // clang-format on
17672 
17673   Style.BinPackArguments = false;
17674 
17675   // clang-format off
17676   verifyFormat("void SomeFunc() {\n"
17677                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
17678                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17679                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
17680                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17681                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
17682                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
17683                "}",
17684                Style);
17685   // clang-format on
17686 }
17687 
17688 TEST_F(FormatTest, AlignWithInitializerPeriods) {
17689   auto Style = getLLVMStyleWithColumns(60);
17690 
17691   verifyFormat("void foo1(void) {\n"
17692                "  BYTE p[1] = 1;\n"
17693                "  A B = {.one_foooooooooooooooo = 2,\n"
17694                "         .two_fooooooooooooo = 3,\n"
17695                "         .three_fooooooooooooo = 4};\n"
17696                "  BYTE payload = 2;\n"
17697                "}",
17698                Style);
17699 
17700   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17701   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
17702   verifyFormat("void foo2(void) {\n"
17703                "  BYTE p[1]    = 1;\n"
17704                "  A B          = {.one_foooooooooooooooo = 2,\n"
17705                "                  .two_fooooooooooooo    = 3,\n"
17706                "                  .three_fooooooooooooo  = 4};\n"
17707                "  BYTE payload = 2;\n"
17708                "}",
17709                Style);
17710 
17711   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
17712   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17713   verifyFormat("void foo3(void) {\n"
17714                "  BYTE p[1] = 1;\n"
17715                "  A    B = {.one_foooooooooooooooo = 2,\n"
17716                "            .two_fooooooooooooo = 3,\n"
17717                "            .three_fooooooooooooo = 4};\n"
17718                "  BYTE payload = 2;\n"
17719                "}",
17720                Style);
17721 
17722   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17723   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17724   verifyFormat("void foo4(void) {\n"
17725                "  BYTE p[1]    = 1;\n"
17726                "  A    B       = {.one_foooooooooooooooo = 2,\n"
17727                "                  .two_fooooooooooooo    = 3,\n"
17728                "                  .three_fooooooooooooo  = 4};\n"
17729                "  BYTE payload = 2;\n"
17730                "}",
17731                Style);
17732 }
17733 
17734 TEST_F(FormatTest, LinuxBraceBreaking) {
17735   FormatStyle LinuxBraceStyle = getLLVMStyle();
17736   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
17737   verifyFormat("namespace a\n"
17738                "{\n"
17739                "class A\n"
17740                "{\n"
17741                "  void f()\n"
17742                "  {\n"
17743                "    if (true) {\n"
17744                "      a();\n"
17745                "      b();\n"
17746                "    } else {\n"
17747                "      a();\n"
17748                "    }\n"
17749                "  }\n"
17750                "  void g() { return; }\n"
17751                "};\n"
17752                "struct B {\n"
17753                "  int x;\n"
17754                "};\n"
17755                "} // namespace a\n",
17756                LinuxBraceStyle);
17757   verifyFormat("enum X {\n"
17758                "  Y = 0,\n"
17759                "}\n",
17760                LinuxBraceStyle);
17761   verifyFormat("struct S {\n"
17762                "  int Type;\n"
17763                "  union {\n"
17764                "    int x;\n"
17765                "    double y;\n"
17766                "  } Value;\n"
17767                "  class C\n"
17768                "  {\n"
17769                "    MyFavoriteType Value;\n"
17770                "  } Class;\n"
17771                "}\n",
17772                LinuxBraceStyle);
17773 }
17774 
17775 TEST_F(FormatTest, MozillaBraceBreaking) {
17776   FormatStyle MozillaBraceStyle = getLLVMStyle();
17777   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
17778   MozillaBraceStyle.FixNamespaceComments = false;
17779   verifyFormat("namespace a {\n"
17780                "class A\n"
17781                "{\n"
17782                "  void f()\n"
17783                "  {\n"
17784                "    if (true) {\n"
17785                "      a();\n"
17786                "      b();\n"
17787                "    }\n"
17788                "  }\n"
17789                "  void g() { return; }\n"
17790                "};\n"
17791                "enum E\n"
17792                "{\n"
17793                "  A,\n"
17794                "  // foo\n"
17795                "  B,\n"
17796                "  C\n"
17797                "};\n"
17798                "struct B\n"
17799                "{\n"
17800                "  int x;\n"
17801                "};\n"
17802                "}\n",
17803                MozillaBraceStyle);
17804   verifyFormat("struct S\n"
17805                "{\n"
17806                "  int Type;\n"
17807                "  union\n"
17808                "  {\n"
17809                "    int x;\n"
17810                "    double y;\n"
17811                "  } Value;\n"
17812                "  class C\n"
17813                "  {\n"
17814                "    MyFavoriteType Value;\n"
17815                "  } Class;\n"
17816                "}\n",
17817                MozillaBraceStyle);
17818 }
17819 
17820 TEST_F(FormatTest, StroustrupBraceBreaking) {
17821   FormatStyle StroustrupBraceStyle = getLLVMStyle();
17822   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
17823   verifyFormat("namespace a {\n"
17824                "class A {\n"
17825                "  void f()\n"
17826                "  {\n"
17827                "    if (true) {\n"
17828                "      a();\n"
17829                "      b();\n"
17830                "    }\n"
17831                "  }\n"
17832                "  void g() { return; }\n"
17833                "};\n"
17834                "struct B {\n"
17835                "  int x;\n"
17836                "};\n"
17837                "} // namespace a\n",
17838                StroustrupBraceStyle);
17839 
17840   verifyFormat("void foo()\n"
17841                "{\n"
17842                "  if (a) {\n"
17843                "    a();\n"
17844                "  }\n"
17845                "  else {\n"
17846                "    b();\n"
17847                "  }\n"
17848                "}\n",
17849                StroustrupBraceStyle);
17850 
17851   verifyFormat("#ifdef _DEBUG\n"
17852                "int foo(int i = 0)\n"
17853                "#else\n"
17854                "int foo(int i = 5)\n"
17855                "#endif\n"
17856                "{\n"
17857                "  return i;\n"
17858                "}",
17859                StroustrupBraceStyle);
17860 
17861   verifyFormat("void foo() {}\n"
17862                "void bar()\n"
17863                "#ifdef _DEBUG\n"
17864                "{\n"
17865                "  foo();\n"
17866                "}\n"
17867                "#else\n"
17868                "{\n"
17869                "}\n"
17870                "#endif",
17871                StroustrupBraceStyle);
17872 
17873   verifyFormat("void foobar() { int i = 5; }\n"
17874                "#ifdef _DEBUG\n"
17875                "void bar() {}\n"
17876                "#else\n"
17877                "void bar() { foobar(); }\n"
17878                "#endif",
17879                StroustrupBraceStyle);
17880 }
17881 
17882 TEST_F(FormatTest, AllmanBraceBreaking) {
17883   FormatStyle AllmanBraceStyle = getLLVMStyle();
17884   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
17885 
17886   EXPECT_EQ("namespace a\n"
17887             "{\n"
17888             "void f();\n"
17889             "void g();\n"
17890             "} // namespace a\n",
17891             format("namespace a\n"
17892                    "{\n"
17893                    "void f();\n"
17894                    "void g();\n"
17895                    "}\n",
17896                    AllmanBraceStyle));
17897 
17898   verifyFormat("namespace a\n"
17899                "{\n"
17900                "class A\n"
17901                "{\n"
17902                "  void f()\n"
17903                "  {\n"
17904                "    if (true)\n"
17905                "    {\n"
17906                "      a();\n"
17907                "      b();\n"
17908                "    }\n"
17909                "  }\n"
17910                "  void g() { return; }\n"
17911                "};\n"
17912                "struct B\n"
17913                "{\n"
17914                "  int x;\n"
17915                "};\n"
17916                "union C\n"
17917                "{\n"
17918                "};\n"
17919                "} // namespace a",
17920                AllmanBraceStyle);
17921 
17922   verifyFormat("void f()\n"
17923                "{\n"
17924                "  if (true)\n"
17925                "  {\n"
17926                "    a();\n"
17927                "  }\n"
17928                "  else if (false)\n"
17929                "  {\n"
17930                "    b();\n"
17931                "  }\n"
17932                "  else\n"
17933                "  {\n"
17934                "    c();\n"
17935                "  }\n"
17936                "}\n",
17937                AllmanBraceStyle);
17938 
17939   verifyFormat("void f()\n"
17940                "{\n"
17941                "  for (int i = 0; i < 10; ++i)\n"
17942                "  {\n"
17943                "    a();\n"
17944                "  }\n"
17945                "  while (false)\n"
17946                "  {\n"
17947                "    b();\n"
17948                "  }\n"
17949                "  do\n"
17950                "  {\n"
17951                "    c();\n"
17952                "  } while (false)\n"
17953                "}\n",
17954                AllmanBraceStyle);
17955 
17956   verifyFormat("void f(int a)\n"
17957                "{\n"
17958                "  switch (a)\n"
17959                "  {\n"
17960                "  case 0:\n"
17961                "    break;\n"
17962                "  case 1:\n"
17963                "  {\n"
17964                "    break;\n"
17965                "  }\n"
17966                "  case 2:\n"
17967                "  {\n"
17968                "  }\n"
17969                "  break;\n"
17970                "  default:\n"
17971                "    break;\n"
17972                "  }\n"
17973                "}\n",
17974                AllmanBraceStyle);
17975 
17976   verifyFormat("enum X\n"
17977                "{\n"
17978                "  Y = 0,\n"
17979                "}\n",
17980                AllmanBraceStyle);
17981   verifyFormat("enum X\n"
17982                "{\n"
17983                "  Y = 0\n"
17984                "}\n",
17985                AllmanBraceStyle);
17986 
17987   verifyFormat("@interface BSApplicationController ()\n"
17988                "{\n"
17989                "@private\n"
17990                "  id _extraIvar;\n"
17991                "}\n"
17992                "@end\n",
17993                AllmanBraceStyle);
17994 
17995   verifyFormat("#ifdef _DEBUG\n"
17996                "int foo(int i = 0)\n"
17997                "#else\n"
17998                "int foo(int i = 5)\n"
17999                "#endif\n"
18000                "{\n"
18001                "  return i;\n"
18002                "}",
18003                AllmanBraceStyle);
18004 
18005   verifyFormat("void foo() {}\n"
18006                "void bar()\n"
18007                "#ifdef _DEBUG\n"
18008                "{\n"
18009                "  foo();\n"
18010                "}\n"
18011                "#else\n"
18012                "{\n"
18013                "}\n"
18014                "#endif",
18015                AllmanBraceStyle);
18016 
18017   verifyFormat("void foobar() { int i = 5; }\n"
18018                "#ifdef _DEBUG\n"
18019                "void bar() {}\n"
18020                "#else\n"
18021                "void bar() { foobar(); }\n"
18022                "#endif",
18023                AllmanBraceStyle);
18024 
18025   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18026             FormatStyle::SLS_All);
18027 
18028   verifyFormat("[](int i) { return i + 2; };\n"
18029                "[](int i, int j)\n"
18030                "{\n"
18031                "  auto x = i + j;\n"
18032                "  auto y = i * j;\n"
18033                "  return x ^ y;\n"
18034                "};\n"
18035                "void foo()\n"
18036                "{\n"
18037                "  auto shortLambda = [](int i) { return i + 2; };\n"
18038                "  auto longLambda = [](int i, int j)\n"
18039                "  {\n"
18040                "    auto x = i + j;\n"
18041                "    auto y = i * j;\n"
18042                "    return x ^ y;\n"
18043                "  };\n"
18044                "}",
18045                AllmanBraceStyle);
18046 
18047   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18048 
18049   verifyFormat("[](int i)\n"
18050                "{\n"
18051                "  return i + 2;\n"
18052                "};\n"
18053                "[](int i, int j)\n"
18054                "{\n"
18055                "  auto x = i + j;\n"
18056                "  auto y = i * j;\n"
18057                "  return x ^ y;\n"
18058                "};\n"
18059                "void foo()\n"
18060                "{\n"
18061                "  auto shortLambda = [](int i)\n"
18062                "  {\n"
18063                "    return i + 2;\n"
18064                "  };\n"
18065                "  auto longLambda = [](int i, int j)\n"
18066                "  {\n"
18067                "    auto x = i + j;\n"
18068                "    auto y = i * j;\n"
18069                "    return x ^ y;\n"
18070                "  };\n"
18071                "}",
18072                AllmanBraceStyle);
18073 
18074   // Reset
18075   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18076 
18077   // This shouldn't affect ObjC blocks..
18078   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18079                "  // ...\n"
18080                "  int i;\n"
18081                "}];",
18082                AllmanBraceStyle);
18083   verifyFormat("void (^block)(void) = ^{\n"
18084                "  // ...\n"
18085                "  int i;\n"
18086                "};",
18087                AllmanBraceStyle);
18088   // .. or dict literals.
18089   verifyFormat("void f()\n"
18090                "{\n"
18091                "  // ...\n"
18092                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18093                "}",
18094                AllmanBraceStyle);
18095   verifyFormat("void f()\n"
18096                "{\n"
18097                "  // ...\n"
18098                "  [object someMethod:@{a : @\"b\"}];\n"
18099                "}",
18100                AllmanBraceStyle);
18101   verifyFormat("int f()\n"
18102                "{ // comment\n"
18103                "  return 42;\n"
18104                "}",
18105                AllmanBraceStyle);
18106 
18107   AllmanBraceStyle.ColumnLimit = 19;
18108   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18109   AllmanBraceStyle.ColumnLimit = 18;
18110   verifyFormat("void f()\n"
18111                "{\n"
18112                "  int i;\n"
18113                "}",
18114                AllmanBraceStyle);
18115   AllmanBraceStyle.ColumnLimit = 80;
18116 
18117   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18118   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18119       FormatStyle::SIS_WithoutElse;
18120   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18121   verifyFormat("void f(bool b)\n"
18122                "{\n"
18123                "  if (b)\n"
18124                "  {\n"
18125                "    return;\n"
18126                "  }\n"
18127                "}\n",
18128                BreakBeforeBraceShortIfs);
18129   verifyFormat("void f(bool b)\n"
18130                "{\n"
18131                "  if constexpr (b)\n"
18132                "  {\n"
18133                "    return;\n"
18134                "  }\n"
18135                "}\n",
18136                BreakBeforeBraceShortIfs);
18137   verifyFormat("void f(bool b)\n"
18138                "{\n"
18139                "  if CONSTEXPR (b)\n"
18140                "  {\n"
18141                "    return;\n"
18142                "  }\n"
18143                "}\n",
18144                BreakBeforeBraceShortIfs);
18145   verifyFormat("void f(bool b)\n"
18146                "{\n"
18147                "  if (b) return;\n"
18148                "}\n",
18149                BreakBeforeBraceShortIfs);
18150   verifyFormat("void f(bool b)\n"
18151                "{\n"
18152                "  if constexpr (b) return;\n"
18153                "}\n",
18154                BreakBeforeBraceShortIfs);
18155   verifyFormat("void f(bool b)\n"
18156                "{\n"
18157                "  if CONSTEXPR (b) return;\n"
18158                "}\n",
18159                BreakBeforeBraceShortIfs);
18160   verifyFormat("void f(bool b)\n"
18161                "{\n"
18162                "  while (b)\n"
18163                "  {\n"
18164                "    return;\n"
18165                "  }\n"
18166                "}\n",
18167                BreakBeforeBraceShortIfs);
18168 }
18169 
18170 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18171   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18172   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18173 
18174   // Make a few changes to the style for testing purposes
18175   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18176       FormatStyle::SFS_Empty;
18177   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18178 
18179   // FIXME: this test case can't decide whether there should be a blank line
18180   // after the ~D() line or not. It adds one if one doesn't exist in the test
18181   // and it removes the line if one exists.
18182   /*
18183   verifyFormat("class A;\n"
18184                "namespace B\n"
18185                "  {\n"
18186                "class C;\n"
18187                "// Comment\n"
18188                "class D\n"
18189                "  {\n"
18190                "public:\n"
18191                "  D();\n"
18192                "  ~D() {}\n"
18193                "private:\n"
18194                "  enum E\n"
18195                "    {\n"
18196                "    F\n"
18197                "    }\n"
18198                "  };\n"
18199                "  } // namespace B\n",
18200                WhitesmithsBraceStyle);
18201   */
18202 
18203   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18204   verifyFormat("namespace a\n"
18205                "  {\n"
18206                "class A\n"
18207                "  {\n"
18208                "  void f()\n"
18209                "    {\n"
18210                "    if (true)\n"
18211                "      {\n"
18212                "      a();\n"
18213                "      b();\n"
18214                "      }\n"
18215                "    }\n"
18216                "  void g()\n"
18217                "    {\n"
18218                "    return;\n"
18219                "    }\n"
18220                "  };\n"
18221                "struct B\n"
18222                "  {\n"
18223                "  int x;\n"
18224                "  };\n"
18225                "  } // namespace a",
18226                WhitesmithsBraceStyle);
18227 
18228   verifyFormat("namespace a\n"
18229                "  {\n"
18230                "namespace b\n"
18231                "  {\n"
18232                "class A\n"
18233                "  {\n"
18234                "  void f()\n"
18235                "    {\n"
18236                "    if (true)\n"
18237                "      {\n"
18238                "      a();\n"
18239                "      b();\n"
18240                "      }\n"
18241                "    }\n"
18242                "  void g()\n"
18243                "    {\n"
18244                "    return;\n"
18245                "    }\n"
18246                "  };\n"
18247                "struct B\n"
18248                "  {\n"
18249                "  int x;\n"
18250                "  };\n"
18251                "  } // namespace b\n"
18252                "  } // namespace a",
18253                WhitesmithsBraceStyle);
18254 
18255   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18256   verifyFormat("namespace a\n"
18257                "  {\n"
18258                "namespace b\n"
18259                "  {\n"
18260                "  class A\n"
18261                "    {\n"
18262                "    void f()\n"
18263                "      {\n"
18264                "      if (true)\n"
18265                "        {\n"
18266                "        a();\n"
18267                "        b();\n"
18268                "        }\n"
18269                "      }\n"
18270                "    void g()\n"
18271                "      {\n"
18272                "      return;\n"
18273                "      }\n"
18274                "    };\n"
18275                "  struct B\n"
18276                "    {\n"
18277                "    int x;\n"
18278                "    };\n"
18279                "  } // namespace b\n"
18280                "  } // namespace a",
18281                WhitesmithsBraceStyle);
18282 
18283   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18284   verifyFormat("namespace a\n"
18285                "  {\n"
18286                "  namespace b\n"
18287                "    {\n"
18288                "    class A\n"
18289                "      {\n"
18290                "      void f()\n"
18291                "        {\n"
18292                "        if (true)\n"
18293                "          {\n"
18294                "          a();\n"
18295                "          b();\n"
18296                "          }\n"
18297                "        }\n"
18298                "      void g()\n"
18299                "        {\n"
18300                "        return;\n"
18301                "        }\n"
18302                "      };\n"
18303                "    struct B\n"
18304                "      {\n"
18305                "      int x;\n"
18306                "      };\n"
18307                "    } // namespace b\n"
18308                "  }   // namespace a",
18309                WhitesmithsBraceStyle);
18310 
18311   verifyFormat("void f()\n"
18312                "  {\n"
18313                "  if (true)\n"
18314                "    {\n"
18315                "    a();\n"
18316                "    }\n"
18317                "  else if (false)\n"
18318                "    {\n"
18319                "    b();\n"
18320                "    }\n"
18321                "  else\n"
18322                "    {\n"
18323                "    c();\n"
18324                "    }\n"
18325                "  }\n",
18326                WhitesmithsBraceStyle);
18327 
18328   verifyFormat("void f()\n"
18329                "  {\n"
18330                "  for (int i = 0; i < 10; ++i)\n"
18331                "    {\n"
18332                "    a();\n"
18333                "    }\n"
18334                "  while (false)\n"
18335                "    {\n"
18336                "    b();\n"
18337                "    }\n"
18338                "  do\n"
18339                "    {\n"
18340                "    c();\n"
18341                "    } while (false)\n"
18342                "  }\n",
18343                WhitesmithsBraceStyle);
18344 
18345   WhitesmithsBraceStyle.IndentCaseLabels = true;
18346   verifyFormat("void switchTest1(int a)\n"
18347                "  {\n"
18348                "  switch (a)\n"
18349                "    {\n"
18350                "    case 2:\n"
18351                "      {\n"
18352                "      }\n"
18353                "      break;\n"
18354                "    }\n"
18355                "  }\n",
18356                WhitesmithsBraceStyle);
18357 
18358   verifyFormat("void switchTest2(int a)\n"
18359                "  {\n"
18360                "  switch (a)\n"
18361                "    {\n"
18362                "    case 0:\n"
18363                "      break;\n"
18364                "    case 1:\n"
18365                "      {\n"
18366                "      break;\n"
18367                "      }\n"
18368                "    case 2:\n"
18369                "      {\n"
18370                "      }\n"
18371                "      break;\n"
18372                "    default:\n"
18373                "      break;\n"
18374                "    }\n"
18375                "  }\n",
18376                WhitesmithsBraceStyle);
18377 
18378   verifyFormat("void switchTest3(int a)\n"
18379                "  {\n"
18380                "  switch (a)\n"
18381                "    {\n"
18382                "    case 0:\n"
18383                "      {\n"
18384                "      foo(x);\n"
18385                "      }\n"
18386                "      break;\n"
18387                "    default:\n"
18388                "      {\n"
18389                "      foo(1);\n"
18390                "      }\n"
18391                "      break;\n"
18392                "    }\n"
18393                "  }\n",
18394                WhitesmithsBraceStyle);
18395 
18396   WhitesmithsBraceStyle.IndentCaseLabels = false;
18397 
18398   verifyFormat("void switchTest4(int a)\n"
18399                "  {\n"
18400                "  switch (a)\n"
18401                "    {\n"
18402                "  case 2:\n"
18403                "    {\n"
18404                "    }\n"
18405                "    break;\n"
18406                "    }\n"
18407                "  }\n",
18408                WhitesmithsBraceStyle);
18409 
18410   verifyFormat("void switchTest5(int a)\n"
18411                "  {\n"
18412                "  switch (a)\n"
18413                "    {\n"
18414                "  case 0:\n"
18415                "    break;\n"
18416                "  case 1:\n"
18417                "    {\n"
18418                "    foo();\n"
18419                "    break;\n"
18420                "    }\n"
18421                "  case 2:\n"
18422                "    {\n"
18423                "    }\n"
18424                "    break;\n"
18425                "  default:\n"
18426                "    break;\n"
18427                "    }\n"
18428                "  }\n",
18429                WhitesmithsBraceStyle);
18430 
18431   verifyFormat("void switchTest6(int a)\n"
18432                "  {\n"
18433                "  switch (a)\n"
18434                "    {\n"
18435                "  case 0:\n"
18436                "    {\n"
18437                "    foo(x);\n"
18438                "    }\n"
18439                "    break;\n"
18440                "  default:\n"
18441                "    {\n"
18442                "    foo(1);\n"
18443                "    }\n"
18444                "    break;\n"
18445                "    }\n"
18446                "  }\n",
18447                WhitesmithsBraceStyle);
18448 
18449   verifyFormat("enum X\n"
18450                "  {\n"
18451                "  Y = 0, // testing\n"
18452                "  }\n",
18453                WhitesmithsBraceStyle);
18454 
18455   verifyFormat("enum X\n"
18456                "  {\n"
18457                "  Y = 0\n"
18458                "  }\n",
18459                WhitesmithsBraceStyle);
18460   verifyFormat("enum X\n"
18461                "  {\n"
18462                "  Y = 0,\n"
18463                "  Z = 1\n"
18464                "  };\n",
18465                WhitesmithsBraceStyle);
18466 
18467   verifyFormat("@interface BSApplicationController ()\n"
18468                "  {\n"
18469                "@private\n"
18470                "  id _extraIvar;\n"
18471                "  }\n"
18472                "@end\n",
18473                WhitesmithsBraceStyle);
18474 
18475   verifyFormat("#ifdef _DEBUG\n"
18476                "int foo(int i = 0)\n"
18477                "#else\n"
18478                "int foo(int i = 5)\n"
18479                "#endif\n"
18480                "  {\n"
18481                "  return i;\n"
18482                "  }",
18483                WhitesmithsBraceStyle);
18484 
18485   verifyFormat("void foo() {}\n"
18486                "void bar()\n"
18487                "#ifdef _DEBUG\n"
18488                "  {\n"
18489                "  foo();\n"
18490                "  }\n"
18491                "#else\n"
18492                "  {\n"
18493                "  }\n"
18494                "#endif",
18495                WhitesmithsBraceStyle);
18496 
18497   verifyFormat("void foobar()\n"
18498                "  {\n"
18499                "  int i = 5;\n"
18500                "  }\n"
18501                "#ifdef _DEBUG\n"
18502                "void bar()\n"
18503                "  {\n"
18504                "  }\n"
18505                "#else\n"
18506                "void bar()\n"
18507                "  {\n"
18508                "  foobar();\n"
18509                "  }\n"
18510                "#endif",
18511                WhitesmithsBraceStyle);
18512 
18513   // This shouldn't affect ObjC blocks..
18514   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18515                "  // ...\n"
18516                "  int i;\n"
18517                "}];",
18518                WhitesmithsBraceStyle);
18519   verifyFormat("void (^block)(void) = ^{\n"
18520                "  // ...\n"
18521                "  int i;\n"
18522                "};",
18523                WhitesmithsBraceStyle);
18524   // .. or dict literals.
18525   verifyFormat("void f()\n"
18526                "  {\n"
18527                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18528                "  }",
18529                WhitesmithsBraceStyle);
18530 
18531   verifyFormat("int f()\n"
18532                "  { // comment\n"
18533                "  return 42;\n"
18534                "  }",
18535                WhitesmithsBraceStyle);
18536 
18537   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
18538   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18539       FormatStyle::SIS_OnlyFirstIf;
18540   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18541   verifyFormat("void f(bool b)\n"
18542                "  {\n"
18543                "  if (b)\n"
18544                "    {\n"
18545                "    return;\n"
18546                "    }\n"
18547                "  }\n",
18548                BreakBeforeBraceShortIfs);
18549   verifyFormat("void f(bool b)\n"
18550                "  {\n"
18551                "  if (b) return;\n"
18552                "  }\n",
18553                BreakBeforeBraceShortIfs);
18554   verifyFormat("void f(bool b)\n"
18555                "  {\n"
18556                "  while (b)\n"
18557                "    {\n"
18558                "    return;\n"
18559                "    }\n"
18560                "  }\n",
18561                BreakBeforeBraceShortIfs);
18562 }
18563 
18564 TEST_F(FormatTest, GNUBraceBreaking) {
18565   FormatStyle GNUBraceStyle = getLLVMStyle();
18566   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
18567   verifyFormat("namespace a\n"
18568                "{\n"
18569                "class A\n"
18570                "{\n"
18571                "  void f()\n"
18572                "  {\n"
18573                "    int a;\n"
18574                "    {\n"
18575                "      int b;\n"
18576                "    }\n"
18577                "    if (true)\n"
18578                "      {\n"
18579                "        a();\n"
18580                "        b();\n"
18581                "      }\n"
18582                "  }\n"
18583                "  void g() { return; }\n"
18584                "}\n"
18585                "} // namespace a",
18586                GNUBraceStyle);
18587 
18588   verifyFormat("void f()\n"
18589                "{\n"
18590                "  if (true)\n"
18591                "    {\n"
18592                "      a();\n"
18593                "    }\n"
18594                "  else if (false)\n"
18595                "    {\n"
18596                "      b();\n"
18597                "    }\n"
18598                "  else\n"
18599                "    {\n"
18600                "      c();\n"
18601                "    }\n"
18602                "}\n",
18603                GNUBraceStyle);
18604 
18605   verifyFormat("void f()\n"
18606                "{\n"
18607                "  for (int i = 0; i < 10; ++i)\n"
18608                "    {\n"
18609                "      a();\n"
18610                "    }\n"
18611                "  while (false)\n"
18612                "    {\n"
18613                "      b();\n"
18614                "    }\n"
18615                "  do\n"
18616                "    {\n"
18617                "      c();\n"
18618                "    }\n"
18619                "  while (false);\n"
18620                "}\n",
18621                GNUBraceStyle);
18622 
18623   verifyFormat("void f(int a)\n"
18624                "{\n"
18625                "  switch (a)\n"
18626                "    {\n"
18627                "    case 0:\n"
18628                "      break;\n"
18629                "    case 1:\n"
18630                "      {\n"
18631                "        break;\n"
18632                "      }\n"
18633                "    case 2:\n"
18634                "      {\n"
18635                "      }\n"
18636                "      break;\n"
18637                "    default:\n"
18638                "      break;\n"
18639                "    }\n"
18640                "}\n",
18641                GNUBraceStyle);
18642 
18643   verifyFormat("enum X\n"
18644                "{\n"
18645                "  Y = 0,\n"
18646                "}\n",
18647                GNUBraceStyle);
18648 
18649   verifyFormat("@interface BSApplicationController ()\n"
18650                "{\n"
18651                "@private\n"
18652                "  id _extraIvar;\n"
18653                "}\n"
18654                "@end\n",
18655                GNUBraceStyle);
18656 
18657   verifyFormat("#ifdef _DEBUG\n"
18658                "int foo(int i = 0)\n"
18659                "#else\n"
18660                "int foo(int i = 5)\n"
18661                "#endif\n"
18662                "{\n"
18663                "  return i;\n"
18664                "}",
18665                GNUBraceStyle);
18666 
18667   verifyFormat("void foo() {}\n"
18668                "void bar()\n"
18669                "#ifdef _DEBUG\n"
18670                "{\n"
18671                "  foo();\n"
18672                "}\n"
18673                "#else\n"
18674                "{\n"
18675                "}\n"
18676                "#endif",
18677                GNUBraceStyle);
18678 
18679   verifyFormat("void foobar() { int i = 5; }\n"
18680                "#ifdef _DEBUG\n"
18681                "void bar() {}\n"
18682                "#else\n"
18683                "void bar() { foobar(); }\n"
18684                "#endif",
18685                GNUBraceStyle);
18686 }
18687 
18688 TEST_F(FormatTest, WebKitBraceBreaking) {
18689   FormatStyle WebKitBraceStyle = getLLVMStyle();
18690   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
18691   WebKitBraceStyle.FixNamespaceComments = false;
18692   verifyFormat("namespace a {\n"
18693                "class A {\n"
18694                "  void f()\n"
18695                "  {\n"
18696                "    if (true) {\n"
18697                "      a();\n"
18698                "      b();\n"
18699                "    }\n"
18700                "  }\n"
18701                "  void g() { return; }\n"
18702                "};\n"
18703                "enum E {\n"
18704                "  A,\n"
18705                "  // foo\n"
18706                "  B,\n"
18707                "  C\n"
18708                "};\n"
18709                "struct B {\n"
18710                "  int x;\n"
18711                "};\n"
18712                "}\n",
18713                WebKitBraceStyle);
18714   verifyFormat("struct S {\n"
18715                "  int Type;\n"
18716                "  union {\n"
18717                "    int x;\n"
18718                "    double y;\n"
18719                "  } Value;\n"
18720                "  class C {\n"
18721                "    MyFavoriteType Value;\n"
18722                "  } Class;\n"
18723                "};\n",
18724                WebKitBraceStyle);
18725 }
18726 
18727 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
18728   verifyFormat("void f() {\n"
18729                "  try {\n"
18730                "  } catch (const Exception &e) {\n"
18731                "  }\n"
18732                "}\n",
18733                getLLVMStyle());
18734 }
18735 
18736 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
18737   auto Style = getLLVMStyle();
18738   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18739   Style.AlignConsecutiveAssignments =
18740       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18741   Style.AlignConsecutiveDeclarations =
18742       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18743   verifyFormat("struct test demo[] = {\n"
18744                "    {56,    23, \"hello\"},\n"
18745                "    {-1, 93463, \"world\"},\n"
18746                "    { 7,     5,    \"!!\"}\n"
18747                "};\n",
18748                Style);
18749 
18750   verifyFormat("struct test demo[] = {\n"
18751                "    {56,    23, \"hello\"}, // first line\n"
18752                "    {-1, 93463, \"world\"}, // second line\n"
18753                "    { 7,     5,    \"!!\"}  // third line\n"
18754                "};\n",
18755                Style);
18756 
18757   verifyFormat("struct test demo[4] = {\n"
18758                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18759                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18760                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18761                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18762                "};\n",
18763                Style);
18764 
18765   verifyFormat("struct test demo[3] = {\n"
18766                "    {56,    23, \"hello\"},\n"
18767                "    {-1, 93463, \"world\"},\n"
18768                "    { 7,     5,    \"!!\"}\n"
18769                "};\n",
18770                Style);
18771 
18772   verifyFormat("struct test demo[3] = {\n"
18773                "    {int{56},    23, \"hello\"},\n"
18774                "    {int{-1}, 93463, \"world\"},\n"
18775                "    { int{7},     5,    \"!!\"}\n"
18776                "};\n",
18777                Style);
18778 
18779   verifyFormat("struct test demo[] = {\n"
18780                "    {56,    23, \"hello\"},\n"
18781                "    {-1, 93463, \"world\"},\n"
18782                "    { 7,     5,    \"!!\"},\n"
18783                "};\n",
18784                Style);
18785 
18786   verifyFormat("test demo[] = {\n"
18787                "    {56,    23, \"hello\"},\n"
18788                "    {-1, 93463, \"world\"},\n"
18789                "    { 7,     5,    \"!!\"},\n"
18790                "};\n",
18791                Style);
18792 
18793   verifyFormat("demo = std::array<struct test, 3>{\n"
18794                "    test{56,    23, \"hello\"},\n"
18795                "    test{-1, 93463, \"world\"},\n"
18796                "    test{ 7,     5,    \"!!\"},\n"
18797                "};\n",
18798                Style);
18799 
18800   verifyFormat("test demo[] = {\n"
18801                "    {56,    23, \"hello\"},\n"
18802                "#if X\n"
18803                "    {-1, 93463, \"world\"},\n"
18804                "#endif\n"
18805                "    { 7,     5,    \"!!\"}\n"
18806                "};\n",
18807                Style);
18808 
18809   verifyFormat(
18810       "test demo[] = {\n"
18811       "    { 7,    23,\n"
18812       "     \"hello world i am a very long line that really, in any\"\n"
18813       "     \"just world, ought to be split over multiple lines\"},\n"
18814       "    {-1, 93463,                                  \"world\"},\n"
18815       "    {56,     5,                                     \"!!\"}\n"
18816       "};\n",
18817       Style);
18818 
18819   verifyFormat("return GradForUnaryCwise(g, {\n"
18820                "                                {{\"sign\"}, \"Sign\",  "
18821                "  {\"x\", \"dy\"}},\n"
18822                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
18823                ", \"sign\"}},\n"
18824                "});\n",
18825                Style);
18826 
18827   Style.ColumnLimit = 0;
18828   EXPECT_EQ(
18829       "test demo[] = {\n"
18830       "    {56,    23, \"hello world i am a very long line that really, "
18831       "in any just world, ought to be split over multiple lines\"},\n"
18832       "    {-1, 93463,                                                  "
18833       "                                                 \"world\"},\n"
18834       "    { 7,     5,                                                  "
18835       "                                                    \"!!\"},\n"
18836       "};",
18837       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18838              "that really, in any just world, ought to be split over multiple "
18839              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18840              Style));
18841 
18842   Style.ColumnLimit = 80;
18843   verifyFormat("test demo[] = {\n"
18844                "    {56,    23, /* a comment */ \"hello\"},\n"
18845                "    {-1, 93463,                 \"world\"},\n"
18846                "    { 7,     5,                    \"!!\"}\n"
18847                "};\n",
18848                Style);
18849 
18850   verifyFormat("test demo[] = {\n"
18851                "    {56,    23,                    \"hello\"},\n"
18852                "    {-1, 93463, \"world\" /* comment here */},\n"
18853                "    { 7,     5,                       \"!!\"}\n"
18854                "};\n",
18855                Style);
18856 
18857   verifyFormat("test demo[] = {\n"
18858                "    {56, /* a comment */ 23, \"hello\"},\n"
18859                "    {-1,              93463, \"world\"},\n"
18860                "    { 7,                  5,    \"!!\"}\n"
18861                "};\n",
18862                Style);
18863 
18864   Style.ColumnLimit = 20;
18865   EXPECT_EQ(
18866       "demo = std::array<\n"
18867       "    struct test, 3>{\n"
18868       "    test{\n"
18869       "         56,    23,\n"
18870       "         \"hello \"\n"
18871       "         \"world i \"\n"
18872       "         \"am a very \"\n"
18873       "         \"long line \"\n"
18874       "         \"that \"\n"
18875       "         \"really, \"\n"
18876       "         \"in any \"\n"
18877       "         \"just \"\n"
18878       "         \"world, \"\n"
18879       "         \"ought to \"\n"
18880       "         \"be split \"\n"
18881       "         \"over \"\n"
18882       "         \"multiple \"\n"
18883       "         \"lines\"},\n"
18884       "    test{-1, 93463,\n"
18885       "         \"world\"},\n"
18886       "    test{ 7,     5,\n"
18887       "         \"!!\"   },\n"
18888       "};",
18889       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18890              "i am a very long line that really, in any just world, ought "
18891              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18892              "test{7, 5, \"!!\"},};",
18893              Style));
18894   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18895   Style = getLLVMStyleWithColumns(50);
18896   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18897   verifyFormat("static A x = {\n"
18898                "    {{init1, init2, init3, init4},\n"
18899                "     {init1, init2, init3, init4}}\n"
18900                "};",
18901                Style);
18902   Style.ColumnLimit = 100;
18903   EXPECT_EQ(
18904       "test demo[] = {\n"
18905       "    {56,    23,\n"
18906       "     \"hello world i am a very long line that really, in any just world"
18907       ", ought to be split over \"\n"
18908       "     \"multiple lines\"  },\n"
18909       "    {-1, 93463, \"world\"},\n"
18910       "    { 7,     5,    \"!!\"},\n"
18911       "};",
18912       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18913              "that really, in any just world, ought to be split over multiple "
18914              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18915              Style));
18916 
18917   Style = getLLVMStyleWithColumns(50);
18918   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18919   Style.AlignConsecutiveAssignments =
18920       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18921   Style.AlignConsecutiveDeclarations =
18922       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18923   verifyFormat("struct test demo[] = {\n"
18924                "    {56,    23, \"hello\"},\n"
18925                "    {-1, 93463, \"world\"},\n"
18926                "    { 7,     5,    \"!!\"}\n"
18927                "};\n"
18928                "static A x = {\n"
18929                "    {{init1, init2, init3, init4},\n"
18930                "     {init1, init2, init3, init4}}\n"
18931                "};",
18932                Style);
18933   Style.ColumnLimit = 100;
18934   Style.AlignConsecutiveAssignments =
18935       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18936   Style.AlignConsecutiveDeclarations =
18937       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18938   verifyFormat("struct test demo[] = {\n"
18939                "    {56,    23, \"hello\"},\n"
18940                "    {-1, 93463, \"world\"},\n"
18941                "    { 7,     5,    \"!!\"}\n"
18942                "};\n"
18943                "struct test demo[4] = {\n"
18944                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18945                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18946                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18947                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18948                "};\n",
18949                Style);
18950   EXPECT_EQ(
18951       "test demo[] = {\n"
18952       "    {56,\n"
18953       "     \"hello world i am a very long line that really, in any just world"
18954       ", ought to be split over \"\n"
18955       "     \"multiple lines\",    23},\n"
18956       "    {-1,      \"world\", 93463},\n"
18957       "    { 7,         \"!!\",     5},\n"
18958       "};",
18959       format("test demo[] = {{56, \"hello world i am a very long line "
18960              "that really, in any just world, ought to be split over multiple "
18961              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
18962              Style));
18963 }
18964 
18965 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
18966   auto Style = getLLVMStyle();
18967   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18968   /* FIXME: This case gets misformatted.
18969   verifyFormat("auto foo = Items{\n"
18970                "    Section{0, bar(), },\n"
18971                "    Section{1, boo()  }\n"
18972                "};\n",
18973                Style);
18974   */
18975   verifyFormat("auto foo = Items{\n"
18976                "    Section{\n"
18977                "            0, bar(),\n"
18978                "            }\n"
18979                "};\n",
18980                Style);
18981   verifyFormat("struct test demo[] = {\n"
18982                "    {56, 23,    \"hello\"},\n"
18983                "    {-1, 93463, \"world\"},\n"
18984                "    {7,  5,     \"!!\"   }\n"
18985                "};\n",
18986                Style);
18987   verifyFormat("struct test demo[] = {\n"
18988                "    {56, 23,    \"hello\"}, // first line\n"
18989                "    {-1, 93463, \"world\"}, // second line\n"
18990                "    {7,  5,     \"!!\"   }  // third line\n"
18991                "};\n",
18992                Style);
18993   verifyFormat("struct test demo[4] = {\n"
18994                "    {56,  23,    21, \"oh\"      }, // first line\n"
18995                "    {-1,  93463, 22, \"my\"      }, // second line\n"
18996                "    {7,   5,     1,  \"goodness\"}  // third line\n"
18997                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
18998                "};\n",
18999                Style);
19000   verifyFormat("struct test demo[3] = {\n"
19001                "    {56, 23,    \"hello\"},\n"
19002                "    {-1, 93463, \"world\"},\n"
19003                "    {7,  5,     \"!!\"   }\n"
19004                "};\n",
19005                Style);
19006 
19007   verifyFormat("struct test demo[3] = {\n"
19008                "    {int{56}, 23,    \"hello\"},\n"
19009                "    {int{-1}, 93463, \"world\"},\n"
19010                "    {int{7},  5,     \"!!\"   }\n"
19011                "};\n",
19012                Style);
19013   verifyFormat("struct test demo[] = {\n"
19014                "    {56, 23,    \"hello\"},\n"
19015                "    {-1, 93463, \"world\"},\n"
19016                "    {7,  5,     \"!!\"   },\n"
19017                "};\n",
19018                Style);
19019   verifyFormat("test demo[] = {\n"
19020                "    {56, 23,    \"hello\"},\n"
19021                "    {-1, 93463, \"world\"},\n"
19022                "    {7,  5,     \"!!\"   },\n"
19023                "};\n",
19024                Style);
19025   verifyFormat("demo = std::array<struct test, 3>{\n"
19026                "    test{56, 23,    \"hello\"},\n"
19027                "    test{-1, 93463, \"world\"},\n"
19028                "    test{7,  5,     \"!!\"   },\n"
19029                "};\n",
19030                Style);
19031   verifyFormat("test demo[] = {\n"
19032                "    {56, 23,    \"hello\"},\n"
19033                "#if X\n"
19034                "    {-1, 93463, \"world\"},\n"
19035                "#endif\n"
19036                "    {7,  5,     \"!!\"   }\n"
19037                "};\n",
19038                Style);
19039   verifyFormat(
19040       "test demo[] = {\n"
19041       "    {7,  23,\n"
19042       "     \"hello world i am a very long line that really, in any\"\n"
19043       "     \"just world, ought to be split over multiple lines\"},\n"
19044       "    {-1, 93463, \"world\"                                 },\n"
19045       "    {56, 5,     \"!!\"                                    }\n"
19046       "};\n",
19047       Style);
19048 
19049   verifyFormat("return GradForUnaryCwise(g, {\n"
19050                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19051                "\"dy\"}   },\n"
19052                "                                {{\"dx\"},   \"Mul\",  "
19053                "{\"dy\", \"sign\"}},\n"
19054                "});\n",
19055                Style);
19056 
19057   Style.ColumnLimit = 0;
19058   EXPECT_EQ(
19059       "test demo[] = {\n"
19060       "    {56, 23,    \"hello world i am a very long line that really, in any "
19061       "just world, ought to be split over multiple lines\"},\n"
19062       "    {-1, 93463, \"world\"                                               "
19063       "                                                   },\n"
19064       "    {7,  5,     \"!!\"                                                  "
19065       "                                                   },\n"
19066       "};",
19067       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19068              "that really, in any just world, ought to be split over multiple "
19069              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19070              Style));
19071 
19072   Style.ColumnLimit = 80;
19073   verifyFormat("test demo[] = {\n"
19074                "    {56, 23,    /* a comment */ \"hello\"},\n"
19075                "    {-1, 93463, \"world\"                },\n"
19076                "    {7,  5,     \"!!\"                   }\n"
19077                "};\n",
19078                Style);
19079 
19080   verifyFormat("test demo[] = {\n"
19081                "    {56, 23,    \"hello\"                   },\n"
19082                "    {-1, 93463, \"world\" /* comment here */},\n"
19083                "    {7,  5,     \"!!\"                      }\n"
19084                "};\n",
19085                Style);
19086 
19087   verifyFormat("test demo[] = {\n"
19088                "    {56, /* a comment */ 23, \"hello\"},\n"
19089                "    {-1, 93463,              \"world\"},\n"
19090                "    {7,  5,                  \"!!\"   }\n"
19091                "};\n",
19092                Style);
19093 
19094   Style.ColumnLimit = 20;
19095   EXPECT_EQ(
19096       "demo = std::array<\n"
19097       "    struct test, 3>{\n"
19098       "    test{\n"
19099       "         56, 23,\n"
19100       "         \"hello \"\n"
19101       "         \"world i \"\n"
19102       "         \"am a very \"\n"
19103       "         \"long line \"\n"
19104       "         \"that \"\n"
19105       "         \"really, \"\n"
19106       "         \"in any \"\n"
19107       "         \"just \"\n"
19108       "         \"world, \"\n"
19109       "         \"ought to \"\n"
19110       "         \"be split \"\n"
19111       "         \"over \"\n"
19112       "         \"multiple \"\n"
19113       "         \"lines\"},\n"
19114       "    test{-1, 93463,\n"
19115       "         \"world\"},\n"
19116       "    test{7,  5,\n"
19117       "         \"!!\"   },\n"
19118       "};",
19119       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19120              "i am a very long line that really, in any just world, ought "
19121              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19122              "test{7, 5, \"!!\"},};",
19123              Style));
19124 
19125   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19126   Style = getLLVMStyleWithColumns(50);
19127   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19128   verifyFormat("static A x = {\n"
19129                "    {{init1, init2, init3, init4},\n"
19130                "     {init1, init2, init3, init4}}\n"
19131                "};",
19132                Style);
19133   Style.ColumnLimit = 100;
19134   EXPECT_EQ(
19135       "test demo[] = {\n"
19136       "    {56, 23,\n"
19137       "     \"hello world i am a very long line that really, in any just world"
19138       ", ought to be split over \"\n"
19139       "     \"multiple lines\"  },\n"
19140       "    {-1, 93463, \"world\"},\n"
19141       "    {7,  5,     \"!!\"   },\n"
19142       "};",
19143       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19144              "that really, in any just world, ought to be split over multiple "
19145              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19146              Style));
19147 }
19148 
19149 TEST_F(FormatTest, UnderstandsPragmas) {
19150   verifyFormat("#pragma omp reduction(| : var)");
19151   verifyFormat("#pragma omp reduction(+ : var)");
19152 
19153   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19154             "(including parentheses).",
19155             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19156                    "(including parentheses)."));
19157 }
19158 
19159 TEST_F(FormatTest, UnderstandPragmaOption) {
19160   verifyFormat("#pragma option -C -A");
19161 
19162   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19163 }
19164 
19165 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19166   FormatStyle Style = getLLVMStyleWithColumns(20);
19167 
19168   // See PR41213
19169   EXPECT_EQ("/*\n"
19170             " *\t9012345\n"
19171             " * /8901\n"
19172             " */",
19173             format("/*\n"
19174                    " *\t9012345 /8901\n"
19175                    " */",
19176                    Style));
19177   EXPECT_EQ("/*\n"
19178             " *345678\n"
19179             " *\t/8901\n"
19180             " */",
19181             format("/*\n"
19182                    " *345678\t/8901\n"
19183                    " */",
19184                    Style));
19185 
19186   verifyFormat("int a; // the\n"
19187                "       // comment",
19188                Style);
19189   EXPECT_EQ("int a; /* first line\n"
19190             "        * second\n"
19191             "        * line third\n"
19192             "        * line\n"
19193             "        */",
19194             format("int a; /* first line\n"
19195                    "        * second\n"
19196                    "        * line third\n"
19197                    "        * line\n"
19198                    "        */",
19199                    Style));
19200   EXPECT_EQ("int a; // first line\n"
19201             "       // second\n"
19202             "       // line third\n"
19203             "       // line",
19204             format("int a; // first line\n"
19205                    "       // second line\n"
19206                    "       // third line",
19207                    Style));
19208 
19209   Style.PenaltyExcessCharacter = 90;
19210   verifyFormat("int a; // the comment", Style);
19211   EXPECT_EQ("int a; // the comment\n"
19212             "       // aaa",
19213             format("int a; // the comment aaa", Style));
19214   EXPECT_EQ("int a; /* first line\n"
19215             "        * second line\n"
19216             "        * third line\n"
19217             "        */",
19218             format("int a; /* first line\n"
19219                    "        * second line\n"
19220                    "        * third line\n"
19221                    "        */",
19222                    Style));
19223   EXPECT_EQ("int a; // first line\n"
19224             "       // second line\n"
19225             "       // third line",
19226             format("int a; // first line\n"
19227                    "       // second line\n"
19228                    "       // third line",
19229                    Style));
19230   // FIXME: Investigate why this is not getting the same layout as the test
19231   // above.
19232   EXPECT_EQ("int a; /* first line\n"
19233             "        * second line\n"
19234             "        * third line\n"
19235             "        */",
19236             format("int a; /* first line second line third line"
19237                    "\n*/",
19238                    Style));
19239 
19240   EXPECT_EQ("// foo bar baz bazfoo\n"
19241             "// foo bar foo bar\n",
19242             format("// foo bar baz bazfoo\n"
19243                    "// foo bar foo           bar\n",
19244                    Style));
19245   EXPECT_EQ("// foo bar baz bazfoo\n"
19246             "// foo bar foo bar\n",
19247             format("// foo bar baz      bazfoo\n"
19248                    "// foo            bar foo bar\n",
19249                    Style));
19250 
19251   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19252   // next one.
19253   EXPECT_EQ("// foo bar baz bazfoo\n"
19254             "// bar foo bar\n",
19255             format("// foo bar baz      bazfoo bar\n"
19256                    "// foo            bar\n",
19257                    Style));
19258 
19259   EXPECT_EQ("// foo bar baz bazfoo\n"
19260             "// foo bar baz bazfoo\n"
19261             "// bar foo bar\n",
19262             format("// foo bar baz      bazfoo\n"
19263                    "// foo bar baz      bazfoo bar\n"
19264                    "// foo bar\n",
19265                    Style));
19266 
19267   EXPECT_EQ("// foo bar baz bazfoo\n"
19268             "// foo bar baz bazfoo\n"
19269             "// bar foo bar\n",
19270             format("// foo bar baz      bazfoo\n"
19271                    "// foo bar baz      bazfoo bar\n"
19272                    "// foo           bar\n",
19273                    Style));
19274 
19275   // Make sure we do not keep protruding characters if strict mode reflow is
19276   // cheaper than keeping protruding characters.
19277   Style.ColumnLimit = 21;
19278   EXPECT_EQ(
19279       "// foo foo foo foo\n"
19280       "// foo foo foo foo\n"
19281       "// foo foo foo foo\n",
19282       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19283 
19284   EXPECT_EQ("int a = /* long block\n"
19285             "           comment */\n"
19286             "    42;",
19287             format("int a = /* long block comment */ 42;", Style));
19288 }
19289 
19290 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19291   FormatStyle Style = getLLVMStyle();
19292   Style.ColumnLimit = 8;
19293   Style.PenaltyExcessCharacter = 15;
19294   verifyFormat("int foo(\n"
19295                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19296                Style);
19297   Style.PenaltyBreakOpenParenthesis = 200;
19298   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19299             format("int foo(\n"
19300                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19301                    Style));
19302 }
19303 
19304 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19305   FormatStyle Style = getLLVMStyle();
19306   Style.ColumnLimit = 5;
19307   Style.PenaltyExcessCharacter = 150;
19308   verifyFormat("foo((\n"
19309                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19310 
19311                Style);
19312   Style.PenaltyBreakOpenParenthesis = 100000;
19313   EXPECT_EQ("foo((int)\n"
19314             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19315             format("foo((\n"
19316                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19317                    Style));
19318 }
19319 
19320 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19321   FormatStyle Style = getLLVMStyle();
19322   Style.ColumnLimit = 4;
19323   Style.PenaltyExcessCharacter = 100;
19324   verifyFormat("for (\n"
19325                "    int iiiiiiiiiiiiiiiii =\n"
19326                "        0;\n"
19327                "    iiiiiiiiiiiiiiiii <\n"
19328                "    2;\n"
19329                "    iiiiiiiiiiiiiiiii++) {\n"
19330                "}",
19331 
19332                Style);
19333   Style.PenaltyBreakOpenParenthesis = 1250;
19334   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19335             "         0;\n"
19336             "     iiiiiiiiiiiiiiiii <\n"
19337             "     2;\n"
19338             "     iiiiiiiiiiiiiiiii++) {\n"
19339             "}",
19340             format("for (\n"
19341                    "    int iiiiiiiiiiiiiiiii =\n"
19342                    "        0;\n"
19343                    "    iiiiiiiiiiiiiiiii <\n"
19344                    "    2;\n"
19345                    "    iiiiiiiiiiiiiiiii++) {\n"
19346                    "}",
19347                    Style));
19348 }
19349 
19350 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19351   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19352   EXPECT_EQ(Styles[0], Styles[i])                                              \
19353       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19354 
19355 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19356   SmallVector<FormatStyle, 3> Styles;
19357   Styles.resize(3);
19358 
19359   Styles[0] = getLLVMStyle();
19360   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19361   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19362   EXPECT_ALL_STYLES_EQUAL(Styles);
19363 
19364   Styles[0] = getGoogleStyle();
19365   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19366   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19367   EXPECT_ALL_STYLES_EQUAL(Styles);
19368 
19369   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19370   EXPECT_TRUE(
19371       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19372   EXPECT_TRUE(
19373       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19374   EXPECT_ALL_STYLES_EQUAL(Styles);
19375 
19376   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19377   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19378   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19379   EXPECT_ALL_STYLES_EQUAL(Styles);
19380 
19381   Styles[0] = getMozillaStyle();
19382   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19383   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19384   EXPECT_ALL_STYLES_EQUAL(Styles);
19385 
19386   Styles[0] = getWebKitStyle();
19387   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19388   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19389   EXPECT_ALL_STYLES_EQUAL(Styles);
19390 
19391   Styles[0] = getGNUStyle();
19392   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19393   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19394   EXPECT_ALL_STYLES_EQUAL(Styles);
19395 
19396   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19397 }
19398 
19399 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19400   SmallVector<FormatStyle, 8> Styles;
19401   Styles.resize(2);
19402 
19403   Styles[0] = getGoogleStyle();
19404   Styles[1] = getLLVMStyle();
19405   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19406   EXPECT_ALL_STYLES_EQUAL(Styles);
19407 
19408   Styles.resize(5);
19409   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19410   Styles[1] = getLLVMStyle();
19411   Styles[1].Language = FormatStyle::LK_JavaScript;
19412   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19413 
19414   Styles[2] = getLLVMStyle();
19415   Styles[2].Language = FormatStyle::LK_JavaScript;
19416   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19417                                   "BasedOnStyle: Google",
19418                                   &Styles[2])
19419                    .value());
19420 
19421   Styles[3] = getLLVMStyle();
19422   Styles[3].Language = FormatStyle::LK_JavaScript;
19423   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19424                                   "Language: JavaScript",
19425                                   &Styles[3])
19426                    .value());
19427 
19428   Styles[4] = getLLVMStyle();
19429   Styles[4].Language = FormatStyle::LK_JavaScript;
19430   EXPECT_EQ(0, parseConfiguration("---\n"
19431                                   "BasedOnStyle: LLVM\n"
19432                                   "IndentWidth: 123\n"
19433                                   "---\n"
19434                                   "BasedOnStyle: Google\n"
19435                                   "Language: JavaScript",
19436                                   &Styles[4])
19437                    .value());
19438   EXPECT_ALL_STYLES_EQUAL(Styles);
19439 }
19440 
19441 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
19442   Style.FIELD = false;                                                         \
19443   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
19444   EXPECT_TRUE(Style.FIELD);                                                    \
19445   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
19446   EXPECT_FALSE(Style.FIELD);
19447 
19448 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
19449 
19450 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
19451   Style.STRUCT.FIELD = false;                                                  \
19452   EXPECT_EQ(0,                                                                 \
19453             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
19454                 .value());                                                     \
19455   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
19456   EXPECT_EQ(0,                                                                 \
19457             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
19458                 .value());                                                     \
19459   EXPECT_FALSE(Style.STRUCT.FIELD);
19460 
19461 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
19462   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
19463 
19464 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
19465   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
19466   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
19467   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
19468 
19469 TEST_F(FormatTest, ParsesConfigurationBools) {
19470   FormatStyle Style = {};
19471   Style.Language = FormatStyle::LK_Cpp;
19472   CHECK_PARSE_BOOL(AlignTrailingComments);
19473   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
19474   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
19475   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
19476   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
19477   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
19478   CHECK_PARSE_BOOL(BinPackArguments);
19479   CHECK_PARSE_BOOL(BinPackParameters);
19480   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
19481   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
19482   CHECK_PARSE_BOOL(BreakStringLiterals);
19483   CHECK_PARSE_BOOL(CompactNamespaces);
19484   CHECK_PARSE_BOOL(DeriveLineEnding);
19485   CHECK_PARSE_BOOL(DerivePointerAlignment);
19486   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
19487   CHECK_PARSE_BOOL(DisableFormat);
19488   CHECK_PARSE_BOOL(IndentAccessModifiers);
19489   CHECK_PARSE_BOOL(IndentCaseLabels);
19490   CHECK_PARSE_BOOL(IndentCaseBlocks);
19491   CHECK_PARSE_BOOL(IndentGotoLabels);
19492   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
19493   CHECK_PARSE_BOOL(IndentRequiresClause);
19494   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
19495   CHECK_PARSE_BOOL(InsertBraces);
19496   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
19497   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
19498   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
19499   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
19500   CHECK_PARSE_BOOL(ReflowComments);
19501   CHECK_PARSE_BOOL(RemoveBracesLLVM);
19502   CHECK_PARSE_BOOL(SortUsingDeclarations);
19503   CHECK_PARSE_BOOL(SpacesInParentheses);
19504   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
19505   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
19506   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
19507   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
19508   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
19509   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
19510   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
19511   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
19512   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
19513   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
19514   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
19515   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
19516   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
19517   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
19518   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
19519   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
19520   CHECK_PARSE_BOOL(UseCRLF);
19521 
19522   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
19523   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
19524   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
19525   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
19526   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
19527   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
19528   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
19529   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
19530   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
19531   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
19532   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
19533   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
19534   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
19535   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
19536   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
19537   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
19538   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
19539   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
19540   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
19541   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19542                           AfterFunctionDeclarationName);
19543   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
19544                           AfterFunctionDefinitionName);
19545   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
19546   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
19547   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
19548 }
19549 
19550 #undef CHECK_PARSE_BOOL
19551 
19552 TEST_F(FormatTest, ParsesConfiguration) {
19553   FormatStyle Style = {};
19554   Style.Language = FormatStyle::LK_Cpp;
19555   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
19556   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
19557               ConstructorInitializerIndentWidth, 1234u);
19558   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
19559   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
19560   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
19561   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
19562   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
19563               PenaltyBreakBeforeFirstCallParameter, 1234u);
19564   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
19565               PenaltyBreakTemplateDeclaration, 1234u);
19566   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
19567               1234u);
19568   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
19569   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
19570               PenaltyReturnTypeOnItsOwnLine, 1234u);
19571   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
19572               SpacesBeforeTrailingComments, 1234u);
19573   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
19574   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
19575   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
19576 
19577   Style.QualifierAlignment = FormatStyle::QAS_Right;
19578   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
19579               FormatStyle::QAS_Leave);
19580   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
19581               FormatStyle::QAS_Right);
19582   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
19583               FormatStyle::QAS_Left);
19584   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
19585               FormatStyle::QAS_Custom);
19586 
19587   Style.QualifierOrder.clear();
19588   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
19589               std::vector<std::string>({"const", "volatile", "type"}));
19590   Style.QualifierOrder.clear();
19591   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
19592               std::vector<std::string>({"const", "type"}));
19593   Style.QualifierOrder.clear();
19594   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
19595               std::vector<std::string>({"volatile", "type"}));
19596 
19597   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
19598   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
19599               FormatStyle::ACS_None);
19600   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
19601               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
19602   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
19603               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
19604   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
19605               AlignConsecutiveAssignments,
19606               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19607   // For backwards compability, false / true should still parse
19608   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
19609               FormatStyle::ACS_None);
19610   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
19611               FormatStyle::ACS_Consecutive);
19612 
19613   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
19614   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
19615               FormatStyle::ACS_None);
19616   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
19617               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
19618   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
19619               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
19620   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
19621               AlignConsecutiveBitFields,
19622               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19623   // For backwards compability, false / true should still parse
19624   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
19625               FormatStyle::ACS_None);
19626   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
19627               FormatStyle::ACS_Consecutive);
19628 
19629   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
19630   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
19631               FormatStyle::ACS_None);
19632   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
19633               FormatStyle::ACS_Consecutive);
19634   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
19635               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
19636   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
19637               AlignConsecutiveMacros,
19638               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19639   // For backwards compability, false / true should still parse
19640   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
19641               FormatStyle::ACS_None);
19642   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
19643               FormatStyle::ACS_Consecutive);
19644 
19645   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
19646   CHECK_PARSE("AlignConsecutiveDeclarations: None",
19647               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
19648   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
19649               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
19650   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
19651               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
19652   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
19653               AlignConsecutiveDeclarations,
19654               FormatStyle::ACS_AcrossEmptyLinesAndComments);
19655   // For backwards compability, false / true should still parse
19656   CHECK_PARSE("AlignConsecutiveDeclarations: false",
19657               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
19658   CHECK_PARSE("AlignConsecutiveDeclarations: true",
19659               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
19660 
19661   Style.PointerAlignment = FormatStyle::PAS_Middle;
19662   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
19663               FormatStyle::PAS_Left);
19664   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
19665               FormatStyle::PAS_Right);
19666   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
19667               FormatStyle::PAS_Middle);
19668   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
19669   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
19670               FormatStyle::RAS_Pointer);
19671   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
19672               FormatStyle::RAS_Left);
19673   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
19674               FormatStyle::RAS_Right);
19675   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
19676               FormatStyle::RAS_Middle);
19677   // For backward compatibility:
19678   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
19679               FormatStyle::PAS_Left);
19680   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
19681               FormatStyle::PAS_Right);
19682   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
19683               FormatStyle::PAS_Middle);
19684 
19685   Style.Standard = FormatStyle::LS_Auto;
19686   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
19687   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
19688   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
19689   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
19690   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
19691   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
19692   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
19693   // Legacy aliases:
19694   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
19695   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
19696   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
19697   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
19698 
19699   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
19700   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
19701               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
19702   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
19703               FormatStyle::BOS_None);
19704   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
19705               FormatStyle::BOS_All);
19706   // For backward compatibility:
19707   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
19708               FormatStyle::BOS_None);
19709   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
19710               FormatStyle::BOS_All);
19711 
19712   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
19713   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
19714               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19715   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
19716               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
19717   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
19718               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
19719   // For backward compatibility:
19720   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
19721               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19722 
19723   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
19724   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
19725               FormatStyle::BILS_AfterComma);
19726   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
19727               FormatStyle::BILS_BeforeComma);
19728   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
19729               FormatStyle::BILS_AfterColon);
19730   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
19731               FormatStyle::BILS_BeforeColon);
19732   // For backward compatibility:
19733   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
19734               FormatStyle::BILS_BeforeComma);
19735 
19736   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19737   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
19738               FormatStyle::PCIS_Never);
19739   CHECK_PARSE("PackConstructorInitializers: BinPack",
19740               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19741   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
19742               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19743   CHECK_PARSE("PackConstructorInitializers: NextLine",
19744               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19745   // For backward compatibility:
19746   CHECK_PARSE("BasedOnStyle: Google\n"
19747               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19748               "AllowAllConstructorInitializersOnNextLine: false",
19749               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19750   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19751   CHECK_PARSE("BasedOnStyle: Google\n"
19752               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
19753               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19754   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19755               "AllowAllConstructorInitializersOnNextLine: true",
19756               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19757   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19758   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19759               "AllowAllConstructorInitializersOnNextLine: false",
19760               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19761 
19762   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
19763   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
19764               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
19765   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
19766               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
19767   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
19768               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
19769   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
19770               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
19771 
19772   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19773   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
19774               FormatStyle::BAS_Align);
19775   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
19776               FormatStyle::BAS_DontAlign);
19777   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
19778               FormatStyle::BAS_AlwaysBreak);
19779   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
19780               FormatStyle::BAS_BlockIndent);
19781   // For backward compatibility:
19782   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
19783               FormatStyle::BAS_DontAlign);
19784   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
19785               FormatStyle::BAS_Align);
19786 
19787   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
19788   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
19789               FormatStyle::ENAS_DontAlign);
19790   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
19791               FormatStyle::ENAS_Left);
19792   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
19793               FormatStyle::ENAS_Right);
19794   // For backward compatibility:
19795   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
19796               FormatStyle::ENAS_Left);
19797   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
19798               FormatStyle::ENAS_Right);
19799 
19800   Style.AlignOperands = FormatStyle::OAS_Align;
19801   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
19802               FormatStyle::OAS_DontAlign);
19803   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
19804   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
19805               FormatStyle::OAS_AlignAfterOperator);
19806   // For backward compatibility:
19807   CHECK_PARSE("AlignOperands: false", AlignOperands,
19808               FormatStyle::OAS_DontAlign);
19809   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
19810 
19811   Style.UseTab = FormatStyle::UT_ForIndentation;
19812   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
19813   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
19814   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
19815   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
19816               FormatStyle::UT_ForContinuationAndIndentation);
19817   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
19818               FormatStyle::UT_AlignWithSpaces);
19819   // For backward compatibility:
19820   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
19821   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
19822 
19823   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
19824   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
19825               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19826   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
19827               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
19828   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
19829               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19830   // For backward compatibility:
19831   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
19832               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19833   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
19834               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19835 
19836   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
19837   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
19838               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19839   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
19840               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
19841   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
19842               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
19843   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
19844               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19845   // For backward compatibility:
19846   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
19847               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19848   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
19849               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19850 
19851   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
19852   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
19853               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
19854   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
19855               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
19856   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
19857               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
19858   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
19859               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
19860 
19861   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
19862   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
19863               FormatStyle::SBPO_Never);
19864   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
19865               FormatStyle::SBPO_Always);
19866   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
19867               FormatStyle::SBPO_ControlStatements);
19868   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
19869               SpaceBeforeParens,
19870               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19871   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
19872               FormatStyle::SBPO_NonEmptyParentheses);
19873   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
19874               FormatStyle::SBPO_Custom);
19875   // For backward compatibility:
19876   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
19877               FormatStyle::SBPO_Never);
19878   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
19879               FormatStyle::SBPO_ControlStatements);
19880   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
19881               SpaceBeforeParens,
19882               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19883 
19884   Style.ColumnLimit = 123;
19885   FormatStyle BaseStyle = getLLVMStyle();
19886   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
19887   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
19888 
19889   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
19890   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
19891               FormatStyle::BS_Attach);
19892   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
19893               FormatStyle::BS_Linux);
19894   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
19895               FormatStyle::BS_Mozilla);
19896   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
19897               FormatStyle::BS_Stroustrup);
19898   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
19899               FormatStyle::BS_Allman);
19900   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
19901               FormatStyle::BS_Whitesmiths);
19902   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
19903   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
19904               FormatStyle::BS_WebKit);
19905   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
19906               FormatStyle::BS_Custom);
19907 
19908   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
19909   CHECK_PARSE("BraceWrapping:\n"
19910               "  AfterControlStatement: MultiLine",
19911               BraceWrapping.AfterControlStatement,
19912               FormatStyle::BWACS_MultiLine);
19913   CHECK_PARSE("BraceWrapping:\n"
19914               "  AfterControlStatement: Always",
19915               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19916   CHECK_PARSE("BraceWrapping:\n"
19917               "  AfterControlStatement: Never",
19918               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19919   // For backward compatibility:
19920   CHECK_PARSE("BraceWrapping:\n"
19921               "  AfterControlStatement: true",
19922               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19923   CHECK_PARSE("BraceWrapping:\n"
19924               "  AfterControlStatement: false",
19925               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19926 
19927   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
19928   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
19929               FormatStyle::RTBS_None);
19930   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
19931               FormatStyle::RTBS_All);
19932   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
19933               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
19934   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
19935               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
19936   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
19937               AlwaysBreakAfterReturnType,
19938               FormatStyle::RTBS_TopLevelDefinitions);
19939 
19940   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
19941   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
19942               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
19943   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
19944               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19945   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
19946               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19947   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
19948               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19949   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
19950               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19951 
19952   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
19953   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
19954               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
19955   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
19956               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
19957   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
19958               AlwaysBreakAfterDefinitionReturnType,
19959               FormatStyle::DRTBS_TopLevel);
19960 
19961   Style.NamespaceIndentation = FormatStyle::NI_All;
19962   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
19963               FormatStyle::NI_None);
19964   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
19965               FormatStyle::NI_Inner);
19966   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
19967               FormatStyle::NI_All);
19968 
19969   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
19970   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
19971               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19972   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
19973               AllowShortIfStatementsOnASingleLine,
19974               FormatStyle::SIS_WithoutElse);
19975   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
19976               AllowShortIfStatementsOnASingleLine,
19977               FormatStyle::SIS_OnlyFirstIf);
19978   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
19979               AllowShortIfStatementsOnASingleLine,
19980               FormatStyle::SIS_AllIfsAndElse);
19981   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
19982               AllowShortIfStatementsOnASingleLine,
19983               FormatStyle::SIS_OnlyFirstIf);
19984   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
19985               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19986   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
19987               AllowShortIfStatementsOnASingleLine,
19988               FormatStyle::SIS_WithoutElse);
19989 
19990   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
19991   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
19992               FormatStyle::IEBS_AfterExternBlock);
19993   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
19994               FormatStyle::IEBS_Indent);
19995   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
19996               FormatStyle::IEBS_NoIndent);
19997   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
19998               FormatStyle::IEBS_Indent);
19999   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20000               FormatStyle::IEBS_NoIndent);
20001 
20002   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20003   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20004               FormatStyle::BFCS_Both);
20005   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20006               FormatStyle::BFCS_None);
20007   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20008               FormatStyle::BFCS_Before);
20009   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20010               FormatStyle::BFCS_After);
20011 
20012   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20013   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20014               FormatStyle::SJSIO_After);
20015   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20016               FormatStyle::SJSIO_Before);
20017 
20018   // FIXME: This is required because parsing a configuration simply overwrites
20019   // the first N elements of the list instead of resetting it.
20020   Style.ForEachMacros.clear();
20021   std::vector<std::string> BoostForeach;
20022   BoostForeach.push_back("BOOST_FOREACH");
20023   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20024   std::vector<std::string> BoostAndQForeach;
20025   BoostAndQForeach.push_back("BOOST_FOREACH");
20026   BoostAndQForeach.push_back("Q_FOREACH");
20027   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20028               BoostAndQForeach);
20029 
20030   Style.IfMacros.clear();
20031   std::vector<std::string> CustomIfs;
20032   CustomIfs.push_back("MYIF");
20033   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20034 
20035   Style.AttributeMacros.clear();
20036   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20037               std::vector<std::string>{"__capability"});
20038   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20039               std::vector<std::string>({"attr1", "attr2"}));
20040 
20041   Style.StatementAttributeLikeMacros.clear();
20042   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20043               StatementAttributeLikeMacros,
20044               std::vector<std::string>({"emit", "Q_EMIT"}));
20045 
20046   Style.StatementMacros.clear();
20047   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20048               std::vector<std::string>{"QUNUSED"});
20049   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20050               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20051 
20052   Style.NamespaceMacros.clear();
20053   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20054               std::vector<std::string>{"TESTSUITE"});
20055   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20056               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20057 
20058   Style.WhitespaceSensitiveMacros.clear();
20059   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20060               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20061   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20062               WhitespaceSensitiveMacros,
20063               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20064   Style.WhitespaceSensitiveMacros.clear();
20065   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20066               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20067   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20068               WhitespaceSensitiveMacros,
20069               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20070 
20071   Style.IncludeStyle.IncludeCategories.clear();
20072   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20073       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20074   CHECK_PARSE("IncludeCategories:\n"
20075               "  - Regex: abc/.*\n"
20076               "    Priority: 2\n"
20077               "  - Regex: .*\n"
20078               "    Priority: 1\n"
20079               "    CaseSensitive: true\n",
20080               IncludeStyle.IncludeCategories, ExpectedCategories);
20081   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20082               "abc$");
20083   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20084               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20085 
20086   Style.SortIncludes = FormatStyle::SI_Never;
20087   CHECK_PARSE("SortIncludes: true", SortIncludes,
20088               FormatStyle::SI_CaseSensitive);
20089   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20090   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20091               FormatStyle::SI_CaseInsensitive);
20092   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20093               FormatStyle::SI_CaseSensitive);
20094   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20095 
20096   Style.RawStringFormats.clear();
20097   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20098       {
20099           FormatStyle::LK_TextProto,
20100           {"pb", "proto"},
20101           {"PARSE_TEXT_PROTO"},
20102           /*CanonicalDelimiter=*/"",
20103           "llvm",
20104       },
20105       {
20106           FormatStyle::LK_Cpp,
20107           {"cc", "cpp"},
20108           {"C_CODEBLOCK", "CPPEVAL"},
20109           /*CanonicalDelimiter=*/"cc",
20110           /*BasedOnStyle=*/"",
20111       },
20112   };
20113 
20114   CHECK_PARSE("RawStringFormats:\n"
20115               "  - Language: TextProto\n"
20116               "    Delimiters:\n"
20117               "      - 'pb'\n"
20118               "      - 'proto'\n"
20119               "    EnclosingFunctions:\n"
20120               "      - 'PARSE_TEXT_PROTO'\n"
20121               "    BasedOnStyle: llvm\n"
20122               "  - Language: Cpp\n"
20123               "    Delimiters:\n"
20124               "      - 'cc'\n"
20125               "      - 'cpp'\n"
20126               "    EnclosingFunctions:\n"
20127               "      - 'C_CODEBLOCK'\n"
20128               "      - 'CPPEVAL'\n"
20129               "    CanonicalDelimiter: 'cc'",
20130               RawStringFormats, ExpectedRawStringFormats);
20131 
20132   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20133               "  Minimum: 0\n"
20134               "  Maximum: 0",
20135               SpacesInLineCommentPrefix.Minimum, 0u);
20136   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20137   Style.SpacesInLineCommentPrefix.Minimum = 1;
20138   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20139               "  Minimum: 2",
20140               SpacesInLineCommentPrefix.Minimum, 0u);
20141   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20142               "  Maximum: -1",
20143               SpacesInLineCommentPrefix.Maximum, -1u);
20144   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20145               "  Minimum: 2",
20146               SpacesInLineCommentPrefix.Minimum, 2u);
20147   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20148               "  Maximum: 1",
20149               SpacesInLineCommentPrefix.Maximum, 1u);
20150   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20151 
20152   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20153   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20154   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20155               FormatStyle::SIAS_Always);
20156   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20157   // For backward compatibility:
20158   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20159   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20160 
20161   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20162               FormatStyle::RCPS_WithPreceding);
20163   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20164               FormatStyle::RCPS_WithFollowing);
20165   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20166               FormatStyle::RCPS_SingleLine);
20167   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20168               FormatStyle::RCPS_OwnLine);
20169 
20170   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20171               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20172   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20173               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20174   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20175               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20176   // For backward compatibility:
20177   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20178               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20179   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20180               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20181 }
20182 
20183 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20184   FormatStyle Style = {};
20185   Style.Language = FormatStyle::LK_Cpp;
20186   CHECK_PARSE("Language: Cpp\n"
20187               "IndentWidth: 12",
20188               IndentWidth, 12u);
20189   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20190                                "IndentWidth: 34",
20191                                &Style),
20192             ParseError::Unsuitable);
20193   FormatStyle BinPackedTCS = {};
20194   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20195   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20196                                "InsertTrailingCommas: Wrapped",
20197                                &BinPackedTCS),
20198             ParseError::BinPackTrailingCommaConflict);
20199   EXPECT_EQ(12u, Style.IndentWidth);
20200   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20201   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20202 
20203   Style.Language = FormatStyle::LK_JavaScript;
20204   CHECK_PARSE("Language: JavaScript\n"
20205               "IndentWidth: 12",
20206               IndentWidth, 12u);
20207   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20208   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20209                                "IndentWidth: 34",
20210                                &Style),
20211             ParseError::Unsuitable);
20212   EXPECT_EQ(23u, Style.IndentWidth);
20213   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20214   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20215 
20216   CHECK_PARSE("BasedOnStyle: LLVM\n"
20217               "IndentWidth: 67",
20218               IndentWidth, 67u);
20219 
20220   CHECK_PARSE("---\n"
20221               "Language: JavaScript\n"
20222               "IndentWidth: 12\n"
20223               "---\n"
20224               "Language: Cpp\n"
20225               "IndentWidth: 34\n"
20226               "...\n",
20227               IndentWidth, 12u);
20228 
20229   Style.Language = FormatStyle::LK_Cpp;
20230   CHECK_PARSE("---\n"
20231               "Language: JavaScript\n"
20232               "IndentWidth: 12\n"
20233               "---\n"
20234               "Language: Cpp\n"
20235               "IndentWidth: 34\n"
20236               "...\n",
20237               IndentWidth, 34u);
20238   CHECK_PARSE("---\n"
20239               "IndentWidth: 78\n"
20240               "---\n"
20241               "Language: JavaScript\n"
20242               "IndentWidth: 56\n"
20243               "...\n",
20244               IndentWidth, 78u);
20245 
20246   Style.ColumnLimit = 123;
20247   Style.IndentWidth = 234;
20248   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20249   Style.TabWidth = 345;
20250   EXPECT_FALSE(parseConfiguration("---\n"
20251                                   "IndentWidth: 456\n"
20252                                   "BreakBeforeBraces: Allman\n"
20253                                   "---\n"
20254                                   "Language: JavaScript\n"
20255                                   "IndentWidth: 111\n"
20256                                   "TabWidth: 111\n"
20257                                   "---\n"
20258                                   "Language: Cpp\n"
20259                                   "BreakBeforeBraces: Stroustrup\n"
20260                                   "TabWidth: 789\n"
20261                                   "...\n",
20262                                   &Style));
20263   EXPECT_EQ(123u, Style.ColumnLimit);
20264   EXPECT_EQ(456u, Style.IndentWidth);
20265   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20266   EXPECT_EQ(789u, Style.TabWidth);
20267 
20268   EXPECT_EQ(parseConfiguration("---\n"
20269                                "Language: JavaScript\n"
20270                                "IndentWidth: 56\n"
20271                                "---\n"
20272                                "IndentWidth: 78\n"
20273                                "...\n",
20274                                &Style),
20275             ParseError::Error);
20276   EXPECT_EQ(parseConfiguration("---\n"
20277                                "Language: JavaScript\n"
20278                                "IndentWidth: 56\n"
20279                                "---\n"
20280                                "Language: JavaScript\n"
20281                                "IndentWidth: 78\n"
20282                                "...\n",
20283                                &Style),
20284             ParseError::Error);
20285 
20286   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20287 }
20288 
20289 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20290   FormatStyle Style = {};
20291   Style.Language = FormatStyle::LK_JavaScript;
20292   Style.BreakBeforeTernaryOperators = true;
20293   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20294   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20295 
20296   Style.BreakBeforeTernaryOperators = true;
20297   EXPECT_EQ(0, parseConfiguration("---\n"
20298                                   "BasedOnStyle: Google\n"
20299                                   "---\n"
20300                                   "Language: JavaScript\n"
20301                                   "IndentWidth: 76\n"
20302                                   "...\n",
20303                                   &Style)
20304                    .value());
20305   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20306   EXPECT_EQ(76u, Style.IndentWidth);
20307   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20308 }
20309 
20310 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20311   FormatStyle Style = getLLVMStyle();
20312   std::string YAML = configurationAsText(Style);
20313   FormatStyle ParsedStyle = {};
20314   ParsedStyle.Language = FormatStyle::LK_Cpp;
20315   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20316   EXPECT_EQ(Style, ParsedStyle);
20317 }
20318 
20319 TEST_F(FormatTest, WorksFor8bitEncodings) {
20320   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20321             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20322             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20323             "\"\xef\xee\xf0\xf3...\"",
20324             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20325                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20326                    "\xef\xee\xf0\xf3...\"",
20327                    getLLVMStyleWithColumns(12)));
20328 }
20329 
20330 TEST_F(FormatTest, HandlesUTF8BOM) {
20331   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20332   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20333             format("\xef\xbb\xbf#include <iostream>"));
20334   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20335             format("\xef\xbb\xbf\n#include <iostream>"));
20336 }
20337 
20338 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20339 #if !defined(_MSC_VER)
20340 
20341 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20342   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20343                getLLVMStyleWithColumns(35));
20344   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20345                getLLVMStyleWithColumns(31));
20346   verifyFormat("// Однажды в студёную зимнюю пору...",
20347                getLLVMStyleWithColumns(36));
20348   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20349   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20350                getLLVMStyleWithColumns(39));
20351   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20352                getLLVMStyleWithColumns(35));
20353 }
20354 
20355 TEST_F(FormatTest, SplitsUTF8Strings) {
20356   // Non-printable characters' width is currently considered to be the length in
20357   // bytes in UTF8. The characters can be displayed in very different manner
20358   // (zero-width, single width with a substitution glyph, expanded to their code
20359   // (e.g. "<8d>"), so there's no single correct way to handle them.
20360   EXPECT_EQ("\"aaaaÄ\"\n"
20361             "\"\xc2\x8d\";",
20362             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20363   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20364             "\"\xc2\x8d\";",
20365             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20366   EXPECT_EQ("\"Однажды, в \"\n"
20367             "\"студёную \"\n"
20368             "\"зимнюю \"\n"
20369             "\"пору,\"",
20370             format("\"Однажды, в студёную зимнюю пору,\"",
20371                    getLLVMStyleWithColumns(13)));
20372   EXPECT_EQ(
20373       "\"一 二 三 \"\n"
20374       "\"四 五六 \"\n"
20375       "\"七 八 九 \"\n"
20376       "\"十\"",
20377       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20378   EXPECT_EQ("\"一\t\"\n"
20379             "\"二 \t\"\n"
20380             "\"三 四 \"\n"
20381             "\"五\t\"\n"
20382             "\"六 \t\"\n"
20383             "\"七 \"\n"
20384             "\"八九十\tqq\"",
20385             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20386                    getLLVMStyleWithColumns(11)));
20387 
20388   // UTF8 character in an escape sequence.
20389   EXPECT_EQ("\"aaaaaa\"\n"
20390             "\"\\\xC2\x8D\"",
20391             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20392 }
20393 
20394 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20395   EXPECT_EQ("const char *sssss =\n"
20396             "    \"一二三四五六七八\\\n"
20397             " 九 十\";",
20398             format("const char *sssss = \"一二三四五六七八\\\n"
20399                    " 九 十\";",
20400                    getLLVMStyleWithColumns(30)));
20401 }
20402 
20403 TEST_F(FormatTest, SplitsUTF8LineComments) {
20404   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20405             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20406   EXPECT_EQ("// Я из лесу\n"
20407             "// вышел; был\n"
20408             "// сильный\n"
20409             "// мороз.",
20410             format("// Я из лесу вышел; был сильный мороз.",
20411                    getLLVMStyleWithColumns(13)));
20412   EXPECT_EQ("// 一二三\n"
20413             "// 四五六七\n"
20414             "// 八  九\n"
20415             "// 十",
20416             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20417 }
20418 
20419 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20420   EXPECT_EQ("/* Гляжу,\n"
20421             " * поднимается\n"
20422             " * медленно в\n"
20423             " * гору\n"
20424             " * Лошадка,\n"
20425             " * везущая\n"
20426             " * хворосту\n"
20427             " * воз. */",
20428             format("/* Гляжу, поднимается медленно в гору\n"
20429                    " * Лошадка, везущая хворосту воз. */",
20430                    getLLVMStyleWithColumns(13)));
20431   EXPECT_EQ(
20432       "/* 一二三\n"
20433       " * 四五六七\n"
20434       " * 八  九\n"
20435       " * 十  */",
20436       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20437   EXPECT_EQ("/* �������� ��������\n"
20438             " * ��������\n"
20439             " * ������-�� */",
20440             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20441 }
20442 
20443 #endif // _MSC_VER
20444 
20445 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
20446   FormatStyle Style = getLLVMStyle();
20447 
20448   Style.ConstructorInitializerIndentWidth = 4;
20449   verifyFormat(
20450       "SomeClass::Constructor()\n"
20451       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20452       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20453       Style);
20454 
20455   Style.ConstructorInitializerIndentWidth = 2;
20456   verifyFormat(
20457       "SomeClass::Constructor()\n"
20458       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20459       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20460       Style);
20461 
20462   Style.ConstructorInitializerIndentWidth = 0;
20463   verifyFormat(
20464       "SomeClass::Constructor()\n"
20465       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
20466       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
20467       Style);
20468   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20469   verifyFormat(
20470       "SomeLongTemplateVariableName<\n"
20471       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
20472       Style);
20473   verifyFormat("bool smaller = 1 < "
20474                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
20475                "                       "
20476                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
20477                Style);
20478 
20479   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
20480   verifyFormat("SomeClass::Constructor() :\n"
20481                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
20482                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
20483                Style);
20484 }
20485 
20486 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
20487   FormatStyle Style = getLLVMStyle();
20488   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20489   Style.ConstructorInitializerIndentWidth = 4;
20490   verifyFormat("SomeClass::Constructor()\n"
20491                "    : a(a)\n"
20492                "    , b(b)\n"
20493                "    , c(c) {}",
20494                Style);
20495   verifyFormat("SomeClass::Constructor()\n"
20496                "    : a(a) {}",
20497                Style);
20498 
20499   Style.ColumnLimit = 0;
20500   verifyFormat("SomeClass::Constructor()\n"
20501                "    : a(a) {}",
20502                Style);
20503   verifyFormat("SomeClass::Constructor() noexcept\n"
20504                "    : a(a) {}",
20505                Style);
20506   verifyFormat("SomeClass::Constructor()\n"
20507                "    : a(a)\n"
20508                "    , b(b)\n"
20509                "    , c(c) {}",
20510                Style);
20511   verifyFormat("SomeClass::Constructor()\n"
20512                "    : a(a) {\n"
20513                "  foo();\n"
20514                "  bar();\n"
20515                "}",
20516                Style);
20517 
20518   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20519   verifyFormat("SomeClass::Constructor()\n"
20520                "    : a(a)\n"
20521                "    , b(b)\n"
20522                "    , c(c) {\n}",
20523                Style);
20524   verifyFormat("SomeClass::Constructor()\n"
20525                "    : a(a) {\n}",
20526                Style);
20527 
20528   Style.ColumnLimit = 80;
20529   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
20530   Style.ConstructorInitializerIndentWidth = 2;
20531   verifyFormat("SomeClass::Constructor()\n"
20532                "  : a(a)\n"
20533                "  , b(b)\n"
20534                "  , c(c) {}",
20535                Style);
20536 
20537   Style.ConstructorInitializerIndentWidth = 0;
20538   verifyFormat("SomeClass::Constructor()\n"
20539                ": a(a)\n"
20540                ", b(b)\n"
20541                ", c(c) {}",
20542                Style);
20543 
20544   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20545   Style.ConstructorInitializerIndentWidth = 4;
20546   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
20547   verifyFormat(
20548       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
20549       Style);
20550   verifyFormat(
20551       "SomeClass::Constructor()\n"
20552       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
20553       Style);
20554   Style.ConstructorInitializerIndentWidth = 4;
20555   Style.ColumnLimit = 60;
20556   verifyFormat("SomeClass::Constructor()\n"
20557                "    : aaaaaaaa(aaaaaaaa)\n"
20558                "    , aaaaaaaa(aaaaaaaa)\n"
20559                "    , aaaaaaaa(aaaaaaaa) {}",
20560                Style);
20561 }
20562 
20563 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
20564   FormatStyle Style = getLLVMStyle();
20565   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
20566   Style.ConstructorInitializerIndentWidth = 4;
20567   verifyFormat("SomeClass::Constructor()\n"
20568                "    : a{a}\n"
20569                "    , b{b} {}",
20570                Style);
20571   verifyFormat("SomeClass::Constructor()\n"
20572                "    : a{a}\n"
20573                "#if CONDITION\n"
20574                "    , b{b}\n"
20575                "#endif\n"
20576                "{\n}",
20577                Style);
20578   Style.ConstructorInitializerIndentWidth = 2;
20579   verifyFormat("SomeClass::Constructor()\n"
20580                "#if CONDITION\n"
20581                "  : a{a}\n"
20582                "#endif\n"
20583                "  , b{b}\n"
20584                "  , c{c} {\n}",
20585                Style);
20586   Style.ConstructorInitializerIndentWidth = 0;
20587   verifyFormat("SomeClass::Constructor()\n"
20588                ": a{a}\n"
20589                "#ifdef CONDITION\n"
20590                ", b{b}\n"
20591                "#else\n"
20592                ", c{c}\n"
20593                "#endif\n"
20594                ", d{d} {\n}",
20595                Style);
20596   Style.ConstructorInitializerIndentWidth = 4;
20597   verifyFormat("SomeClass::Constructor()\n"
20598                "    : a{a}\n"
20599                "#if WINDOWS\n"
20600                "#if DEBUG\n"
20601                "    , b{0}\n"
20602                "#else\n"
20603                "    , b{1}\n"
20604                "#endif\n"
20605                "#else\n"
20606                "#if DEBUG\n"
20607                "    , b{2}\n"
20608                "#else\n"
20609                "    , b{3}\n"
20610                "#endif\n"
20611                "#endif\n"
20612                "{\n}",
20613                Style);
20614   verifyFormat("SomeClass::Constructor()\n"
20615                "    : a{a}\n"
20616                "#if WINDOWS\n"
20617                "    , b{0}\n"
20618                "#if DEBUG\n"
20619                "    , c{0}\n"
20620                "#else\n"
20621                "    , c{1}\n"
20622                "#endif\n"
20623                "#else\n"
20624                "#if DEBUG\n"
20625                "    , c{2}\n"
20626                "#else\n"
20627                "    , c{3}\n"
20628                "#endif\n"
20629                "    , b{1}\n"
20630                "#endif\n"
20631                "{\n}",
20632                Style);
20633 }
20634 
20635 TEST_F(FormatTest, Destructors) {
20636   verifyFormat("void F(int &i) { i.~int(); }");
20637   verifyFormat("void F(int &i) { i->~int(); }");
20638 }
20639 
20640 TEST_F(FormatTest, FormatsWithWebKitStyle) {
20641   FormatStyle Style = getWebKitStyle();
20642 
20643   // Don't indent in outer namespaces.
20644   verifyFormat("namespace outer {\n"
20645                "int i;\n"
20646                "namespace inner {\n"
20647                "    int i;\n"
20648                "} // namespace inner\n"
20649                "} // namespace outer\n"
20650                "namespace other_outer {\n"
20651                "int i;\n"
20652                "}",
20653                Style);
20654 
20655   // Don't indent case labels.
20656   verifyFormat("switch (variable) {\n"
20657                "case 1:\n"
20658                "case 2:\n"
20659                "    doSomething();\n"
20660                "    break;\n"
20661                "default:\n"
20662                "    ++variable;\n"
20663                "}",
20664                Style);
20665 
20666   // Wrap before binary operators.
20667   EXPECT_EQ("void f()\n"
20668             "{\n"
20669             "    if (aaaaaaaaaaaaaaaa\n"
20670             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
20671             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20672             "        return;\n"
20673             "}",
20674             format("void f() {\n"
20675                    "if (aaaaaaaaaaaaaaaa\n"
20676                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
20677                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
20678                    "return;\n"
20679                    "}",
20680                    Style));
20681 
20682   // Allow functions on a single line.
20683   verifyFormat("void f() { return; }", Style);
20684 
20685   // Allow empty blocks on a single line and insert a space in empty blocks.
20686   EXPECT_EQ("void f() { }", format("void f() {}", Style));
20687   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
20688   // However, don't merge non-empty short loops.
20689   EXPECT_EQ("while (true) {\n"
20690             "    continue;\n"
20691             "}",
20692             format("while (true) { continue; }", Style));
20693 
20694   // Constructor initializers are formatted one per line with the "," on the
20695   // new line.
20696   verifyFormat("Constructor()\n"
20697                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
20698                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
20699                "          aaaaaaaaaaaaaa)\n"
20700                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
20701                "{\n"
20702                "}",
20703                Style);
20704   verifyFormat("SomeClass::Constructor()\n"
20705                "    : a(a)\n"
20706                "{\n"
20707                "}",
20708                Style);
20709   EXPECT_EQ("SomeClass::Constructor()\n"
20710             "    : a(a)\n"
20711             "{\n"
20712             "}",
20713             format("SomeClass::Constructor():a(a){}", Style));
20714   verifyFormat("SomeClass::Constructor()\n"
20715                "    : a(a)\n"
20716                "    , b(b)\n"
20717                "    , c(c)\n"
20718                "{\n"
20719                "}",
20720                Style);
20721   verifyFormat("SomeClass::Constructor()\n"
20722                "    : a(a)\n"
20723                "{\n"
20724                "    foo();\n"
20725                "    bar();\n"
20726                "}",
20727                Style);
20728 
20729   // Access specifiers should be aligned left.
20730   verifyFormat("class C {\n"
20731                "public:\n"
20732                "    int i;\n"
20733                "};",
20734                Style);
20735 
20736   // Do not align comments.
20737   verifyFormat("int a; // Do not\n"
20738                "double b; // align comments.",
20739                Style);
20740 
20741   // Do not align operands.
20742   EXPECT_EQ("ASSERT(aaaa\n"
20743             "    || bbbb);",
20744             format("ASSERT ( aaaa\n||bbbb);", Style));
20745 
20746   // Accept input's line breaks.
20747   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
20748             "    || bbbbbbbbbbbbbbb) {\n"
20749             "    i++;\n"
20750             "}",
20751             format("if (aaaaaaaaaaaaaaa\n"
20752                    "|| bbbbbbbbbbbbbbb) { i++; }",
20753                    Style));
20754   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
20755             "    i++;\n"
20756             "}",
20757             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
20758 
20759   // Don't automatically break all macro definitions (llvm.org/PR17842).
20760   verifyFormat("#define aNumber 10", Style);
20761   // However, generally keep the line breaks that the user authored.
20762   EXPECT_EQ("#define aNumber \\\n"
20763             "    10",
20764             format("#define aNumber \\\n"
20765                    " 10",
20766                    Style));
20767 
20768   // Keep empty and one-element array literals on a single line.
20769   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
20770             "                                  copyItems:YES];",
20771             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
20772                    "copyItems:YES];",
20773                    Style));
20774   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
20775             "                                  copyItems:YES];",
20776             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
20777                    "             copyItems:YES];",
20778                    Style));
20779   // FIXME: This does not seem right, there should be more indentation before
20780   // the array literal's entries. Nested blocks have the same problem.
20781   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20782             "    @\"a\",\n"
20783             "    @\"a\"\n"
20784             "]\n"
20785             "                                  copyItems:YES];",
20786             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20787                    "     @\"a\",\n"
20788                    "     @\"a\"\n"
20789                    "     ]\n"
20790                    "       copyItems:YES];",
20791                    Style));
20792   EXPECT_EQ(
20793       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20794       "                                  copyItems:YES];",
20795       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20796              "   copyItems:YES];",
20797              Style));
20798 
20799   verifyFormat("[self.a b:c c:d];", Style);
20800   EXPECT_EQ("[self.a b:c\n"
20801             "        c:d];",
20802             format("[self.a b:c\n"
20803                    "c:d];",
20804                    Style));
20805 }
20806 
20807 TEST_F(FormatTest, FormatsLambdas) {
20808   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
20809   verifyFormat(
20810       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
20811   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
20812   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
20813   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
20814   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
20815   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
20816   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
20817   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
20818   verifyFormat("int x = f(*+[] {});");
20819   verifyFormat("void f() {\n"
20820                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
20821                "}\n");
20822   verifyFormat("void f() {\n"
20823                "  other(x.begin(), //\n"
20824                "        x.end(),   //\n"
20825                "        [&](int, int) { return 1; });\n"
20826                "}\n");
20827   verifyFormat("void f() {\n"
20828                "  other.other.other.other.other(\n"
20829                "      x.begin(), x.end(),\n"
20830                "      [something, rather](int, int, int, int, int, int, int) { "
20831                "return 1; });\n"
20832                "}\n");
20833   verifyFormat(
20834       "void f() {\n"
20835       "  other.other.other.other.other(\n"
20836       "      x.begin(), x.end(),\n"
20837       "      [something, rather](int, int, int, int, int, int, int) {\n"
20838       "        //\n"
20839       "      });\n"
20840       "}\n");
20841   verifyFormat("SomeFunction([]() { // A cool function...\n"
20842                "  return 43;\n"
20843                "});");
20844   EXPECT_EQ("SomeFunction([]() {\n"
20845             "#define A a\n"
20846             "  return 43;\n"
20847             "});",
20848             format("SomeFunction([](){\n"
20849                    "#define A a\n"
20850                    "return 43;\n"
20851                    "});"));
20852   verifyFormat("void f() {\n"
20853                "  SomeFunction([](decltype(x), A *a) {});\n"
20854                "  SomeFunction([](typeof(x), A *a) {});\n"
20855                "  SomeFunction([](_Atomic(x), A *a) {});\n"
20856                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
20857                "}");
20858   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20859                "    [](const aaaaaaaaaa &a) { return a; });");
20860   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
20861                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
20862                "});");
20863   verifyFormat("Constructor()\n"
20864                "    : Field([] { // comment\n"
20865                "        int i;\n"
20866                "      }) {}");
20867   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
20868                "  return some_parameter.size();\n"
20869                "};");
20870   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
20871                "    [](const string &s) { return s; };");
20872   verifyFormat("int i = aaaaaa ? 1 //\n"
20873                "               : [] {\n"
20874                "                   return 2; //\n"
20875                "                 }();");
20876   verifyFormat("llvm::errs() << \"number of twos is \"\n"
20877                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
20878                "                  return x == 2; // force break\n"
20879                "                });");
20880   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20881                "    [=](int iiiiiiiiiiii) {\n"
20882                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
20883                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
20884                "    });",
20885                getLLVMStyleWithColumns(60));
20886 
20887   verifyFormat("SomeFunction({[&] {\n"
20888                "                // comment\n"
20889                "              },\n"
20890                "              [&] {\n"
20891                "                // comment\n"
20892                "              }});");
20893   verifyFormat("SomeFunction({[&] {\n"
20894                "  // comment\n"
20895                "}});");
20896   verifyFormat(
20897       "virtual aaaaaaaaaaaaaaaa(\n"
20898       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
20899       "    aaaaa aaaaaaaaa);");
20900 
20901   // Lambdas with return types.
20902   verifyFormat("int c = []() -> int { return 2; }();\n");
20903   verifyFormat("int c = []() -> int * { return 2; }();\n");
20904   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
20905   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
20906   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
20907   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
20908   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
20909   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
20910   verifyFormat("[a, a]() -> a<1> {};");
20911   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
20912   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
20913   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
20914   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
20915   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
20916   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
20917   verifyFormat("[]() -> foo<!5> { return {}; };");
20918   verifyFormat("[]() -> foo<~5> { return {}; };");
20919   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
20920   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
20921   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
20922   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
20923   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
20924   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
20925   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
20926   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
20927   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
20928   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
20929   verifyFormat("namespace bar {\n"
20930                "// broken:\n"
20931                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
20932                "} // namespace bar");
20933   verifyFormat("namespace bar {\n"
20934                "// broken:\n"
20935                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
20936                "} // namespace bar");
20937   verifyFormat("namespace bar {\n"
20938                "// broken:\n"
20939                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
20940                "} // namespace bar");
20941   verifyFormat("namespace bar {\n"
20942                "// broken:\n"
20943                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
20944                "} // namespace bar");
20945   verifyFormat("namespace bar {\n"
20946                "// broken:\n"
20947                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
20948                "} // namespace bar");
20949   verifyFormat("namespace bar {\n"
20950                "// broken:\n"
20951                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
20952                "} // namespace bar");
20953   verifyFormat("namespace bar {\n"
20954                "// broken:\n"
20955                "auto foo{[]() -> foo<!5> { return {}; }};\n"
20956                "} // namespace bar");
20957   verifyFormat("namespace bar {\n"
20958                "// broken:\n"
20959                "auto foo{[]() -> foo<~5> { return {}; }};\n"
20960                "} // namespace bar");
20961   verifyFormat("namespace bar {\n"
20962                "// broken:\n"
20963                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
20964                "} // namespace bar");
20965   verifyFormat("namespace bar {\n"
20966                "// broken:\n"
20967                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
20968                "} // namespace bar");
20969   verifyFormat("namespace bar {\n"
20970                "// broken:\n"
20971                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
20972                "} // namespace bar");
20973   verifyFormat("namespace bar {\n"
20974                "// broken:\n"
20975                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
20976                "} // namespace bar");
20977   verifyFormat("namespace bar {\n"
20978                "// broken:\n"
20979                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
20980                "} // namespace bar");
20981   verifyFormat("namespace bar {\n"
20982                "// broken:\n"
20983                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
20984                "} // namespace bar");
20985   verifyFormat("namespace bar {\n"
20986                "// broken:\n"
20987                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
20988                "} // namespace bar");
20989   verifyFormat("namespace bar {\n"
20990                "// broken:\n"
20991                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
20992                "} // namespace bar");
20993   verifyFormat("namespace bar {\n"
20994                "// broken:\n"
20995                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
20996                "} // namespace bar");
20997   verifyFormat("namespace bar {\n"
20998                "// broken:\n"
20999                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21000                "} // namespace bar");
21001   verifyFormat("[]() -> a<1> {};");
21002   verifyFormat("[]() -> a<1> { ; };");
21003   verifyFormat("[]() -> a<1> { ; }();");
21004   verifyFormat("[a, a]() -> a<true> {};");
21005   verifyFormat("[]() -> a<true> {};");
21006   verifyFormat("[]() -> a<true> { ; };");
21007   verifyFormat("[]() -> a<true> { ; }();");
21008   verifyFormat("[a, a]() -> a<false> {};");
21009   verifyFormat("[]() -> a<false> {};");
21010   verifyFormat("[]() -> a<false> { ; };");
21011   verifyFormat("[]() -> a<false> { ; }();");
21012   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21013   verifyFormat("namespace bar {\n"
21014                "auto foo{[]() -> foo<false> { ; }};\n"
21015                "} // namespace bar");
21016   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21017                "                   int j) -> int {\n"
21018                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21019                "};");
21020   verifyFormat(
21021       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21022       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21023       "      return aaaaaaaaaaaaaaaaa;\n"
21024       "    });",
21025       getLLVMStyleWithColumns(70));
21026   verifyFormat("[]() //\n"
21027                "    -> int {\n"
21028                "  return 1; //\n"
21029                "};");
21030   verifyFormat("[]() -> Void<T...> {};");
21031   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21032   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21033   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21034   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21035   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21036   verifyFormat("return int{[x = x]() { return x; }()};");
21037 
21038   // Lambdas with explicit template argument lists.
21039   verifyFormat(
21040       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21041   verifyFormat("auto L = []<class T>(T) {\n"
21042                "  {\n"
21043                "    f();\n"
21044                "    g();\n"
21045                "  }\n"
21046                "};\n");
21047   verifyFormat("auto L = []<class... T>(T...) {\n"
21048                "  {\n"
21049                "    f();\n"
21050                "    g();\n"
21051                "  }\n"
21052                "};\n");
21053   verifyFormat("auto L = []<typename... T>(T...) {\n"
21054                "  {\n"
21055                "    f();\n"
21056                "    g();\n"
21057                "  }\n"
21058                "};\n");
21059   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21060                "  {\n"
21061                "    f();\n"
21062                "    g();\n"
21063                "  }\n"
21064                "};\n");
21065   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21066                "  {\n"
21067                "    f();\n"
21068                "    g();\n"
21069                "  }\n"
21070                "};\n");
21071 
21072   // Multiple lambdas in the same parentheses change indentation rules. These
21073   // lambdas are forced to start on new lines.
21074   verifyFormat("SomeFunction(\n"
21075                "    []() {\n"
21076                "      //\n"
21077                "    },\n"
21078                "    []() {\n"
21079                "      //\n"
21080                "    });");
21081 
21082   // A lambda passed as arg0 is always pushed to the next line.
21083   verifyFormat("SomeFunction(\n"
21084                "    [this] {\n"
21085                "      //\n"
21086                "    },\n"
21087                "    1);\n");
21088 
21089   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21090   // the arg0 case above.
21091   auto Style = getGoogleStyle();
21092   Style.BinPackArguments = false;
21093   verifyFormat("SomeFunction(\n"
21094                "    a,\n"
21095                "    [this] {\n"
21096                "      //\n"
21097                "    },\n"
21098                "    b);\n",
21099                Style);
21100   verifyFormat("SomeFunction(\n"
21101                "    a,\n"
21102                "    [this] {\n"
21103                "      //\n"
21104                "    },\n"
21105                "    b);\n");
21106 
21107   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21108   // the BinPackArguments value (as long as the code is wide enough).
21109   verifyFormat(
21110       "something->SomeFunction(\n"
21111       "    a,\n"
21112       "    [this] {\n"
21113       "      "
21114       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21115       "    },\n"
21116       "    b);\n");
21117 
21118   // A multi-line lambda is pulled up as long as the introducer fits on the
21119   // previous line and there are no further args.
21120   verifyFormat("function(1, [this, that] {\n"
21121                "  //\n"
21122                "});\n");
21123   verifyFormat("function([this, that] {\n"
21124                "  //\n"
21125                "});\n");
21126   // FIXME: this format is not ideal and we should consider forcing the first
21127   // arg onto its own line.
21128   verifyFormat("function(a, b, c, //\n"
21129                "         d, [this, that] {\n"
21130                "           //\n"
21131                "         });\n");
21132 
21133   // Multiple lambdas are treated correctly even when there is a short arg0.
21134   verifyFormat("SomeFunction(\n"
21135                "    1,\n"
21136                "    [this] {\n"
21137                "      //\n"
21138                "    },\n"
21139                "    [this] {\n"
21140                "      //\n"
21141                "    },\n"
21142                "    1);\n");
21143 
21144   // More complex introducers.
21145   verifyFormat("return [i, args...] {};");
21146 
21147   // Not lambdas.
21148   verifyFormat("constexpr char hello[]{\"hello\"};");
21149   verifyFormat("double &operator[](int i) { return 0; }\n"
21150                "int i;");
21151   verifyFormat("std::unique_ptr<int[]> foo() {}");
21152   verifyFormat("int i = a[a][a]->f();");
21153   verifyFormat("int i = (*b)[a]->f();");
21154 
21155   // Other corner cases.
21156   verifyFormat("void f() {\n"
21157                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21158                "  );\n"
21159                "}");
21160 
21161   // Lambdas created through weird macros.
21162   verifyFormat("void f() {\n"
21163                "  MACRO((const AA &a) { return 1; });\n"
21164                "  MACRO((AA &a) { return 1; });\n"
21165                "}");
21166 
21167   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21168                "      doo_dah();\n"
21169                "      doo_dah();\n"
21170                "    })) {\n"
21171                "}");
21172   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21173                "                doo_dah();\n"
21174                "                doo_dah();\n"
21175                "              })) {\n"
21176                "}");
21177   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21178                "                doo_dah();\n"
21179                "                doo_dah();\n"
21180                "              })) {\n"
21181                "}");
21182   verifyFormat("auto lambda = []() {\n"
21183                "  int a = 2\n"
21184                "#if A\n"
21185                "          + 2\n"
21186                "#endif\n"
21187                "      ;\n"
21188                "};");
21189 
21190   // Lambdas with complex multiline introducers.
21191   verifyFormat(
21192       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21193       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21194       "        -> ::std::unordered_set<\n"
21195       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21196       "      //\n"
21197       "    });");
21198 
21199   FormatStyle DoNotMerge = getLLVMStyle();
21200   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21201   verifyFormat("auto c = []() {\n"
21202                "  return b;\n"
21203                "};",
21204                "auto c = []() { return b; };", DoNotMerge);
21205   verifyFormat("auto c = []() {\n"
21206                "};",
21207                " auto c = []() {};", DoNotMerge);
21208 
21209   FormatStyle MergeEmptyOnly = getLLVMStyle();
21210   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21211   verifyFormat("auto c = []() {\n"
21212                "  return b;\n"
21213                "};",
21214                "auto c = []() {\n"
21215                "  return b;\n"
21216                " };",
21217                MergeEmptyOnly);
21218   verifyFormat("auto c = []() {};",
21219                "auto c = []() {\n"
21220                "};",
21221                MergeEmptyOnly);
21222 
21223   FormatStyle MergeInline = getLLVMStyle();
21224   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21225   verifyFormat("auto c = []() {\n"
21226                "  return b;\n"
21227                "};",
21228                "auto c = []() { return b; };", MergeInline);
21229   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21230                MergeInline);
21231   verifyFormat("function([]() { return b; }, a)",
21232                "function([]() { return b; }, a)", MergeInline);
21233   verifyFormat("function(a, []() { return b; })",
21234                "function(a, []() { return b; })", MergeInline);
21235 
21236   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21237   // AllowShortLambdasOnASingleLine
21238   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21239   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21240   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21241   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21242       FormatStyle::ShortLambdaStyle::SLS_None;
21243   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21244                "    []()\n"
21245                "    {\n"
21246                "      return 17;\n"
21247                "    });",
21248                LLVMWithBeforeLambdaBody);
21249   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21250                "    []()\n"
21251                "    {\n"
21252                "    });",
21253                LLVMWithBeforeLambdaBody);
21254   verifyFormat("auto fct_SLS_None = []()\n"
21255                "{\n"
21256                "  return 17;\n"
21257                "};",
21258                LLVMWithBeforeLambdaBody);
21259   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21260                "    []()\n"
21261                "    {\n"
21262                "      return Call(\n"
21263                "          []()\n"
21264                "          {\n"
21265                "            return 17;\n"
21266                "          });\n"
21267                "    });",
21268                LLVMWithBeforeLambdaBody);
21269   verifyFormat("void Fct() {\n"
21270                "  return {[]()\n"
21271                "          {\n"
21272                "            return 17;\n"
21273                "          }};\n"
21274                "}",
21275                LLVMWithBeforeLambdaBody);
21276 
21277   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21278       FormatStyle::ShortLambdaStyle::SLS_Empty;
21279   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21280                "    []()\n"
21281                "    {\n"
21282                "      return 17;\n"
21283                "    });",
21284                LLVMWithBeforeLambdaBody);
21285   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21286                LLVMWithBeforeLambdaBody);
21287   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21288                "ongFunctionName_SLS_Empty(\n"
21289                "    []() {});",
21290                LLVMWithBeforeLambdaBody);
21291   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21292                "                                []()\n"
21293                "                                {\n"
21294                "                                  return 17;\n"
21295                "                                });",
21296                LLVMWithBeforeLambdaBody);
21297   verifyFormat("auto fct_SLS_Empty = []()\n"
21298                "{\n"
21299                "  return 17;\n"
21300                "};",
21301                LLVMWithBeforeLambdaBody);
21302   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21303                "    []()\n"
21304                "    {\n"
21305                "      return Call([]() {});\n"
21306                "    });",
21307                LLVMWithBeforeLambdaBody);
21308   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21309                "                           []()\n"
21310                "                           {\n"
21311                "                             return Call([]() {});\n"
21312                "                           });",
21313                LLVMWithBeforeLambdaBody);
21314   verifyFormat(
21315       "FctWithLongLineInLambda_SLS_Empty(\n"
21316       "    []()\n"
21317       "    {\n"
21318       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21319       "                               AndShouldNotBeConsiderAsInline,\n"
21320       "                               LambdaBodyMustBeBreak);\n"
21321       "    });",
21322       LLVMWithBeforeLambdaBody);
21323 
21324   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21325       FormatStyle::ShortLambdaStyle::SLS_Inline;
21326   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21327                LLVMWithBeforeLambdaBody);
21328   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21329                LLVMWithBeforeLambdaBody);
21330   verifyFormat("auto fct_SLS_Inline = []()\n"
21331                "{\n"
21332                "  return 17;\n"
21333                "};",
21334                LLVMWithBeforeLambdaBody);
21335   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21336                "17; }); });",
21337                LLVMWithBeforeLambdaBody);
21338   verifyFormat(
21339       "FctWithLongLineInLambda_SLS_Inline(\n"
21340       "    []()\n"
21341       "    {\n"
21342       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21343       "                               AndShouldNotBeConsiderAsInline,\n"
21344       "                               LambdaBodyMustBeBreak);\n"
21345       "    });",
21346       LLVMWithBeforeLambdaBody);
21347   verifyFormat("FctWithMultipleParams_SLS_Inline("
21348                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21349                "                                 []() { return 17; });",
21350                LLVMWithBeforeLambdaBody);
21351   verifyFormat(
21352       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21353       LLVMWithBeforeLambdaBody);
21354 
21355   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21356       FormatStyle::ShortLambdaStyle::SLS_All;
21357   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21358                LLVMWithBeforeLambdaBody);
21359   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21360                LLVMWithBeforeLambdaBody);
21361   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21362                LLVMWithBeforeLambdaBody);
21363   verifyFormat("FctWithOneParam_SLS_All(\n"
21364                "    []()\n"
21365                "    {\n"
21366                "      // A cool function...\n"
21367                "      return 43;\n"
21368                "    });",
21369                LLVMWithBeforeLambdaBody);
21370   verifyFormat("FctWithMultipleParams_SLS_All("
21371                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21372                "                              []() { return 17; });",
21373                LLVMWithBeforeLambdaBody);
21374   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21375                LLVMWithBeforeLambdaBody);
21376   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21377                LLVMWithBeforeLambdaBody);
21378   verifyFormat(
21379       "FctWithLongLineInLambda_SLS_All(\n"
21380       "    []()\n"
21381       "    {\n"
21382       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21383       "                               AndShouldNotBeConsiderAsInline,\n"
21384       "                               LambdaBodyMustBeBreak);\n"
21385       "    });",
21386       LLVMWithBeforeLambdaBody);
21387   verifyFormat(
21388       "auto fct_SLS_All = []()\n"
21389       "{\n"
21390       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21391       "                           AndShouldNotBeConsiderAsInline,\n"
21392       "                           LambdaBodyMustBeBreak);\n"
21393       "};",
21394       LLVMWithBeforeLambdaBody);
21395   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21396   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21397                LLVMWithBeforeLambdaBody);
21398   verifyFormat(
21399       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21400       "                                FirstParam,\n"
21401       "                                SecondParam,\n"
21402       "                                ThirdParam,\n"
21403       "                                FourthParam);",
21404       LLVMWithBeforeLambdaBody);
21405   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21406                "    []() { return "
21407                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21408                "    FirstParam,\n"
21409                "    SecondParam,\n"
21410                "    ThirdParam,\n"
21411                "    FourthParam);",
21412                LLVMWithBeforeLambdaBody);
21413   verifyFormat(
21414       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21415       "                                SecondParam,\n"
21416       "                                ThirdParam,\n"
21417       "                                FourthParam,\n"
21418       "                                []() { return SomeValueNotSoLong; });",
21419       LLVMWithBeforeLambdaBody);
21420   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21421                "    []()\n"
21422                "    {\n"
21423                "      return "
21424                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21425                "eConsiderAsInline;\n"
21426                "    });",
21427                LLVMWithBeforeLambdaBody);
21428   verifyFormat(
21429       "FctWithLongLineInLambda_SLS_All(\n"
21430       "    []()\n"
21431       "    {\n"
21432       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21433       "                               AndShouldNotBeConsiderAsInline,\n"
21434       "                               LambdaBodyMustBeBreak);\n"
21435       "    });",
21436       LLVMWithBeforeLambdaBody);
21437   verifyFormat("FctWithTwoParams_SLS_All(\n"
21438                "    []()\n"
21439                "    {\n"
21440                "      // A cool function...\n"
21441                "      return 43;\n"
21442                "    },\n"
21443                "    87);",
21444                LLVMWithBeforeLambdaBody);
21445   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
21446                LLVMWithBeforeLambdaBody);
21447   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
21448                LLVMWithBeforeLambdaBody);
21449   verifyFormat(
21450       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
21451       LLVMWithBeforeLambdaBody);
21452   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
21453                "}); }, x);",
21454                LLVMWithBeforeLambdaBody);
21455   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21456                "    []()\n"
21457                "    {\n"
21458                "      // A cool function...\n"
21459                "      return Call([]() { return 17; });\n"
21460                "    });",
21461                LLVMWithBeforeLambdaBody);
21462   verifyFormat("TwoNestedLambdas_SLS_All(\n"
21463                "    []()\n"
21464                "    {\n"
21465                "      return Call(\n"
21466                "          []()\n"
21467                "          {\n"
21468                "            // A cool function...\n"
21469                "            return 17;\n"
21470                "          });\n"
21471                "    });",
21472                LLVMWithBeforeLambdaBody);
21473 
21474   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21475       FormatStyle::ShortLambdaStyle::SLS_None;
21476 
21477   verifyFormat("auto select = [this]() -> const Library::Object *\n"
21478                "{\n"
21479                "  return MyAssignment::SelectFromList(this);\n"
21480                "};\n",
21481                LLVMWithBeforeLambdaBody);
21482 
21483   verifyFormat("auto select = [this]() -> const Library::Object &\n"
21484                "{\n"
21485                "  return MyAssignment::SelectFromList(this);\n"
21486                "};\n",
21487                LLVMWithBeforeLambdaBody);
21488 
21489   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
21490                "{\n"
21491                "  return MyAssignment::SelectFromList(this);\n"
21492                "};\n",
21493                LLVMWithBeforeLambdaBody);
21494 
21495   verifyFormat("namespace test {\n"
21496                "class Test {\n"
21497                "public:\n"
21498                "  Test() = default;\n"
21499                "};\n"
21500                "} // namespace test",
21501                LLVMWithBeforeLambdaBody);
21502 
21503   // Lambdas with different indentation styles.
21504   Style = getLLVMStyleWithColumns(100);
21505   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21506             "  return promise.then(\n"
21507             "      [this, &someVariable, someObject = "
21508             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21509             "        return someObject.startAsyncAction().then(\n"
21510             "            [this, &someVariable](AsyncActionResult result) "
21511             "mutable { result.processMore(); });\n"
21512             "      });\n"
21513             "}\n",
21514             format("SomeResult doSomething(SomeObject promise) {\n"
21515                    "  return promise.then([this, &someVariable, someObject = "
21516                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21517                    "    return someObject.startAsyncAction().then([this, "
21518                    "&someVariable](AsyncActionResult result) mutable {\n"
21519                    "      result.processMore();\n"
21520                    "    });\n"
21521                    "  });\n"
21522                    "}\n",
21523                    Style));
21524   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21525   verifyFormat("test() {\n"
21526                "  ([]() -> {\n"
21527                "    int b = 32;\n"
21528                "    return 3;\n"
21529                "  }).foo();\n"
21530                "}",
21531                Style);
21532   verifyFormat("test() {\n"
21533                "  []() -> {\n"
21534                "    int b = 32;\n"
21535                "    return 3;\n"
21536                "  }\n"
21537                "}",
21538                Style);
21539   verifyFormat("std::sort(v.begin(), v.end(),\n"
21540                "          [](const auto &someLongArgumentName, const auto "
21541                "&someOtherLongArgumentName) {\n"
21542                "  return someLongArgumentName.someMemberVariable < "
21543                "someOtherLongArgumentName.someMemberVariable;\n"
21544                "});",
21545                Style);
21546   verifyFormat("test() {\n"
21547                "  (\n"
21548                "      []() -> {\n"
21549                "        int b = 32;\n"
21550                "        return 3;\n"
21551                "      },\n"
21552                "      foo, bar)\n"
21553                "      .foo();\n"
21554                "}",
21555                Style);
21556   verifyFormat("test() {\n"
21557                "  ([]() -> {\n"
21558                "    int b = 32;\n"
21559                "    return 3;\n"
21560                "  })\n"
21561                "      .foo()\n"
21562                "      .bar();\n"
21563                "}",
21564                Style);
21565   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21566             "  return promise.then(\n"
21567             "      [this, &someVariable, someObject = "
21568             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21569             "    return someObject.startAsyncAction().then(\n"
21570             "        [this, &someVariable](AsyncActionResult result) mutable { "
21571             "result.processMore(); });\n"
21572             "  });\n"
21573             "}\n",
21574             format("SomeResult doSomething(SomeObject promise) {\n"
21575                    "  return promise.then([this, &someVariable, someObject = "
21576                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
21577                    "    return someObject.startAsyncAction().then([this, "
21578                    "&someVariable](AsyncActionResult result) mutable {\n"
21579                    "      result.processMore();\n"
21580                    "    });\n"
21581                    "  });\n"
21582                    "}\n",
21583                    Style));
21584   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
21585             "  return promise.then([this, &someVariable] {\n"
21586             "    return someObject.startAsyncAction().then(\n"
21587             "        [this, &someVariable](AsyncActionResult result) mutable { "
21588             "result.processMore(); });\n"
21589             "  });\n"
21590             "}\n",
21591             format("SomeResult doSomething(SomeObject promise) {\n"
21592                    "  return promise.then([this, &someVariable] {\n"
21593                    "    return someObject.startAsyncAction().then([this, "
21594                    "&someVariable](AsyncActionResult result) mutable {\n"
21595                    "      result.processMore();\n"
21596                    "    });\n"
21597                    "  });\n"
21598                    "}\n",
21599                    Style));
21600   Style = getGoogleStyle();
21601   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
21602   EXPECT_EQ("#define A                                       \\\n"
21603             "  [] {                                          \\\n"
21604             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
21605             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
21606             "      }",
21607             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
21608                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
21609                    Style));
21610   // TODO: The current formatting has a minor issue that's not worth fixing
21611   // right now whereby the closing brace is indented relative to the signature
21612   // instead of being aligned. This only happens with macros.
21613 }
21614 
21615 TEST_F(FormatTest, LambdaWithLineComments) {
21616   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21617   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21618   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21619   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21620       FormatStyle::ShortLambdaStyle::SLS_All;
21621 
21622   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
21623   verifyFormat("auto k = []() // comment\n"
21624                "{ return; }",
21625                LLVMWithBeforeLambdaBody);
21626   verifyFormat("auto k = []() /* comment */ { return; }",
21627                LLVMWithBeforeLambdaBody);
21628   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
21629                LLVMWithBeforeLambdaBody);
21630   verifyFormat("auto k = []() // X\n"
21631                "{ return; }",
21632                LLVMWithBeforeLambdaBody);
21633   verifyFormat(
21634       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
21635       "{ return; }",
21636       LLVMWithBeforeLambdaBody);
21637 }
21638 
21639 TEST_F(FormatTest, EmptyLinesInLambdas) {
21640   verifyFormat("auto lambda = []() {\n"
21641                "  x(); //\n"
21642                "};",
21643                "auto lambda = []() {\n"
21644                "\n"
21645                "  x(); //\n"
21646                "\n"
21647                "};");
21648 }
21649 
21650 TEST_F(FormatTest, FormatsBlocks) {
21651   FormatStyle ShortBlocks = getLLVMStyle();
21652   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21653   verifyFormat("int (^Block)(int, int);", ShortBlocks);
21654   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
21655   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
21656   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
21657   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
21658   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
21659 
21660   verifyFormat("foo(^{ bar(); });", ShortBlocks);
21661   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
21662   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
21663 
21664   verifyFormat("[operation setCompletionBlock:^{\n"
21665                "  [self onOperationDone];\n"
21666                "}];");
21667   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
21668                "  [self onOperationDone];\n"
21669                "}]};");
21670   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
21671                "  f();\n"
21672                "}];");
21673   verifyFormat("int a = [operation block:^int(int *i) {\n"
21674                "  return 1;\n"
21675                "}];");
21676   verifyFormat("[myObject doSomethingWith:arg1\n"
21677                "                      aaa:^int(int *a) {\n"
21678                "                        return 1;\n"
21679                "                      }\n"
21680                "                      bbb:f(a * bbbbbbbb)];");
21681 
21682   verifyFormat("[operation setCompletionBlock:^{\n"
21683                "  [self.delegate newDataAvailable];\n"
21684                "}];",
21685                getLLVMStyleWithColumns(60));
21686   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
21687                "  NSString *path = [self sessionFilePath];\n"
21688                "  if (path) {\n"
21689                "    // ...\n"
21690                "  }\n"
21691                "});");
21692   verifyFormat("[[SessionService sharedService]\n"
21693                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21694                "      if (window) {\n"
21695                "        [self windowDidLoad:window];\n"
21696                "      } else {\n"
21697                "        [self errorLoadingWindow];\n"
21698                "      }\n"
21699                "    }];");
21700   verifyFormat("void (^largeBlock)(void) = ^{\n"
21701                "  // ...\n"
21702                "};\n",
21703                getLLVMStyleWithColumns(40));
21704   verifyFormat("[[SessionService sharedService]\n"
21705                "    loadWindowWithCompletionBlock: //\n"
21706                "        ^(SessionWindow *window) {\n"
21707                "          if (window) {\n"
21708                "            [self windowDidLoad:window];\n"
21709                "          } else {\n"
21710                "            [self errorLoadingWindow];\n"
21711                "          }\n"
21712                "        }];",
21713                getLLVMStyleWithColumns(60));
21714   verifyFormat("[myObject doSomethingWith:arg1\n"
21715                "    firstBlock:^(Foo *a) {\n"
21716                "      // ...\n"
21717                "      int i;\n"
21718                "    }\n"
21719                "    secondBlock:^(Bar *b) {\n"
21720                "      // ...\n"
21721                "      int i;\n"
21722                "    }\n"
21723                "    thirdBlock:^Foo(Bar *b) {\n"
21724                "      // ...\n"
21725                "      int i;\n"
21726                "    }];");
21727   verifyFormat("[myObject doSomethingWith:arg1\n"
21728                "               firstBlock:-1\n"
21729                "              secondBlock:^(Bar *b) {\n"
21730                "                // ...\n"
21731                "                int i;\n"
21732                "              }];");
21733 
21734   verifyFormat("f(^{\n"
21735                "  @autoreleasepool {\n"
21736                "    if (a) {\n"
21737                "      g();\n"
21738                "    }\n"
21739                "  }\n"
21740                "});");
21741   verifyFormat("Block b = ^int *(A *a, B *b) {}");
21742   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
21743                "};");
21744 
21745   FormatStyle FourIndent = getLLVMStyle();
21746   FourIndent.ObjCBlockIndentWidth = 4;
21747   verifyFormat("[operation setCompletionBlock:^{\n"
21748                "    [self onOperationDone];\n"
21749                "}];",
21750                FourIndent);
21751 }
21752 
21753 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
21754   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
21755 
21756   verifyFormat("[[SessionService sharedService] "
21757                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21758                "  if (window) {\n"
21759                "    [self windowDidLoad:window];\n"
21760                "  } else {\n"
21761                "    [self errorLoadingWindow];\n"
21762                "  }\n"
21763                "}];",
21764                ZeroColumn);
21765   EXPECT_EQ("[[SessionService sharedService]\n"
21766             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21767             "      if (window) {\n"
21768             "        [self windowDidLoad:window];\n"
21769             "      } else {\n"
21770             "        [self errorLoadingWindow];\n"
21771             "      }\n"
21772             "    }];",
21773             format("[[SessionService sharedService]\n"
21774                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21775                    "                if (window) {\n"
21776                    "    [self windowDidLoad:window];\n"
21777                    "  } else {\n"
21778                    "    [self errorLoadingWindow];\n"
21779                    "  }\n"
21780                    "}];",
21781                    ZeroColumn));
21782   verifyFormat("[myObject doSomethingWith:arg1\n"
21783                "    firstBlock:^(Foo *a) {\n"
21784                "      // ...\n"
21785                "      int i;\n"
21786                "    }\n"
21787                "    secondBlock:^(Bar *b) {\n"
21788                "      // ...\n"
21789                "      int i;\n"
21790                "    }\n"
21791                "    thirdBlock:^Foo(Bar *b) {\n"
21792                "      // ...\n"
21793                "      int i;\n"
21794                "    }];",
21795                ZeroColumn);
21796   verifyFormat("f(^{\n"
21797                "  @autoreleasepool {\n"
21798                "    if (a) {\n"
21799                "      g();\n"
21800                "    }\n"
21801                "  }\n"
21802                "});",
21803                ZeroColumn);
21804   verifyFormat("void (^largeBlock)(void) = ^{\n"
21805                "  // ...\n"
21806                "};",
21807                ZeroColumn);
21808 
21809   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21810   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
21811             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21812   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
21813   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
21814             "  int i;\n"
21815             "};",
21816             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21817 }
21818 
21819 TEST_F(FormatTest, SupportsCRLF) {
21820   EXPECT_EQ("int a;\r\n"
21821             "int b;\r\n"
21822             "int c;\r\n",
21823             format("int a;\r\n"
21824                    "  int b;\r\n"
21825                    "    int c;\r\n",
21826                    getLLVMStyle()));
21827   EXPECT_EQ("int a;\r\n"
21828             "int b;\r\n"
21829             "int c;\r\n",
21830             format("int a;\r\n"
21831                    "  int b;\n"
21832                    "    int c;\r\n",
21833                    getLLVMStyle()));
21834   EXPECT_EQ("int a;\n"
21835             "int b;\n"
21836             "int c;\n",
21837             format("int a;\r\n"
21838                    "  int b;\n"
21839                    "    int c;\n",
21840                    getLLVMStyle()));
21841   EXPECT_EQ("\"aaaaaaa \"\r\n"
21842             "\"bbbbbbb\";\r\n",
21843             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
21844   EXPECT_EQ("#define A \\\r\n"
21845             "  b;      \\\r\n"
21846             "  c;      \\\r\n"
21847             "  d;\r\n",
21848             format("#define A \\\r\n"
21849                    "  b; \\\r\n"
21850                    "  c; d; \r\n",
21851                    getGoogleStyle()));
21852 
21853   EXPECT_EQ("/*\r\n"
21854             "multi line block comments\r\n"
21855             "should not introduce\r\n"
21856             "an extra carriage return\r\n"
21857             "*/\r\n",
21858             format("/*\r\n"
21859                    "multi line block comments\r\n"
21860                    "should not introduce\r\n"
21861                    "an extra carriage return\r\n"
21862                    "*/\r\n"));
21863   EXPECT_EQ("/*\r\n"
21864             "\r\n"
21865             "*/",
21866             format("/*\r\n"
21867                    "    \r\r\r\n"
21868                    "*/"));
21869 
21870   FormatStyle style = getLLVMStyle();
21871 
21872   style.DeriveLineEnding = true;
21873   style.UseCRLF = false;
21874   EXPECT_EQ("union FooBarBazQux {\n"
21875             "  int foo;\n"
21876             "  int bar;\n"
21877             "  int baz;\n"
21878             "};",
21879             format("union FooBarBazQux {\r\n"
21880                    "  int foo;\n"
21881                    "  int bar;\r\n"
21882                    "  int baz;\n"
21883                    "};",
21884                    style));
21885   style.UseCRLF = true;
21886   EXPECT_EQ("union FooBarBazQux {\r\n"
21887             "  int foo;\r\n"
21888             "  int bar;\r\n"
21889             "  int baz;\r\n"
21890             "};",
21891             format("union FooBarBazQux {\r\n"
21892                    "  int foo;\n"
21893                    "  int bar;\r\n"
21894                    "  int baz;\n"
21895                    "};",
21896                    style));
21897 
21898   style.DeriveLineEnding = false;
21899   style.UseCRLF = false;
21900   EXPECT_EQ("union FooBarBazQux {\n"
21901             "  int foo;\n"
21902             "  int bar;\n"
21903             "  int baz;\n"
21904             "  int qux;\n"
21905             "};",
21906             format("union FooBarBazQux {\r\n"
21907                    "  int foo;\n"
21908                    "  int bar;\r\n"
21909                    "  int baz;\n"
21910                    "  int qux;\r\n"
21911                    "};",
21912                    style));
21913   style.UseCRLF = true;
21914   EXPECT_EQ("union FooBarBazQux {\r\n"
21915             "  int foo;\r\n"
21916             "  int bar;\r\n"
21917             "  int baz;\r\n"
21918             "  int qux;\r\n"
21919             "};",
21920             format("union FooBarBazQux {\r\n"
21921                    "  int foo;\n"
21922                    "  int bar;\r\n"
21923                    "  int baz;\n"
21924                    "  int qux;\n"
21925                    "};",
21926                    style));
21927 
21928   style.DeriveLineEnding = true;
21929   style.UseCRLF = false;
21930   EXPECT_EQ("union FooBarBazQux {\r\n"
21931             "  int foo;\r\n"
21932             "  int bar;\r\n"
21933             "  int baz;\r\n"
21934             "  int qux;\r\n"
21935             "};",
21936             format("union FooBarBazQux {\r\n"
21937                    "  int foo;\n"
21938                    "  int bar;\r\n"
21939                    "  int baz;\n"
21940                    "  int qux;\r\n"
21941                    "};",
21942                    style));
21943   style.UseCRLF = true;
21944   EXPECT_EQ("union FooBarBazQux {\n"
21945             "  int foo;\n"
21946             "  int bar;\n"
21947             "  int baz;\n"
21948             "  int qux;\n"
21949             "};",
21950             format("union FooBarBazQux {\r\n"
21951                    "  int foo;\n"
21952                    "  int bar;\r\n"
21953                    "  int baz;\n"
21954                    "  int qux;\n"
21955                    "};",
21956                    style));
21957 }
21958 
21959 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
21960   verifyFormat("MY_CLASS(C) {\n"
21961                "  int i;\n"
21962                "  int j;\n"
21963                "};");
21964 }
21965 
21966 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
21967   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
21968   TwoIndent.ContinuationIndentWidth = 2;
21969 
21970   EXPECT_EQ("int i =\n"
21971             "  longFunction(\n"
21972             "    arg);",
21973             format("int i = longFunction(arg);", TwoIndent));
21974 
21975   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
21976   SixIndent.ContinuationIndentWidth = 6;
21977 
21978   EXPECT_EQ("int i =\n"
21979             "      longFunction(\n"
21980             "            arg);",
21981             format("int i = longFunction(arg);", SixIndent));
21982 }
21983 
21984 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
21985   FormatStyle Style = getLLVMStyle();
21986   verifyFormat("int Foo::getter(\n"
21987                "    //\n"
21988                ") const {\n"
21989                "  return foo;\n"
21990                "}",
21991                Style);
21992   verifyFormat("void Foo::setter(\n"
21993                "    //\n"
21994                ") {\n"
21995                "  foo = 1;\n"
21996                "}",
21997                Style);
21998 }
21999 
22000 TEST_F(FormatTest, SpacesInAngles) {
22001   FormatStyle Spaces = getLLVMStyle();
22002   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22003 
22004   verifyFormat("vector< ::std::string > x1;", Spaces);
22005   verifyFormat("Foo< int, Bar > x2;", Spaces);
22006   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22007 
22008   verifyFormat("static_cast< int >(arg);", Spaces);
22009   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22010   verifyFormat("f< int, float >();", Spaces);
22011   verifyFormat("template <> g() {}", Spaces);
22012   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22013   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22014   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22015                Spaces);
22016 
22017   Spaces.Standard = FormatStyle::LS_Cpp03;
22018   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22019   verifyFormat("A< A< int > >();", Spaces);
22020 
22021   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22022   verifyFormat("A<A<int> >();", Spaces);
22023 
22024   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22025   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22026                Spaces);
22027   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22028                Spaces);
22029 
22030   verifyFormat("A<A<int> >();", Spaces);
22031   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22032   verifyFormat("A< A< int > >();", Spaces);
22033 
22034   Spaces.Standard = FormatStyle::LS_Cpp11;
22035   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22036   verifyFormat("A< A< int > >();", Spaces);
22037 
22038   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22039   verifyFormat("vector<::std::string> x4;", Spaces);
22040   verifyFormat("vector<int> x5;", Spaces);
22041   verifyFormat("Foo<int, Bar> x6;", Spaces);
22042   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22043 
22044   verifyFormat("A<A<int>>();", Spaces);
22045 
22046   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22047   verifyFormat("vector<::std::string> x4;", Spaces);
22048   verifyFormat("vector< ::std::string > x4;", Spaces);
22049   verifyFormat("vector<int> x5;", Spaces);
22050   verifyFormat("vector< int > x5;", Spaces);
22051   verifyFormat("Foo<int, Bar> x6;", Spaces);
22052   verifyFormat("Foo< int, Bar > x6;", Spaces);
22053   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22054   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22055 
22056   verifyFormat("A<A<int>>();", Spaces);
22057   verifyFormat("A< A< int > >();", Spaces);
22058   verifyFormat("A<A<int > >();", Spaces);
22059   verifyFormat("A< A< int>>();", Spaces);
22060 
22061   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22062   verifyFormat("// clang-format off\n"
22063                "foo<<<1, 1>>>();\n"
22064                "// clang-format on\n",
22065                Spaces);
22066   verifyFormat("// clang-format off\n"
22067                "foo< < <1, 1> > >();\n"
22068                "// clang-format on\n",
22069                Spaces);
22070 }
22071 
22072 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22073   FormatStyle Style = getLLVMStyle();
22074   Style.SpaceAfterTemplateKeyword = false;
22075   verifyFormat("template<int> void foo();", Style);
22076 }
22077 
22078 TEST_F(FormatTest, TripleAngleBrackets) {
22079   verifyFormat("f<<<1, 1>>>();");
22080   verifyFormat("f<<<1, 1, 1, s>>>();");
22081   verifyFormat("f<<<a, b, c, d>>>();");
22082   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22083   verifyFormat("f<param><<<1, 1>>>();");
22084   verifyFormat("f<1><<<1, 1>>>();");
22085   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22086   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22087                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22088   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22089                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22090 }
22091 
22092 TEST_F(FormatTest, MergeLessLessAtEnd) {
22093   verifyFormat("<<");
22094   EXPECT_EQ("< < <", format("\\\n<<<"));
22095   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22096                "aaallvm::outs() <<");
22097   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22098                "aaaallvm::outs()\n    <<");
22099 }
22100 
22101 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22102   std::string code = "#if A\n"
22103                      "#if B\n"
22104                      "a.\n"
22105                      "#endif\n"
22106                      "    a = 1;\n"
22107                      "#else\n"
22108                      "#endif\n"
22109                      "#if C\n"
22110                      "#else\n"
22111                      "#endif\n";
22112   EXPECT_EQ(code, format(code));
22113 }
22114 
22115 TEST_F(FormatTest, HandleConflictMarkers) {
22116   // Git/SVN conflict markers.
22117   EXPECT_EQ("int a;\n"
22118             "void f() {\n"
22119             "  callme(some(parameter1,\n"
22120             "<<<<<<< text by the vcs\n"
22121             "              parameter2),\n"
22122             "||||||| text by the vcs\n"
22123             "              parameter2),\n"
22124             "         parameter3,\n"
22125             "======= text by the vcs\n"
22126             "              parameter2, parameter3),\n"
22127             ">>>>>>> text by the vcs\n"
22128             "         otherparameter);\n",
22129             format("int a;\n"
22130                    "void f() {\n"
22131                    "  callme(some(parameter1,\n"
22132                    "<<<<<<< text by the vcs\n"
22133                    "  parameter2),\n"
22134                    "||||||| text by the vcs\n"
22135                    "  parameter2),\n"
22136                    "  parameter3,\n"
22137                    "======= text by the vcs\n"
22138                    "  parameter2,\n"
22139                    "  parameter3),\n"
22140                    ">>>>>>> text by the vcs\n"
22141                    "  otherparameter);\n"));
22142 
22143   // Perforce markers.
22144   EXPECT_EQ("void f() {\n"
22145             "  function(\n"
22146             ">>>> text by the vcs\n"
22147             "      parameter,\n"
22148             "==== text by the vcs\n"
22149             "      parameter,\n"
22150             "==== text by the vcs\n"
22151             "      parameter,\n"
22152             "<<<< text by the vcs\n"
22153             "      parameter);\n",
22154             format("void f() {\n"
22155                    "  function(\n"
22156                    ">>>> text by the vcs\n"
22157                    "  parameter,\n"
22158                    "==== text by the vcs\n"
22159                    "  parameter,\n"
22160                    "==== text by the vcs\n"
22161                    "  parameter,\n"
22162                    "<<<< text by the vcs\n"
22163                    "  parameter);\n"));
22164 
22165   EXPECT_EQ("<<<<<<<\n"
22166             "|||||||\n"
22167             "=======\n"
22168             ">>>>>>>",
22169             format("<<<<<<<\n"
22170                    "|||||||\n"
22171                    "=======\n"
22172                    ">>>>>>>"));
22173 
22174   EXPECT_EQ("<<<<<<<\n"
22175             "|||||||\n"
22176             "int i;\n"
22177             "=======\n"
22178             ">>>>>>>",
22179             format("<<<<<<<\n"
22180                    "|||||||\n"
22181                    "int i;\n"
22182                    "=======\n"
22183                    ">>>>>>>"));
22184 
22185   // FIXME: Handle parsing of macros around conflict markers correctly:
22186   EXPECT_EQ("#define Macro \\\n"
22187             "<<<<<<<\n"
22188             "Something \\\n"
22189             "|||||||\n"
22190             "Else \\\n"
22191             "=======\n"
22192             "Other \\\n"
22193             ">>>>>>>\n"
22194             "    End int i;\n",
22195             format("#define Macro \\\n"
22196                    "<<<<<<<\n"
22197                    "  Something \\\n"
22198                    "|||||||\n"
22199                    "  Else \\\n"
22200                    "=======\n"
22201                    "  Other \\\n"
22202                    ">>>>>>>\n"
22203                    "  End\n"
22204                    "int i;\n"));
22205 
22206   verifyFormat(R"(====
22207 #ifdef A
22208 a
22209 #else
22210 b
22211 #endif
22212 )");
22213 }
22214 
22215 TEST_F(FormatTest, DisableRegions) {
22216   EXPECT_EQ("int i;\n"
22217             "// clang-format off\n"
22218             "  int j;\n"
22219             "// clang-format on\n"
22220             "int k;",
22221             format(" int  i;\n"
22222                    "   // clang-format off\n"
22223                    "  int j;\n"
22224                    " // clang-format on\n"
22225                    "   int   k;"));
22226   EXPECT_EQ("int i;\n"
22227             "/* clang-format off */\n"
22228             "  int j;\n"
22229             "/* clang-format on */\n"
22230             "int k;",
22231             format(" int  i;\n"
22232                    "   /* clang-format off */\n"
22233                    "  int j;\n"
22234                    " /* clang-format on */\n"
22235                    "   int   k;"));
22236 
22237   // Don't reflow comments within disabled regions.
22238   EXPECT_EQ("// clang-format off\n"
22239             "// long long long long long long line\n"
22240             "/* clang-format on */\n"
22241             "/* long long long\n"
22242             " * long long long\n"
22243             " * line */\n"
22244             "int i;\n"
22245             "/* clang-format off */\n"
22246             "/* long long long long long long line */\n",
22247             format("// clang-format off\n"
22248                    "// long long long long long long line\n"
22249                    "/* clang-format on */\n"
22250                    "/* long long long long long long line */\n"
22251                    "int i;\n"
22252                    "/* clang-format off */\n"
22253                    "/* long long long long long long line */\n",
22254                    getLLVMStyleWithColumns(20)));
22255 }
22256 
22257 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22258   format("? ) =");
22259   verifyNoCrash("#define a\\\n /**/}");
22260 }
22261 
22262 TEST_F(FormatTest, FormatsTableGenCode) {
22263   FormatStyle Style = getLLVMStyle();
22264   Style.Language = FormatStyle::LK_TableGen;
22265   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22266 }
22267 
22268 TEST_F(FormatTest, ArrayOfTemplates) {
22269   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22270             format("auto a = new unique_ptr<int > [ 10];"));
22271 
22272   FormatStyle Spaces = getLLVMStyle();
22273   Spaces.SpacesInSquareBrackets = true;
22274   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22275             format("auto a = new unique_ptr<int > [10];", Spaces));
22276 }
22277 
22278 TEST_F(FormatTest, ArrayAsTemplateType) {
22279   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22280             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22281 
22282   FormatStyle Spaces = getLLVMStyle();
22283   Spaces.SpacesInSquareBrackets = true;
22284   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22285             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22286 }
22287 
22288 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22289 
22290 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22291   llvm::vfs::InMemoryFileSystem FS;
22292   auto Style1 = getStyle("file", "", "Google", "", &FS);
22293   ASSERT_TRUE((bool)Style1);
22294   ASSERT_EQ(*Style1, getGoogleStyle());
22295 }
22296 
22297 TEST(FormatStyle, GetStyleOfFile) {
22298   llvm::vfs::InMemoryFileSystem FS;
22299   // Test 1: format file in the same directory.
22300   ASSERT_TRUE(
22301       FS.addFile("/a/.clang-format", 0,
22302                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22303   ASSERT_TRUE(
22304       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22305   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22306   ASSERT_TRUE((bool)Style1);
22307   ASSERT_EQ(*Style1, getLLVMStyle());
22308 
22309   // Test 2.1: fallback to default.
22310   ASSERT_TRUE(
22311       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22312   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22313   ASSERT_TRUE((bool)Style2);
22314   ASSERT_EQ(*Style2, getMozillaStyle());
22315 
22316   // Test 2.2: no format on 'none' fallback style.
22317   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22318   ASSERT_TRUE((bool)Style2);
22319   ASSERT_EQ(*Style2, getNoStyle());
22320 
22321   // Test 2.3: format if config is found with no based style while fallback is
22322   // 'none'.
22323   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22324                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22325   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22326   ASSERT_TRUE((bool)Style2);
22327   ASSERT_EQ(*Style2, getLLVMStyle());
22328 
22329   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22330   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22331   ASSERT_TRUE((bool)Style2);
22332   ASSERT_EQ(*Style2, getLLVMStyle());
22333 
22334   // Test 3: format file in parent directory.
22335   ASSERT_TRUE(
22336       FS.addFile("/c/.clang-format", 0,
22337                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22338   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22339                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22340   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22341   ASSERT_TRUE((bool)Style3);
22342   ASSERT_EQ(*Style3, getGoogleStyle());
22343 
22344   // Test 4: error on invalid fallback style
22345   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22346   ASSERT_FALSE((bool)Style4);
22347   llvm::consumeError(Style4.takeError());
22348 
22349   // Test 5: error on invalid yaml on command line
22350   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22351   ASSERT_FALSE((bool)Style5);
22352   llvm::consumeError(Style5.takeError());
22353 
22354   // Test 6: error on invalid style
22355   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22356   ASSERT_FALSE((bool)Style6);
22357   llvm::consumeError(Style6.takeError());
22358 
22359   // Test 7: found config file, error on parsing it
22360   ASSERT_TRUE(
22361       FS.addFile("/d/.clang-format", 0,
22362                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22363                                                   "InvalidKey: InvalidValue")));
22364   ASSERT_TRUE(
22365       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22366   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22367   ASSERT_FALSE((bool)Style7a);
22368   llvm::consumeError(Style7a.takeError());
22369 
22370   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22371   ASSERT_TRUE((bool)Style7b);
22372 
22373   // Test 8: inferred per-language defaults apply.
22374   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22375   ASSERT_TRUE((bool)StyleTd);
22376   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22377 
22378   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22379   // fallback style.
22380   ASSERT_TRUE(FS.addFile(
22381       "/e/sub/.clang-format", 0,
22382       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22383                                        "ColumnLimit: 20")));
22384   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22385                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22386   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22387   ASSERT_TRUE(static_cast<bool>(Style9));
22388   ASSERT_EQ(*Style9, [] {
22389     auto Style = getNoStyle();
22390     Style.ColumnLimit = 20;
22391     return Style;
22392   }());
22393 
22394   // Test 9.1.2: propagate more than one level with no parent file.
22395   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22396                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22397   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22398                          llvm::MemoryBuffer::getMemBuffer(
22399                              "BasedOnStyle: InheritParentConfig\n"
22400                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22401   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22402 
22403   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22404   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22405   ASSERT_TRUE(static_cast<bool>(Style9));
22406   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22407     auto Style = getNoStyle();
22408     Style.ColumnLimit = 20;
22409     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22410     return Style;
22411   }());
22412 
22413   // Test 9.2: with LLVM fallback style
22414   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22415   ASSERT_TRUE(static_cast<bool>(Style9));
22416   ASSERT_EQ(*Style9, [] {
22417     auto Style = getLLVMStyle();
22418     Style.ColumnLimit = 20;
22419     return Style;
22420   }());
22421 
22422   // Test 9.3: with a parent file
22423   ASSERT_TRUE(
22424       FS.addFile("/e/.clang-format", 0,
22425                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
22426                                                   "UseTab: Always")));
22427   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22428   ASSERT_TRUE(static_cast<bool>(Style9));
22429   ASSERT_EQ(*Style9, [] {
22430     auto Style = getGoogleStyle();
22431     Style.ColumnLimit = 20;
22432     Style.UseTab = FormatStyle::UT_Always;
22433     return Style;
22434   }());
22435 
22436   // Test 9.4: propagate more than one level with a parent file.
22437   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
22438     auto Style = getGoogleStyle();
22439     Style.ColumnLimit = 20;
22440     Style.UseTab = FormatStyle::UT_Always;
22441     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22442     return Style;
22443   }();
22444 
22445   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22446   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22447   ASSERT_TRUE(static_cast<bool>(Style9));
22448   ASSERT_EQ(*Style9, SubSubStyle);
22449 
22450   // Test 9.5: use InheritParentConfig as style name
22451   Style9 =
22452       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
22453   ASSERT_TRUE(static_cast<bool>(Style9));
22454   ASSERT_EQ(*Style9, SubSubStyle);
22455 
22456   // Test 9.6: use command line style with inheritance
22457   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
22458                     "none", "", &FS);
22459   ASSERT_TRUE(static_cast<bool>(Style9));
22460   ASSERT_EQ(*Style9, SubSubStyle);
22461 
22462   // Test 9.7: use command line style with inheritance and own config
22463   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
22464                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
22465                     "/e/sub/code.cpp", "none", "", &FS);
22466   ASSERT_TRUE(static_cast<bool>(Style9));
22467   ASSERT_EQ(*Style9, SubSubStyle);
22468 
22469   // Test 9.8: use inheritance from a file without BasedOnStyle
22470   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
22471                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
22472   ASSERT_TRUE(
22473       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
22474                  llvm::MemoryBuffer::getMemBuffer(
22475                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
22476   // Make sure we do not use the fallback style
22477   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
22478   ASSERT_TRUE(static_cast<bool>(Style9));
22479   ASSERT_EQ(*Style9, [] {
22480     auto Style = getLLVMStyle();
22481     Style.ColumnLimit = 123;
22482     return Style;
22483   }());
22484 
22485   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
22486   ASSERT_TRUE(static_cast<bool>(Style9));
22487   ASSERT_EQ(*Style9, [] {
22488     auto Style = getLLVMStyle();
22489     Style.ColumnLimit = 123;
22490     Style.IndentWidth = 7;
22491     return Style;
22492   }());
22493 
22494   // Test 9.9: use inheritance from a specific config file.
22495   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
22496                     "none", "", &FS);
22497   ASSERT_TRUE(static_cast<bool>(Style9));
22498   ASSERT_EQ(*Style9, SubSubStyle);
22499 }
22500 
22501 TEST(FormatStyle, GetStyleOfSpecificFile) {
22502   llvm::vfs::InMemoryFileSystem FS;
22503   // Specify absolute path to a format file in a parent directory.
22504   ASSERT_TRUE(
22505       FS.addFile("/e/.clang-format", 0,
22506                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22507   ASSERT_TRUE(
22508       FS.addFile("/e/explicit.clang-format", 0,
22509                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22510   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
22511                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22512   auto Style = getStyle("file:/e/explicit.clang-format",
22513                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22514   ASSERT_TRUE(static_cast<bool>(Style));
22515   ASSERT_EQ(*Style, getGoogleStyle());
22516 
22517   // Specify relative path to a format file.
22518   ASSERT_TRUE(
22519       FS.addFile("../../e/explicit.clang-format", 0,
22520                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22521   Style = getStyle("file:../../e/explicit.clang-format",
22522                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22523   ASSERT_TRUE(static_cast<bool>(Style));
22524   ASSERT_EQ(*Style, getGoogleStyle());
22525 
22526   // Specify path to a format file that does not exist.
22527   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
22528                    "LLVM", "", &FS);
22529   ASSERT_FALSE(static_cast<bool>(Style));
22530   llvm::consumeError(Style.takeError());
22531 
22532   // Specify path to a file on the filesystem.
22533   SmallString<128> FormatFilePath;
22534   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
22535       "FormatFileTest", "tpl", FormatFilePath);
22536   EXPECT_FALSE((bool)ECF);
22537   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
22538   EXPECT_FALSE((bool)ECF);
22539   FormatFileTest << "BasedOnStyle: Google\n";
22540   FormatFileTest.close();
22541 
22542   SmallString<128> TestFilePath;
22543   std::error_code ECT =
22544       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
22545   EXPECT_FALSE((bool)ECT);
22546   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
22547   CodeFileTest << "int i;\n";
22548   CodeFileTest.close();
22549 
22550   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
22551   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
22552 
22553   llvm::sys::fs::remove(FormatFilePath.c_str());
22554   llvm::sys::fs::remove(TestFilePath.c_str());
22555   ASSERT_TRUE(static_cast<bool>(Style));
22556   ASSERT_EQ(*Style, getGoogleStyle());
22557 }
22558 
22559 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
22560   // Column limit is 20.
22561   std::string Code = "Type *a =\n"
22562                      "    new Type();\n"
22563                      "g(iiiii, 0, jjjjj,\n"
22564                      "  0, kkkkk, 0, mm);\n"
22565                      "int  bad     = format   ;";
22566   std::string Expected = "auto a = new Type();\n"
22567                          "g(iiiii, nullptr,\n"
22568                          "  jjjjj, nullptr,\n"
22569                          "  kkkkk, nullptr,\n"
22570                          "  mm);\n"
22571                          "int  bad     = format   ;";
22572   FileID ID = Context.createInMemoryFile("format.cpp", Code);
22573   tooling::Replacements Replaces = toReplacements(
22574       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
22575                             "auto "),
22576        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
22577                             "nullptr"),
22578        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
22579                             "nullptr"),
22580        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
22581                             "nullptr")});
22582 
22583   FormatStyle Style = getLLVMStyle();
22584   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
22585   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22586   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22587       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22588   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22589   EXPECT_TRUE(static_cast<bool>(Result));
22590   EXPECT_EQ(Expected, *Result);
22591 }
22592 
22593 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
22594   std::string Code = "#include \"a.h\"\n"
22595                      "#include \"c.h\"\n"
22596                      "\n"
22597                      "int main() {\n"
22598                      "  return 0;\n"
22599                      "}";
22600   std::string Expected = "#include \"a.h\"\n"
22601                          "#include \"b.h\"\n"
22602                          "#include \"c.h\"\n"
22603                          "\n"
22604                          "int main() {\n"
22605                          "  return 0;\n"
22606                          "}";
22607   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
22608   tooling::Replacements Replaces = toReplacements(
22609       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
22610                             "#include \"b.h\"\n")});
22611 
22612   FormatStyle Style = getLLVMStyle();
22613   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
22614   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
22615   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
22616       << llvm::toString(FormattedReplaces.takeError()) << "\n";
22617   auto Result = applyAllReplacements(Code, *FormattedReplaces);
22618   EXPECT_TRUE(static_cast<bool>(Result));
22619   EXPECT_EQ(Expected, *Result);
22620 }
22621 
22622 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
22623   EXPECT_EQ("using std::cin;\n"
22624             "using std::cout;",
22625             format("using std::cout;\n"
22626                    "using std::cin;",
22627                    getGoogleStyle()));
22628 }
22629 
22630 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
22631   FormatStyle Style = getLLVMStyle();
22632   Style.Standard = FormatStyle::LS_Cpp03;
22633   // cpp03 recognize this string as identifier u8 and literal character 'a'
22634   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
22635 }
22636 
22637 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
22638   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
22639   // all modes, including C++11, C++14 and C++17
22640   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
22641 }
22642 
22643 TEST_F(FormatTest, DoNotFormatLikelyXml) {
22644   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
22645   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
22646 }
22647 
22648 TEST_F(FormatTest, StructuredBindings) {
22649   // Structured bindings is a C++17 feature.
22650   // all modes, including C++11, C++14 and C++17
22651   verifyFormat("auto [a, b] = f();");
22652   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
22653   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
22654   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
22655   EXPECT_EQ("auto const volatile [a, b] = f();",
22656             format("auto  const   volatile[a, b] = f();"));
22657   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
22658   EXPECT_EQ("auto &[a, b, c] = f();",
22659             format("auto   &[  a  ,  b,c   ] = f();"));
22660   EXPECT_EQ("auto &&[a, b, c] = f();",
22661             format("auto   &&[  a  ,  b,c   ] = f();"));
22662   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
22663   EXPECT_EQ("auto const volatile &&[a, b] = f();",
22664             format("auto  const  volatile  &&[a, b] = f();"));
22665   EXPECT_EQ("auto const &&[a, b] = f();",
22666             format("auto  const   &&  [a, b] = f();"));
22667   EXPECT_EQ("const auto &[a, b] = f();",
22668             format("const  auto  &  [a, b] = f();"));
22669   EXPECT_EQ("const auto volatile &&[a, b] = f();",
22670             format("const  auto   volatile  &&[a, b] = f();"));
22671   EXPECT_EQ("volatile const auto &&[a, b] = f();",
22672             format("volatile  const  auto   &&[a, b] = f();"));
22673   EXPECT_EQ("const auto &&[a, b] = f();",
22674             format("const  auto  &&  [a, b] = f();"));
22675 
22676   // Make sure we don't mistake structured bindings for lambdas.
22677   FormatStyle PointerMiddle = getLLVMStyle();
22678   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
22679   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
22680   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
22681   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
22682   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
22683   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
22684   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
22685   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
22686   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
22687   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
22688   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
22689   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
22690   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
22691 
22692   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
22693             format("for (const auto   &&   [a, b] : some_range) {\n}"));
22694   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
22695             format("for (const auto   &   [a, b] : some_range) {\n}"));
22696   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
22697             format("for (const auto[a, b] : some_range) {\n}"));
22698   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
22699   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
22700   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
22701   EXPECT_EQ("auto const &[x, y](expr);",
22702             format("auto  const  &  [x,y]  (expr);"));
22703   EXPECT_EQ("auto const &&[x, y](expr);",
22704             format("auto  const  &&  [x,y]  (expr);"));
22705   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
22706   EXPECT_EQ("auto const &[x, y]{expr};",
22707             format("auto  const  &  [x,y]  {expr};"));
22708   EXPECT_EQ("auto const &&[x, y]{expr};",
22709             format("auto  const  &&  [x,y]  {expr};"));
22710 
22711   FormatStyle Spaces = getLLVMStyle();
22712   Spaces.SpacesInSquareBrackets = true;
22713   verifyFormat("auto [ a, b ] = f();", Spaces);
22714   verifyFormat("auto &&[ a, b ] = f();", Spaces);
22715   verifyFormat("auto &[ a, b ] = f();", Spaces);
22716   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
22717   verifyFormat("auto const &[ a, b ] = f();", Spaces);
22718 }
22719 
22720 TEST_F(FormatTest, FileAndCode) {
22721   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
22722   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
22723   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
22724   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
22725   EXPECT_EQ(FormatStyle::LK_ObjC,
22726             guessLanguage("foo.h", "@interface Foo\n@end\n"));
22727   EXPECT_EQ(
22728       FormatStyle::LK_ObjC,
22729       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
22730   EXPECT_EQ(FormatStyle::LK_ObjC,
22731             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
22732   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
22733   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
22734   EXPECT_EQ(FormatStyle::LK_ObjC,
22735             guessLanguage("foo", "@interface Foo\n@end\n"));
22736   EXPECT_EQ(FormatStyle::LK_ObjC,
22737             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
22738   EXPECT_EQ(
22739       FormatStyle::LK_ObjC,
22740       guessLanguage("foo.h",
22741                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
22742   EXPECT_EQ(
22743       FormatStyle::LK_Cpp,
22744       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
22745   // Only one of the two preprocessor regions has ObjC-like code.
22746   EXPECT_EQ(FormatStyle::LK_ObjC,
22747             guessLanguage("foo.h", "#if A\n"
22748                                    "#define B() C\n"
22749                                    "#else\n"
22750                                    "#define B() [NSString a:@\"\"]\n"
22751                                    "#endif\n"));
22752 }
22753 
22754 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
22755   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
22756   EXPECT_EQ(FormatStyle::LK_ObjC,
22757             guessLanguage("foo.h", "array[[calculator getIndex]];"));
22758   EXPECT_EQ(FormatStyle::LK_Cpp,
22759             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
22760   EXPECT_EQ(
22761       FormatStyle::LK_Cpp,
22762       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
22763   EXPECT_EQ(FormatStyle::LK_ObjC,
22764             guessLanguage("foo.h", "[[noreturn foo] bar];"));
22765   EXPECT_EQ(FormatStyle::LK_Cpp,
22766             guessLanguage("foo.h", "[[clang::fallthrough]];"));
22767   EXPECT_EQ(FormatStyle::LK_ObjC,
22768             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
22769   EXPECT_EQ(FormatStyle::LK_Cpp,
22770             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
22771   EXPECT_EQ(FormatStyle::LK_Cpp,
22772             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
22773   EXPECT_EQ(FormatStyle::LK_ObjC,
22774             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
22775   EXPECT_EQ(FormatStyle::LK_Cpp,
22776             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
22777   EXPECT_EQ(
22778       FormatStyle::LK_Cpp,
22779       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
22780   EXPECT_EQ(
22781       FormatStyle::LK_Cpp,
22782       guessLanguage("foo.h",
22783                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
22784   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
22785 }
22786 
22787 TEST_F(FormatTest, GuessLanguageWithCaret) {
22788   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
22789   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
22790   EXPECT_EQ(FormatStyle::LK_ObjC,
22791             guessLanguage("foo.h", "int(^)(char, float);"));
22792   EXPECT_EQ(FormatStyle::LK_ObjC,
22793             guessLanguage("foo.h", "int(^foo)(char, float);"));
22794   EXPECT_EQ(FormatStyle::LK_ObjC,
22795             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
22796   EXPECT_EQ(FormatStyle::LK_ObjC,
22797             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
22798   EXPECT_EQ(
22799       FormatStyle::LK_ObjC,
22800       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
22801 }
22802 
22803 TEST_F(FormatTest, GuessLanguageWithPragmas) {
22804   EXPECT_EQ(FormatStyle::LK_Cpp,
22805             guessLanguage("foo.h", "__pragma(warning(disable:))"));
22806   EXPECT_EQ(FormatStyle::LK_Cpp,
22807             guessLanguage("foo.h", "#pragma(warning(disable:))"));
22808   EXPECT_EQ(FormatStyle::LK_Cpp,
22809             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
22810 }
22811 
22812 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
22813   // ASM symbolic names are identifiers that must be surrounded by [] without
22814   // space in between:
22815   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
22816 
22817   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
22818   verifyFormat(R"(//
22819 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
22820 )");
22821 
22822   // A list of several ASM symbolic names.
22823   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
22824 
22825   // ASM symbolic names in inline ASM with inputs and outputs.
22826   verifyFormat(R"(//
22827 asm("cmoveq %1, %2, %[result]"
22828     : [result] "=r"(result)
22829     : "r"(test), "r"(new), "[result]"(old));
22830 )");
22831 
22832   // ASM symbolic names in inline ASM with no outputs.
22833   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
22834 }
22835 
22836 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
22837   EXPECT_EQ(FormatStyle::LK_Cpp,
22838             guessLanguage("foo.h", "void f() {\n"
22839                                    "  asm (\"mov %[e], %[d]\"\n"
22840                                    "     : [d] \"=rm\" (d)\n"
22841                                    "       [e] \"rm\" (*e));\n"
22842                                    "}"));
22843   EXPECT_EQ(FormatStyle::LK_Cpp,
22844             guessLanguage("foo.h", "void f() {\n"
22845                                    "  _asm (\"mov %[e], %[d]\"\n"
22846                                    "     : [d] \"=rm\" (d)\n"
22847                                    "       [e] \"rm\" (*e));\n"
22848                                    "}"));
22849   EXPECT_EQ(FormatStyle::LK_Cpp,
22850             guessLanguage("foo.h", "void f() {\n"
22851                                    "  __asm (\"mov %[e], %[d]\"\n"
22852                                    "     : [d] \"=rm\" (d)\n"
22853                                    "       [e] \"rm\" (*e));\n"
22854                                    "}"));
22855   EXPECT_EQ(FormatStyle::LK_Cpp,
22856             guessLanguage("foo.h", "void f() {\n"
22857                                    "  __asm__ (\"mov %[e], %[d]\"\n"
22858                                    "     : [d] \"=rm\" (d)\n"
22859                                    "       [e] \"rm\" (*e));\n"
22860                                    "}"));
22861   EXPECT_EQ(FormatStyle::LK_Cpp,
22862             guessLanguage("foo.h", "void f() {\n"
22863                                    "  asm (\"mov %[e], %[d]\"\n"
22864                                    "     : [d] \"=rm\" (d),\n"
22865                                    "       [e] \"rm\" (*e));\n"
22866                                    "}"));
22867   EXPECT_EQ(FormatStyle::LK_Cpp,
22868             guessLanguage("foo.h", "void f() {\n"
22869                                    "  asm volatile (\"mov %[e], %[d]\"\n"
22870                                    "     : [d] \"=rm\" (d)\n"
22871                                    "       [e] \"rm\" (*e));\n"
22872                                    "}"));
22873 }
22874 
22875 TEST_F(FormatTest, GuessLanguageWithChildLines) {
22876   EXPECT_EQ(FormatStyle::LK_Cpp,
22877             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
22878   EXPECT_EQ(FormatStyle::LK_ObjC,
22879             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
22880   EXPECT_EQ(
22881       FormatStyle::LK_Cpp,
22882       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
22883   EXPECT_EQ(
22884       FormatStyle::LK_ObjC,
22885       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
22886 }
22887 
22888 TEST_F(FormatTest, TypenameMacros) {
22889   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
22890 
22891   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
22892   FormatStyle Google = getGoogleStyleWithColumns(0);
22893   Google.TypenameMacros = TypenameMacros;
22894   verifyFormat("struct foo {\n"
22895                "  int bar;\n"
22896                "  TAILQ_ENTRY(a) bleh;\n"
22897                "};",
22898                Google);
22899 
22900   FormatStyle Macros = getLLVMStyle();
22901   Macros.TypenameMacros = TypenameMacros;
22902 
22903   verifyFormat("STACK_OF(int) a;", Macros);
22904   verifyFormat("STACK_OF(int) *a;", Macros);
22905   verifyFormat("STACK_OF(int const *) *a;", Macros);
22906   verifyFormat("STACK_OF(int *const) *a;", Macros);
22907   verifyFormat("STACK_OF(int, string) a;", Macros);
22908   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
22909   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
22910   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
22911   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
22912   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
22913   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
22914 
22915   Macros.PointerAlignment = FormatStyle::PAS_Left;
22916   verifyFormat("STACK_OF(int)* a;", Macros);
22917   verifyFormat("STACK_OF(int*)* a;", Macros);
22918   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
22919   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
22920   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
22921 }
22922 
22923 TEST_F(FormatTest, AtomicQualifier) {
22924   // Check that we treate _Atomic as a type and not a function call
22925   FormatStyle Google = getGoogleStyleWithColumns(0);
22926   verifyFormat("struct foo {\n"
22927                "  int a1;\n"
22928                "  _Atomic(a) a2;\n"
22929                "  _Atomic(_Atomic(int) *const) a3;\n"
22930                "};",
22931                Google);
22932   verifyFormat("_Atomic(uint64_t) a;");
22933   verifyFormat("_Atomic(uint64_t) *a;");
22934   verifyFormat("_Atomic(uint64_t const *) *a;");
22935   verifyFormat("_Atomic(uint64_t *const) *a;");
22936   verifyFormat("_Atomic(const uint64_t *) *a;");
22937   verifyFormat("_Atomic(uint64_t) a;");
22938   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
22939   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
22940   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
22941   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
22942 
22943   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
22944   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
22945   FormatStyle Style = getLLVMStyle();
22946   Style.PointerAlignment = FormatStyle::PAS_Left;
22947   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
22948   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
22949   verifyFormat("_Atomic(int)* a;", Style);
22950   verifyFormat("_Atomic(int*)* a;", Style);
22951   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
22952 
22953   Style.SpacesInCStyleCastParentheses = true;
22954   Style.SpacesInParentheses = false;
22955   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
22956   Style.SpacesInCStyleCastParentheses = false;
22957   Style.SpacesInParentheses = true;
22958   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
22959   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
22960 }
22961 
22962 TEST_F(FormatTest, AmbersandInLamda) {
22963   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
22964   FormatStyle AlignStyle = getLLVMStyle();
22965   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
22966   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22967   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
22968   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22969 }
22970 
22971 TEST_F(FormatTest, SpacesInConditionalStatement) {
22972   FormatStyle Spaces = getLLVMStyle();
22973   Spaces.IfMacros.clear();
22974   Spaces.IfMacros.push_back("MYIF");
22975   Spaces.SpacesInConditionalStatement = true;
22976   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
22977   verifyFormat("if ( !a )\n  return;", Spaces);
22978   verifyFormat("if ( a )\n  return;", Spaces);
22979   verifyFormat("if constexpr ( a )\n  return;", Spaces);
22980   verifyFormat("MYIF ( a )\n  return;", Spaces);
22981   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
22982   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
22983   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
22984   verifyFormat("while ( a )\n  return;", Spaces);
22985   verifyFormat("while ( (a && b) )\n  return;", Spaces);
22986   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
22987   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
22988   // Check that space on the left of "::" is inserted as expected at beginning
22989   // of condition.
22990   verifyFormat("while ( ::func() )\n  return;", Spaces);
22991 
22992   // Check impact of ControlStatementsExceptControlMacros is honored.
22993   Spaces.SpaceBeforeParens =
22994       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
22995   verifyFormat("MYIF( a )\n  return;", Spaces);
22996   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
22997   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
22998 }
22999 
23000 TEST_F(FormatTest, AlternativeOperators) {
23001   // Test case for ensuring alternate operators are not
23002   // combined with their right most neighbour.
23003   verifyFormat("int a and b;");
23004   verifyFormat("int a and_eq b;");
23005   verifyFormat("int a bitand b;");
23006   verifyFormat("int a bitor b;");
23007   verifyFormat("int a compl b;");
23008   verifyFormat("int a not b;");
23009   verifyFormat("int a not_eq b;");
23010   verifyFormat("int a or b;");
23011   verifyFormat("int a xor b;");
23012   verifyFormat("int a xor_eq b;");
23013   verifyFormat("return this not_eq bitand other;");
23014   verifyFormat("bool operator not_eq(const X bitand other)");
23015 
23016   verifyFormat("int a and 5;");
23017   verifyFormat("int a and_eq 5;");
23018   verifyFormat("int a bitand 5;");
23019   verifyFormat("int a bitor 5;");
23020   verifyFormat("int a compl 5;");
23021   verifyFormat("int a not 5;");
23022   verifyFormat("int a not_eq 5;");
23023   verifyFormat("int a or 5;");
23024   verifyFormat("int a xor 5;");
23025   verifyFormat("int a xor_eq 5;");
23026 
23027   verifyFormat("int a compl(5);");
23028   verifyFormat("int a not(5);");
23029 
23030   /* FIXME handle alternate tokens
23031    * https://en.cppreference.com/w/cpp/language/operator_alternative
23032   // alternative tokens
23033   verifyFormat("compl foo();");     //  ~foo();
23034   verifyFormat("foo() <%%>;");      // foo();
23035   verifyFormat("void foo() <%%>;"); // void foo(){}
23036   verifyFormat("int a <:1:>;");     // int a[1];[
23037   verifyFormat("%:define ABC abc"); // #define ABC abc
23038   verifyFormat("%:%:");             // ##
23039   */
23040 }
23041 
23042 TEST_F(FormatTest, STLWhileNotDefineChed) {
23043   verifyFormat("#if defined(while)\n"
23044                "#define while EMIT WARNING C4005\n"
23045                "#endif // while");
23046 }
23047 
23048 TEST_F(FormatTest, OperatorSpacing) {
23049   FormatStyle Style = getLLVMStyle();
23050   Style.PointerAlignment = FormatStyle::PAS_Right;
23051   verifyFormat("Foo::operator*();", Style);
23052   verifyFormat("Foo::operator void *();", Style);
23053   verifyFormat("Foo::operator void **();", Style);
23054   verifyFormat("Foo::operator void *&();", Style);
23055   verifyFormat("Foo::operator void *&&();", Style);
23056   verifyFormat("Foo::operator void const *();", Style);
23057   verifyFormat("Foo::operator void const **();", Style);
23058   verifyFormat("Foo::operator void const *&();", Style);
23059   verifyFormat("Foo::operator void const *&&();", Style);
23060   verifyFormat("Foo::operator()(void *);", Style);
23061   verifyFormat("Foo::operator*(void *);", Style);
23062   verifyFormat("Foo::operator*();", Style);
23063   verifyFormat("Foo::operator**();", Style);
23064   verifyFormat("Foo::operator&();", Style);
23065   verifyFormat("Foo::operator<int> *();", Style);
23066   verifyFormat("Foo::operator<Foo> *();", Style);
23067   verifyFormat("Foo::operator<int> **();", Style);
23068   verifyFormat("Foo::operator<Foo> **();", Style);
23069   verifyFormat("Foo::operator<int> &();", Style);
23070   verifyFormat("Foo::operator<Foo> &();", Style);
23071   verifyFormat("Foo::operator<int> &&();", Style);
23072   verifyFormat("Foo::operator<Foo> &&();", Style);
23073   verifyFormat("Foo::operator<int> *&();", Style);
23074   verifyFormat("Foo::operator<Foo> *&();", Style);
23075   verifyFormat("Foo::operator<int> *&&();", Style);
23076   verifyFormat("Foo::operator<Foo> *&&();", Style);
23077   verifyFormat("operator*(int (*)(), class Foo);", Style);
23078 
23079   verifyFormat("Foo::operator&();", Style);
23080   verifyFormat("Foo::operator void &();", Style);
23081   verifyFormat("Foo::operator void const &();", Style);
23082   verifyFormat("Foo::operator()(void &);", Style);
23083   verifyFormat("Foo::operator&(void &);", Style);
23084   verifyFormat("Foo::operator&();", Style);
23085   verifyFormat("operator&(int (&)(), class Foo);", Style);
23086   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23087 
23088   verifyFormat("Foo::operator&&();", Style);
23089   verifyFormat("Foo::operator**();", Style);
23090   verifyFormat("Foo::operator void &&();", Style);
23091   verifyFormat("Foo::operator void const &&();", Style);
23092   verifyFormat("Foo::operator()(void &&);", Style);
23093   verifyFormat("Foo::operator&&(void &&);", Style);
23094   verifyFormat("Foo::operator&&();", Style);
23095   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23096   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23097   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23098                Style);
23099   verifyFormat("operator void **()", Style);
23100   verifyFormat("operator const FooRight<Object> &()", Style);
23101   verifyFormat("operator const FooRight<Object> *()", Style);
23102   verifyFormat("operator const FooRight<Object> **()", Style);
23103   verifyFormat("operator const FooRight<Object> *&()", Style);
23104   verifyFormat("operator const FooRight<Object> *&&()", Style);
23105 
23106   Style.PointerAlignment = FormatStyle::PAS_Left;
23107   verifyFormat("Foo::operator*();", Style);
23108   verifyFormat("Foo::operator**();", Style);
23109   verifyFormat("Foo::operator void*();", Style);
23110   verifyFormat("Foo::operator void**();", Style);
23111   verifyFormat("Foo::operator void*&();", Style);
23112   verifyFormat("Foo::operator void*&&();", Style);
23113   verifyFormat("Foo::operator void const*();", Style);
23114   verifyFormat("Foo::operator void const**();", Style);
23115   verifyFormat("Foo::operator void const*&();", Style);
23116   verifyFormat("Foo::operator void const*&&();", Style);
23117   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23118   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23119   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23120   verifyFormat("Foo::operator()(void*);", Style);
23121   verifyFormat("Foo::operator*(void*);", Style);
23122   verifyFormat("Foo::operator*();", Style);
23123   verifyFormat("Foo::operator<int>*();", Style);
23124   verifyFormat("Foo::operator<Foo>*();", Style);
23125   verifyFormat("Foo::operator<int>**();", Style);
23126   verifyFormat("Foo::operator<Foo>**();", Style);
23127   verifyFormat("Foo::operator<Foo>*&();", Style);
23128   verifyFormat("Foo::operator<int>&();", Style);
23129   verifyFormat("Foo::operator<Foo>&();", Style);
23130   verifyFormat("Foo::operator<int>&&();", Style);
23131   verifyFormat("Foo::operator<Foo>&&();", Style);
23132   verifyFormat("Foo::operator<int>*&();", Style);
23133   verifyFormat("Foo::operator<Foo>*&();", Style);
23134   verifyFormat("operator*(int (*)(), class Foo);", Style);
23135 
23136   verifyFormat("Foo::operator&();", Style);
23137   verifyFormat("Foo::operator void&();", Style);
23138   verifyFormat("Foo::operator void const&();", Style);
23139   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23140   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23141   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23142   verifyFormat("Foo::operator()(void&);", Style);
23143   verifyFormat("Foo::operator&(void&);", Style);
23144   verifyFormat("Foo::operator&();", Style);
23145   verifyFormat("operator&(int (&)(), class Foo);", Style);
23146   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23147   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23148 
23149   verifyFormat("Foo::operator&&();", Style);
23150   verifyFormat("Foo::operator void&&();", Style);
23151   verifyFormat("Foo::operator void const&&();", Style);
23152   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23153   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23154   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23155   verifyFormat("Foo::operator()(void&&);", Style);
23156   verifyFormat("Foo::operator&&(void&&);", Style);
23157   verifyFormat("Foo::operator&&();", Style);
23158   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23159   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23160   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23161                Style);
23162   verifyFormat("operator void**()", Style);
23163   verifyFormat("operator const FooLeft<Object>&()", Style);
23164   verifyFormat("operator const FooLeft<Object>*()", Style);
23165   verifyFormat("operator const FooLeft<Object>**()", Style);
23166   verifyFormat("operator const FooLeft<Object>*&()", Style);
23167   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23168 
23169   // PR45107
23170   verifyFormat("operator Vector<String>&();", Style);
23171   verifyFormat("operator const Vector<String>&();", Style);
23172   verifyFormat("operator foo::Bar*();", Style);
23173   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23174   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23175                Style);
23176 
23177   Style.PointerAlignment = FormatStyle::PAS_Middle;
23178   verifyFormat("Foo::operator*();", Style);
23179   verifyFormat("Foo::operator void *();", Style);
23180   verifyFormat("Foo::operator()(void *);", Style);
23181   verifyFormat("Foo::operator*(void *);", Style);
23182   verifyFormat("Foo::operator*();", Style);
23183   verifyFormat("operator*(int (*)(), class Foo);", Style);
23184 
23185   verifyFormat("Foo::operator&();", Style);
23186   verifyFormat("Foo::operator void &();", Style);
23187   verifyFormat("Foo::operator void const &();", Style);
23188   verifyFormat("Foo::operator()(void &);", Style);
23189   verifyFormat("Foo::operator&(void &);", Style);
23190   verifyFormat("Foo::operator&();", Style);
23191   verifyFormat("operator&(int (&)(), class Foo);", Style);
23192 
23193   verifyFormat("Foo::operator&&();", Style);
23194   verifyFormat("Foo::operator void &&();", Style);
23195   verifyFormat("Foo::operator void const &&();", Style);
23196   verifyFormat("Foo::operator()(void &&);", Style);
23197   verifyFormat("Foo::operator&&(void &&);", Style);
23198   verifyFormat("Foo::operator&&();", Style);
23199   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23200 }
23201 
23202 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23203   FormatStyle Style = getLLVMStyle();
23204   // PR46157
23205   verifyFormat("foo(operator+, -42);", Style);
23206   verifyFormat("foo(operator++, -42);", Style);
23207   verifyFormat("foo(operator--, -42);", Style);
23208   verifyFormat("foo(-42, operator--);", Style);
23209   verifyFormat("foo(-42, operator, );", Style);
23210   verifyFormat("foo(operator, , -42);", Style);
23211 }
23212 
23213 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23214   FormatStyle Style = getLLVMStyle();
23215   Style.WhitespaceSensitiveMacros.push_back("FOO");
23216 
23217   // Don't use the helpers here, since 'mess up' will change the whitespace
23218   // and these are all whitespace sensitive by definition
23219   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23220             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23221   EXPECT_EQ(
23222       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23223       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23224   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23225             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23226   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23227             "       Still=Intentional);",
23228             format("FOO(String-ized&Messy+But,: :\n"
23229                    "       Still=Intentional);",
23230                    Style));
23231   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
23232   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23233             "       Still=Intentional);",
23234             format("FOO(String-ized=&Messy+But,: :\n"
23235                    "       Still=Intentional);",
23236                    Style));
23237 
23238   Style.ColumnLimit = 21;
23239   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23240             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23241 }
23242 
23243 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23244   // These tests are not in NamespaceFixer because that doesn't
23245   // test its interaction with line wrapping
23246   FormatStyle Style = getLLVMStyleWithColumns(80);
23247   verifyFormat("namespace {\n"
23248                "int i;\n"
23249                "int j;\n"
23250                "} // namespace",
23251                Style);
23252 
23253   verifyFormat("namespace AAA {\n"
23254                "int i;\n"
23255                "int j;\n"
23256                "} // namespace AAA",
23257                Style);
23258 
23259   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23260             "int i;\n"
23261             "int j;\n"
23262             "} // namespace Averyveryveryverylongnamespace",
23263             format("namespace Averyveryveryverylongnamespace {\n"
23264                    "int i;\n"
23265                    "int j;\n"
23266                    "}",
23267                    Style));
23268 
23269   EXPECT_EQ(
23270       "namespace "
23271       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23272       "    went::mad::now {\n"
23273       "int i;\n"
23274       "int j;\n"
23275       "} // namespace\n"
23276       "  // "
23277       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23278       "went::mad::now",
23279       format("namespace "
23280              "would::it::save::you::a::lot::of::time::if_::i::"
23281              "just::gave::up::and_::went::mad::now {\n"
23282              "int i;\n"
23283              "int j;\n"
23284              "}",
23285              Style));
23286 
23287   // This used to duplicate the comment again and again on subsequent runs
23288   EXPECT_EQ(
23289       "namespace "
23290       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23291       "    went::mad::now {\n"
23292       "int i;\n"
23293       "int j;\n"
23294       "} // namespace\n"
23295       "  // "
23296       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23297       "went::mad::now",
23298       format("namespace "
23299              "would::it::save::you::a::lot::of::time::if_::i::"
23300              "just::gave::up::and_::went::mad::now {\n"
23301              "int i;\n"
23302              "int j;\n"
23303              "} // namespace\n"
23304              "  // "
23305              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23306              "and_::went::mad::now",
23307              Style));
23308 }
23309 
23310 TEST_F(FormatTest, LikelyUnlikely) {
23311   FormatStyle Style = getLLVMStyle();
23312 
23313   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23314                "  return 29;\n"
23315                "}",
23316                Style);
23317 
23318   verifyFormat("if (argc > 5) [[likely]] {\n"
23319                "  return 29;\n"
23320                "}",
23321                Style);
23322 
23323   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23324                "  return 29;\n"
23325                "} else [[likely]] {\n"
23326                "  return 42;\n"
23327                "}\n",
23328                Style);
23329 
23330   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23331                "  return 29;\n"
23332                "} else if (argc > 10) [[likely]] {\n"
23333                "  return 99;\n"
23334                "} else {\n"
23335                "  return 42;\n"
23336                "}\n",
23337                Style);
23338 
23339   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23340                "  return 29;\n"
23341                "}",
23342                Style);
23343 
23344   verifyFormat("if (argc > 5) [[unlikely]]\n"
23345                "  return 29;\n",
23346                Style);
23347   verifyFormat("if (argc > 5) [[likely]]\n"
23348                "  return 29;\n",
23349                Style);
23350 
23351   Style.AttributeMacros.push_back("UNLIKELY");
23352   Style.AttributeMacros.push_back("LIKELY");
23353   verifyFormat("if (argc > 5) UNLIKELY\n"
23354                "  return 29;\n",
23355                Style);
23356 
23357   verifyFormat("if (argc > 5) UNLIKELY {\n"
23358                "  return 29;\n"
23359                "}",
23360                Style);
23361   verifyFormat("if (argc > 5) UNLIKELY {\n"
23362                "  return 29;\n"
23363                "} else [[likely]] {\n"
23364                "  return 42;\n"
23365                "}\n",
23366                Style);
23367   verifyFormat("if (argc > 5) UNLIKELY {\n"
23368                "  return 29;\n"
23369                "} else LIKELY {\n"
23370                "  return 42;\n"
23371                "}\n",
23372                Style);
23373   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23374                "  return 29;\n"
23375                "} else LIKELY {\n"
23376                "  return 42;\n"
23377                "}\n",
23378                Style);
23379 }
23380 
23381 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23382   verifyFormat("Constructor()\n"
23383                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23384                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23385                "aaaaaaaaaaaaaaaaaat))");
23386   verifyFormat("Constructor()\n"
23387                "    : aaaaaaaaaaaaa(aaaaaa), "
23388                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
23389 
23390   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
23391   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
23392   verifyFormat("Constructor()\n"
23393                "    : aaaaaa(aaaaaa),\n"
23394                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23395                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
23396                StyleWithWhitespacePenalty);
23397   verifyFormat("Constructor()\n"
23398                "    : aaaaaaaaaaaaa(aaaaaa), "
23399                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
23400                StyleWithWhitespacePenalty);
23401 }
23402 
23403 TEST_F(FormatTest, LLVMDefaultStyle) {
23404   FormatStyle Style = getLLVMStyle();
23405   verifyFormat("extern \"C\" {\n"
23406                "int foo();\n"
23407                "}",
23408                Style);
23409 }
23410 TEST_F(FormatTest, GNUDefaultStyle) {
23411   FormatStyle Style = getGNUStyle();
23412   verifyFormat("extern \"C\"\n"
23413                "{\n"
23414                "  int foo ();\n"
23415                "}",
23416                Style);
23417 }
23418 TEST_F(FormatTest, MozillaDefaultStyle) {
23419   FormatStyle Style = getMozillaStyle();
23420   verifyFormat("extern \"C\"\n"
23421                "{\n"
23422                "  int foo();\n"
23423                "}",
23424                Style);
23425 }
23426 TEST_F(FormatTest, GoogleDefaultStyle) {
23427   FormatStyle Style = getGoogleStyle();
23428   verifyFormat("extern \"C\" {\n"
23429                "int foo();\n"
23430                "}",
23431                Style);
23432 }
23433 TEST_F(FormatTest, ChromiumDefaultStyle) {
23434   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
23435   verifyFormat("extern \"C\" {\n"
23436                "int foo();\n"
23437                "}",
23438                Style);
23439 }
23440 TEST_F(FormatTest, MicrosoftDefaultStyle) {
23441   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
23442   verifyFormat("extern \"C\"\n"
23443                "{\n"
23444                "    int foo();\n"
23445                "}",
23446                Style);
23447 }
23448 TEST_F(FormatTest, WebKitDefaultStyle) {
23449   FormatStyle Style = getWebKitStyle();
23450   verifyFormat("extern \"C\" {\n"
23451                "int foo();\n"
23452                "}",
23453                Style);
23454 }
23455 
23456 TEST_F(FormatTest, Concepts) {
23457   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
23458             FormatStyle::BBCDS_Always);
23459   verifyFormat("template <typename T>\n"
23460                "concept True = true;");
23461 
23462   verifyFormat("template <typename T>\n"
23463                "concept C = ((false || foo()) && C2<T>) ||\n"
23464                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
23465                getLLVMStyleWithColumns(60));
23466 
23467   verifyFormat("template <typename T>\n"
23468                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
23469                "sizeof(T) <= 8;");
23470 
23471   verifyFormat("template <typename T>\n"
23472                "concept DelayedCheck = true && requires(T t) {\n"
23473                "                                 t.bar();\n"
23474                "                                 t.baz();\n"
23475                "                               } && sizeof(T) <= 8;");
23476 
23477   verifyFormat("template <typename T>\n"
23478                "concept DelayedCheck = true && requires(T t) { // Comment\n"
23479                "                                 t.bar();\n"
23480                "                                 t.baz();\n"
23481                "                               } && sizeof(T) <= 8;");
23482 
23483   verifyFormat("template <typename T>\n"
23484                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
23485                "sizeof(T) <= 8;");
23486 
23487   verifyFormat("template <typename T>\n"
23488                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
23489                "&& sizeof(T) <= 8;");
23490 
23491   verifyFormat(
23492       "template <typename T>\n"
23493       "concept DelayedCheck = static_cast<bool>(0) ||\n"
23494       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23495 
23496   verifyFormat("template <typename T>\n"
23497                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
23498                "&& sizeof(T) <= 8;");
23499 
23500   verifyFormat(
23501       "template <typename T>\n"
23502       "concept DelayedCheck = (bool)(0) ||\n"
23503       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23504 
23505   verifyFormat("template <typename T>\n"
23506                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
23507                "&& sizeof(T) <= 8;");
23508 
23509   verifyFormat("template <typename T>\n"
23510                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
23511                "sizeof(T) <= 8;");
23512 
23513   verifyFormat("template <typename T>\n"
23514                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
23515                "               requires(T t) {\n"
23516                "                 t.bar();\n"
23517                "                 t.baz();\n"
23518                "               } && sizeof(T) <= 8 && !(4 < 3);",
23519                getLLVMStyleWithColumns(60));
23520 
23521   verifyFormat("template <typename T>\n"
23522                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
23523 
23524   verifyFormat("template <typename T>\n"
23525                "concept C = foo();");
23526 
23527   verifyFormat("template <typename T>\n"
23528                "concept C = foo(T());");
23529 
23530   verifyFormat("template <typename T>\n"
23531                "concept C = foo(T{});");
23532 
23533   verifyFormat("template <typename T>\n"
23534                "concept Size = V<sizeof(T)>::Value > 5;");
23535 
23536   verifyFormat("template <typename T>\n"
23537                "concept True = S<T>::Value;");
23538 
23539   verifyFormat(
23540       "template <typename T>\n"
23541       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
23542       "            sizeof(T) <= 8;");
23543 
23544   // FIXME: This is misformatted because the fake l paren starts at bool, not at
23545   // the lambda l square.
23546   verifyFormat("template <typename T>\n"
23547                "concept C = [] -> bool { return true; }() && requires(T t) { "
23548                "t.bar(); } &&\n"
23549                "                      sizeof(T) <= 8;");
23550 
23551   verifyFormat(
23552       "template <typename T>\n"
23553       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
23554       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23555 
23556   verifyFormat("template <typename T>\n"
23557                "concept C = decltype([]() { return std::true_type{}; "
23558                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
23559                getLLVMStyleWithColumns(120));
23560 
23561   verifyFormat("template <typename T>\n"
23562                "concept C = decltype([]() -> std::true_type { return {}; "
23563                "}())::value &&\n"
23564                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
23565 
23566   verifyFormat("template <typename T>\n"
23567                "concept C = true;\n"
23568                "Foo Bar;");
23569 
23570   verifyFormat("template <typename T>\n"
23571                "concept Hashable = requires(T a) {\n"
23572                "                     { std::hash<T>{}(a) } -> "
23573                "std::convertible_to<std::size_t>;\n"
23574                "                   };");
23575 
23576   verifyFormat(
23577       "template <typename T>\n"
23578       "concept EqualityComparable = requires(T a, T b) {\n"
23579       "                               { a == b } -> std::same_as<bool>;\n"
23580       "                             };");
23581 
23582   verifyFormat(
23583       "template <typename T>\n"
23584       "concept EqualityComparable = requires(T a, T b) {\n"
23585       "                               { a == b } -> std::same_as<bool>;\n"
23586       "                               { a != b } -> std::same_as<bool>;\n"
23587       "                             };");
23588 
23589   verifyFormat("template <typename T>\n"
23590                "concept WeakEqualityComparable = requires(T a, T b) {\n"
23591                "                                   { a == b };\n"
23592                "                                   { a != b };\n"
23593                "                                 };");
23594 
23595   verifyFormat("template <typename T>\n"
23596                "concept HasSizeT = requires { typename T::size_t; };");
23597 
23598   verifyFormat("template <typename T>\n"
23599                "concept Semiregular =\n"
23600                "    DefaultConstructible<T> && CopyConstructible<T> && "
23601                "CopyAssignable<T> &&\n"
23602                "    requires(T a, std::size_t n) {\n"
23603                "      requires Same<T *, decltype(&a)>;\n"
23604                "      { a.~T() } noexcept;\n"
23605                "      requires Same<T *, decltype(new T)>;\n"
23606                "      requires Same<T *, decltype(new T[n])>;\n"
23607                "      { delete new T; };\n"
23608                "      { delete new T[n]; };\n"
23609                "    };");
23610 
23611   verifyFormat("template <typename T>\n"
23612                "concept Semiregular =\n"
23613                "    requires(T a, std::size_t n) {\n"
23614                "      requires Same<T *, decltype(&a)>;\n"
23615                "      { a.~T() } noexcept;\n"
23616                "      requires Same<T *, decltype(new T)>;\n"
23617                "      requires Same<T *, decltype(new T[n])>;\n"
23618                "      { delete new T; };\n"
23619                "      { delete new T[n]; };\n"
23620                "      { new T } -> std::same_as<T *>;\n"
23621                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
23622                "CopyAssignable<T>;");
23623 
23624   verifyFormat(
23625       "template <typename T>\n"
23626       "concept Semiregular =\n"
23627       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
23628       "                                 requires Same<T *, decltype(&a)>;\n"
23629       "                                 { a.~T() } noexcept;\n"
23630       "                                 requires Same<T *, decltype(new T)>;\n"
23631       "                                 requires Same<T *, decltype(new "
23632       "T[n])>;\n"
23633       "                                 { delete new T; };\n"
23634       "                                 { delete new T[n]; };\n"
23635       "                               } && CopyConstructible<T> && "
23636       "CopyAssignable<T>;");
23637 
23638   verifyFormat("template <typename T>\n"
23639                "concept Two = requires(T t) {\n"
23640                "                { t.foo() } -> std::same_as<Bar>;\n"
23641                "              } && requires(T &&t) {\n"
23642                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
23643                "                   };");
23644 
23645   verifyFormat(
23646       "template <typename T>\n"
23647       "concept C = requires(T x) {\n"
23648       "              { *x } -> std::convertible_to<typename T::inner>;\n"
23649       "              { x + 1 } noexcept -> std::same_as<int>;\n"
23650       "              { x * 1 } -> std::convertible_to<T>;\n"
23651       "            };");
23652 
23653   verifyFormat(
23654       "template <typename T, typename U = T>\n"
23655       "concept Swappable = requires(T &&t, U &&u) {\n"
23656       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
23657       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
23658       "                    };");
23659 
23660   verifyFormat("template <typename T, typename U>\n"
23661                "concept Common = requires(T &&t, U &&u) {\n"
23662                "                   typename CommonType<T, U>;\n"
23663                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
23664                "                 };");
23665 
23666   verifyFormat("template <typename T, typename U>\n"
23667                "concept Common = requires(T &&t, U &&u) {\n"
23668                "                   typename CommonType<T, U>;\n"
23669                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
23670                "                 };");
23671 
23672   verifyFormat(
23673       "template <typename T>\n"
23674       "concept C = requires(T t) {\n"
23675       "              requires Bar<T> && Foo<T>;\n"
23676       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
23677       "            };");
23678 
23679   verifyFormat("template <typename T>\n"
23680                "concept HasFoo = requires(T t) {\n"
23681                "                   { t.foo() };\n"
23682                "                   t.foo();\n"
23683                "                 };\n"
23684                "template <typename T>\n"
23685                "concept HasBar = requires(T t) {\n"
23686                "                   { t.bar() };\n"
23687                "                   t.bar();\n"
23688                "                 };");
23689 
23690   verifyFormat("template <typename T>\n"
23691                "concept Large = sizeof(T) > 10;");
23692 
23693   verifyFormat("template <typename T, typename U>\n"
23694                "concept FooableWith = requires(T t, U u) {\n"
23695                "                        typename T::foo_type;\n"
23696                "                        { t.foo(u) } -> typename T::foo_type;\n"
23697                "                        t++;\n"
23698                "                      };\n"
23699                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
23700 
23701   verifyFormat("template <typename T>\n"
23702                "concept Context = is_specialization_of_v<context, T>;");
23703 
23704   verifyFormat("template <typename T>\n"
23705                "concept Node = std::is_object_v<T>;");
23706 
23707   auto Style = getLLVMStyle();
23708   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
23709 
23710   verifyFormat(
23711       "template <typename T>\n"
23712       "concept C = requires(T t) {\n"
23713       "              requires Bar<T> && Foo<T>;\n"
23714       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
23715       "            };",
23716       Style);
23717 
23718   verifyFormat("template <typename T>\n"
23719                "concept HasFoo = requires(T t) {\n"
23720                "                   { t.foo() };\n"
23721                "                   t.foo();\n"
23722                "                 };\n"
23723                "template <typename T>\n"
23724                "concept HasBar = requires(T t) {\n"
23725                "                   { t.bar() };\n"
23726                "                   t.bar();\n"
23727                "                 };",
23728                Style);
23729 
23730   verifyFormat("template <typename T> concept True = true;", Style);
23731 
23732   verifyFormat("template <typename T>\n"
23733                "concept C = decltype([]() -> std::true_type { return {}; "
23734                "}())::value &&\n"
23735                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
23736                Style);
23737 
23738   verifyFormat("template <typename T>\n"
23739                "concept Semiregular =\n"
23740                "    DefaultConstructible<T> && CopyConstructible<T> && "
23741                "CopyAssignable<T> &&\n"
23742                "    requires(T a, std::size_t n) {\n"
23743                "      requires Same<T *, decltype(&a)>;\n"
23744                "      { a.~T() } noexcept;\n"
23745                "      requires Same<T *, decltype(new T)>;\n"
23746                "      requires Same<T *, decltype(new T[n])>;\n"
23747                "      { delete new T; };\n"
23748                "      { delete new T[n]; };\n"
23749                "    };",
23750                Style);
23751 
23752   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
23753 
23754   verifyFormat("template <typename T> concept C =\n"
23755                "    requires(T t) {\n"
23756                "      requires Bar<T> && Foo<T>;\n"
23757                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
23758                "    };",
23759                Style);
23760 
23761   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
23762                "                                         { t.foo() };\n"
23763                "                                         t.foo();\n"
23764                "                                       };\n"
23765                "template <typename T> concept HasBar = requires(T t) {\n"
23766                "                                         { t.bar() };\n"
23767                "                                         t.bar();\n"
23768                "                                       };",
23769                Style);
23770 
23771   verifyFormat("template <typename T> concept True = true;", Style);
23772 
23773   verifyFormat(
23774       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
23775       "                                    return {};\n"
23776       "                                  }())::value\n"
23777       "                                  && requires(T t) { t.bar(); } &&\n"
23778       "                                  sizeof(T) <= 8;",
23779       Style);
23780 
23781   verifyFormat("template <typename T> concept Semiregular =\n"
23782                "    DefaultConstructible<T> && CopyConstructible<T> && "
23783                "CopyAssignable<T> &&\n"
23784                "    requires(T a, std::size_t n) {\n"
23785                "      requires Same<T *, decltype(&a)>;\n"
23786                "      { a.~T() } noexcept;\n"
23787                "      requires Same<T *, decltype(new T)>;\n"
23788                "      requires Same<T *, decltype(new T[n])>;\n"
23789                "      { delete new T; };\n"
23790                "      { delete new T[n]; };\n"
23791                "    };",
23792                Style);
23793 
23794   // The following tests are invalid C++, we just want to make sure we don't
23795   // assert.
23796   verifyFormat("template <typename T>\n"
23797                "concept C = requires C2<T>;");
23798 
23799   verifyFormat("template <typename T>\n"
23800                "concept C = 5 + 4;");
23801 
23802   verifyFormat("template <typename T>\n"
23803                "concept C =\n"
23804                "class X;");
23805 
23806   verifyFormat("template <typename T>\n"
23807                "concept C = [] && true;");
23808 
23809   verifyFormat("template <typename T>\n"
23810                "concept C = [] && requires(T t) { typename T::size_type; };");
23811 }
23812 
23813 TEST_F(FormatTest, RequiresClausesPositions) {
23814   auto Style = getLLVMStyle();
23815   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
23816   EXPECT_EQ(Style.IndentRequiresClause, true);
23817 
23818   verifyFormat("template <typename T>\n"
23819                "  requires(Foo<T> && std::trait<T>)\n"
23820                "struct Bar;",
23821                Style);
23822 
23823   verifyFormat("template <typename T>\n"
23824                "  requires(Foo<T> && std::trait<T>)\n"
23825                "class Bar {\n"
23826                "public:\n"
23827                "  Bar(T t);\n"
23828                "  bool baz();\n"
23829                "};",
23830                Style);
23831 
23832   verifyFormat(
23833       "template <typename T>\n"
23834       "  requires requires(T &&t) {\n"
23835       "             typename T::I;\n"
23836       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
23837       "           }\n"
23838       "Bar(T) -> Bar<typename T::I>;",
23839       Style);
23840 
23841   verifyFormat("template <typename T>\n"
23842                "  requires(Foo<T> && std::trait<T>)\n"
23843                "constexpr T MyGlobal;",
23844                Style);
23845 
23846   verifyFormat("template <typename T>\n"
23847                "  requires Foo<T> && requires(T t) {\n"
23848                "                       { t.baz() } -> std::same_as<bool>;\n"
23849                "                       requires std::same_as<T::Factor, int>;\n"
23850                "                     }\n"
23851                "inline int bar(T t) {\n"
23852                "  return t.baz() ? T::Factor : 5;\n"
23853                "}",
23854                Style);
23855 
23856   verifyFormat("template <typename T>\n"
23857                "inline int bar(T t)\n"
23858                "  requires Foo<T> && requires(T t) {\n"
23859                "                       { t.baz() } -> std::same_as<bool>;\n"
23860                "                       requires std::same_as<T::Factor, int>;\n"
23861                "                     }\n"
23862                "{\n"
23863                "  return t.baz() ? T::Factor : 5;\n"
23864                "}",
23865                Style);
23866 
23867   verifyFormat("template <typename T>\n"
23868                "  requires F<T>\n"
23869                "int bar(T t) {\n"
23870                "  return 5;\n"
23871                "}",
23872                Style);
23873 
23874   verifyFormat("template <typename T>\n"
23875                "int bar(T t)\n"
23876                "  requires F<T>\n"
23877                "{\n"
23878                "  return 5;\n"
23879                "}",
23880                Style);
23881 
23882   verifyFormat("template <typename T>\n"
23883                "int bar(T t)\n"
23884                "  requires F<T>;",
23885                Style);
23886 
23887   Style.IndentRequiresClause = false;
23888   verifyFormat("template <typename T>\n"
23889                "requires F<T>\n"
23890                "int bar(T t) {\n"
23891                "  return 5;\n"
23892                "}",
23893                Style);
23894 
23895   verifyFormat("template <typename T>\n"
23896                "int bar(T t)\n"
23897                "requires F<T>\n"
23898                "{\n"
23899                "  return 5;\n"
23900                "}",
23901                Style);
23902 
23903   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
23904   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
23905                "template <typename T> requires Foo<T> void bar() {}\n"
23906                "template <typename T> void bar() requires Foo<T> {}\n"
23907                "template <typename T> void bar() requires Foo<T>;\n"
23908                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
23909                Style);
23910 
23911   auto ColumnStyle = Style;
23912   ColumnStyle.ColumnLimit = 40;
23913   verifyFormat("template <typename AAAAAAA>\n"
23914                "requires Foo<T> struct Bar {};\n"
23915                "template <typename AAAAAAA>\n"
23916                "requires Foo<T> void bar() {}\n"
23917                "template <typename AAAAAAA>\n"
23918                "void bar() requires Foo<T> {}\n"
23919                "template <typename AAAAAAA>\n"
23920                "requires Foo<T> Baz(T) -> Baz<T>;",
23921                ColumnStyle);
23922 
23923   verifyFormat("template <typename T>\n"
23924                "requires Foo<AAAAAAA> struct Bar {};\n"
23925                "template <typename T>\n"
23926                "requires Foo<AAAAAAA> void bar() {}\n"
23927                "template <typename T>\n"
23928                "void bar() requires Foo<AAAAAAA> {}\n"
23929                "template <typename T>\n"
23930                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
23931                ColumnStyle);
23932 
23933   verifyFormat("template <typename AAAAAAA>\n"
23934                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23935                "struct Bar {};\n"
23936                "template <typename AAAAAAA>\n"
23937                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23938                "void bar() {}\n"
23939                "template <typename AAAAAAA>\n"
23940                "void bar()\n"
23941                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
23942                "template <typename AAAAAAA>\n"
23943                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
23944                "template <typename AAAAAAA>\n"
23945                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23946                "Bar(T) -> Bar<T>;",
23947                ColumnStyle);
23948 
23949   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
23950   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
23951 
23952   verifyFormat("template <typename T>\n"
23953                "requires Foo<T> struct Bar {};\n"
23954                "template <typename T>\n"
23955                "requires Foo<T> void bar() {}\n"
23956                "template <typename T>\n"
23957                "void bar()\n"
23958                "requires Foo<T> {}\n"
23959                "template <typename T>\n"
23960                "void bar()\n"
23961                "requires Foo<T>;\n"
23962                "template <typename T>\n"
23963                "requires Foo<T> Bar(T) -> Bar<T>;",
23964                Style);
23965 
23966   verifyFormat("template <typename AAAAAAA>\n"
23967                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23968                "struct Bar {};\n"
23969                "template <typename AAAAAAA>\n"
23970                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23971                "void bar() {}\n"
23972                "template <typename AAAAAAA>\n"
23973                "void bar()\n"
23974                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
23975                "template <typename AAAAAAA>\n"
23976                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
23977                "template <typename AAAAAAA>\n"
23978                "requires Foo<AAAAAAAAAAAAAAAA>\n"
23979                "Bar(T) -> Bar<T>;",
23980                ColumnStyle);
23981 
23982   Style.IndentRequiresClause = true;
23983   ColumnStyle.IndentRequiresClause = true;
23984 
23985   verifyFormat("template <typename T>\n"
23986                "  requires Foo<T> struct Bar {};\n"
23987                "template <typename T>\n"
23988                "  requires Foo<T> void bar() {}\n"
23989                "template <typename T>\n"
23990                "void bar()\n"
23991                "  requires Foo<T> {}\n"
23992                "template <typename T>\n"
23993                "  requires Foo<T> Bar(T) -> Bar<T>;",
23994                Style);
23995 
23996   verifyFormat("template <typename AAAAAAA>\n"
23997                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
23998                "struct Bar {};\n"
23999                "template <typename AAAAAAA>\n"
24000                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24001                "void bar() {}\n"
24002                "template <typename AAAAAAA>\n"
24003                "void bar()\n"
24004                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24005                "template <typename AAAAAAA>\n"
24006                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24007                "template <typename AAAAAAA>\n"
24008                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24009                "Bar(T) -> Bar<T>;",
24010                ColumnStyle);
24011 
24012   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24013   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24014 
24015   verifyFormat("template <typename T> requires Foo<T>\n"
24016                "struct Bar {};\n"
24017                "template <typename T> requires Foo<T>\n"
24018                "void bar() {}\n"
24019                "template <typename T>\n"
24020                "void bar() requires Foo<T>\n"
24021                "{}\n"
24022                "template <typename T> void bar() requires Foo<T>;\n"
24023                "template <typename T> requires Foo<T>\n"
24024                "Bar(T) -> Bar<T>;",
24025                Style);
24026 
24027   verifyFormat("template <typename AAAAAAA>\n"
24028                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24029                "struct Bar {};\n"
24030                "template <typename AAAAAAA>\n"
24031                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24032                "void bar() {}\n"
24033                "template <typename AAAAAAA>\n"
24034                "void bar()\n"
24035                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24036                "{}\n"
24037                "template <typename AAAAAAA>\n"
24038                "requires Foo<AAAAAAAA>\n"
24039                "Bar(T) -> Bar<T>;\n"
24040                "template <typename AAAAAAA>\n"
24041                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24042                "Bar(T) -> Bar<T>;",
24043                ColumnStyle);
24044 }
24045 
24046 TEST_F(FormatTest, RequiresClauses) {
24047   verifyFormat("struct [[nodiscard]] zero_t {\n"
24048                "  template <class T>\n"
24049                "    requires requires { number_zero_v<T>; }\n"
24050                "  [[nodiscard]] constexpr operator T() const {\n"
24051                "    return number_zero_v<T>;\n"
24052                "  }\n"
24053                "};");
24054 }
24055 
24056 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24057   FormatStyle Style = getLLVMStyle();
24058   StringRef Source = "void Foo::slot() {\n"
24059                      "  unsigned char MyChar = 'x';\n"
24060                      "  emit signal(MyChar);\n"
24061                      "  Q_EMIT signal(MyChar);\n"
24062                      "}";
24063 
24064   EXPECT_EQ(Source, format(Source, Style));
24065 
24066   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
24067   EXPECT_EQ("void Foo::slot() {\n"
24068             "  unsigned char MyChar = 'x';\n"
24069             "  emit          signal(MyChar);\n"
24070             "  Q_EMIT signal(MyChar);\n"
24071             "}",
24072             format(Source, Style));
24073 
24074   Style.StatementAttributeLikeMacros.push_back("emit");
24075   EXPECT_EQ(Source, format(Source, Style));
24076 
24077   Style.StatementAttributeLikeMacros = {};
24078   EXPECT_EQ("void Foo::slot() {\n"
24079             "  unsigned char MyChar = 'x';\n"
24080             "  emit          signal(MyChar);\n"
24081             "  Q_EMIT        signal(MyChar);\n"
24082             "}",
24083             format(Source, Style));
24084 }
24085 
24086 TEST_F(FormatTest, IndentAccessModifiers) {
24087   FormatStyle Style = getLLVMStyle();
24088   Style.IndentAccessModifiers = true;
24089   // Members are *two* levels below the record;
24090   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24091   verifyFormat("class C {\n"
24092                "    int i;\n"
24093                "};\n",
24094                Style);
24095   verifyFormat("union C {\n"
24096                "    int i;\n"
24097                "    unsigned u;\n"
24098                "};\n",
24099                Style);
24100   // Access modifiers should be indented one level below the record.
24101   verifyFormat("class C {\n"
24102                "  public:\n"
24103                "    int i;\n"
24104                "};\n",
24105                Style);
24106   verifyFormat("struct S {\n"
24107                "  private:\n"
24108                "    class C {\n"
24109                "        int j;\n"
24110                "\n"
24111                "      public:\n"
24112                "        C();\n"
24113                "    };\n"
24114                "\n"
24115                "  public:\n"
24116                "    int i;\n"
24117                "};\n",
24118                Style);
24119   // Enumerations are not records and should be unaffected.
24120   Style.AllowShortEnumsOnASingleLine = false;
24121   verifyFormat("enum class E {\n"
24122                "  A,\n"
24123                "  B\n"
24124                "};\n",
24125                Style);
24126   // Test with a different indentation width;
24127   // also proves that the result is Style.AccessModifierOffset agnostic.
24128   Style.IndentWidth = 3;
24129   verifyFormat("class C {\n"
24130                "   public:\n"
24131                "      int i;\n"
24132                "};\n",
24133                Style);
24134 }
24135 
24136 TEST_F(FormatTest, LimitlessStringsAndComments) {
24137   auto Style = getLLVMStyleWithColumns(0);
24138   constexpr StringRef Code =
24139       "/**\n"
24140       " * This is a multiline comment with quite some long lines, at least for "
24141       "the LLVM Style.\n"
24142       " * We will redo this with strings and line comments. Just to  check if "
24143       "everything is working.\n"
24144       " */\n"
24145       "bool foo() {\n"
24146       "  /* Single line multi line comment. */\n"
24147       "  const std::string String = \"This is a multiline string with quite "
24148       "some long lines, at least for the LLVM Style.\"\n"
24149       "                             \"We already did it with multi line "
24150       "comments, and we will do it with line comments. Just to check if "
24151       "everything is working.\";\n"
24152       "  // This is a line comment (block) with quite some long lines, at "
24153       "least for the LLVM Style.\n"
24154       "  // We already did this with multi line comments and strings. Just to "
24155       "check if everything is working.\n"
24156       "  const std::string SmallString = \"Hello World\";\n"
24157       "  // Small line comment\n"
24158       "  return String.size() > SmallString.size();\n"
24159       "}";
24160   EXPECT_EQ(Code, format(Code, Style));
24161 }
24162 
24163 TEST_F(FormatTest, FormatDecayCopy) {
24164   // error cases from unit tests
24165   verifyFormat("foo(auto())");
24166   verifyFormat("foo(auto{})");
24167   verifyFormat("foo(auto({}))");
24168   verifyFormat("foo(auto{{}})");
24169 
24170   verifyFormat("foo(auto(1))");
24171   verifyFormat("foo(auto{1})");
24172   verifyFormat("foo(new auto(1))");
24173   verifyFormat("foo(new auto{1})");
24174   verifyFormat("decltype(auto(1)) x;");
24175   verifyFormat("decltype(auto{1}) x;");
24176   verifyFormat("auto(x);");
24177   verifyFormat("auto{x};");
24178   verifyFormat("new auto{x};");
24179   verifyFormat("auto{x} = y;");
24180   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24181                                 // the user's own fault
24182   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24183                                          // clearly the user's own fault
24184   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24185 }
24186 
24187 TEST_F(FormatTest, Cpp20ModulesSupport) {
24188   FormatStyle Style = getLLVMStyle();
24189   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24190   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24191 
24192   verifyFormat("export import foo;", Style);
24193   verifyFormat("export import foo:bar;", Style);
24194   verifyFormat("export import foo.bar;", Style);
24195   verifyFormat("export import foo.bar:baz;", Style);
24196   verifyFormat("export import :bar;", Style);
24197   verifyFormat("export module foo:bar;", Style);
24198   verifyFormat("export module foo;", Style);
24199   verifyFormat("export module foo.bar;", Style);
24200   verifyFormat("export module foo.bar:baz;", Style);
24201   verifyFormat("export import <string_view>;", Style);
24202 
24203   verifyFormat("export type_name var;", Style);
24204   verifyFormat("template <class T> export using A = B<T>;", Style);
24205   verifyFormat("export using A = B;", Style);
24206   verifyFormat("export int func() {\n"
24207                "  foo();\n"
24208                "}",
24209                Style);
24210   verifyFormat("export struct {\n"
24211                "  int foo;\n"
24212                "};",
24213                Style);
24214   verifyFormat("export {\n"
24215                "  int foo;\n"
24216                "};",
24217                Style);
24218   verifyFormat("export export char const *hello() { return \"hello\"; }");
24219 
24220   verifyFormat("import bar;", Style);
24221   verifyFormat("import foo.bar;", Style);
24222   verifyFormat("import foo:bar;", Style);
24223   verifyFormat("import :bar;", Style);
24224   verifyFormat("import <ctime>;", Style);
24225   verifyFormat("import \"header\";", Style);
24226 
24227   verifyFormat("module foo;", Style);
24228   verifyFormat("module foo:bar;", Style);
24229   verifyFormat("module foo.bar;", Style);
24230   verifyFormat("module;", Style);
24231 
24232   verifyFormat("export namespace hi {\n"
24233                "const char *sayhi();\n"
24234                "}",
24235                Style);
24236 
24237   verifyFormat("module :private;", Style);
24238   verifyFormat("import <foo/bar.h>;", Style);
24239   verifyFormat("import foo...bar;", Style);
24240   verifyFormat("import ..........;", Style);
24241   verifyFormat("module foo:private;", Style);
24242   verifyFormat("import a", Style);
24243   verifyFormat("module a", Style);
24244   verifyFormat("export import a", Style);
24245   verifyFormat("export module a", Style);
24246 
24247   verifyFormat("import", Style);
24248   verifyFormat("module", Style);
24249   verifyFormat("export", Style);
24250 }
24251 
24252 TEST_F(FormatTest, CoroutineForCoawait) {
24253   FormatStyle Style = getLLVMStyle();
24254   verifyFormat("for co_await (auto x : range())\n  ;");
24255   verifyFormat("for (auto i : arr) {\n"
24256                "}",
24257                Style);
24258   verifyFormat("for co_await (auto i : arr) {\n"
24259                "}",
24260                Style);
24261   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24262                "}",
24263                Style);
24264 }
24265 
24266 TEST_F(FormatTest, CoroutineCoAwait) {
24267   verifyFormat("int x = co_await foo();");
24268   verifyFormat("int x = (co_await foo());");
24269   verifyFormat("co_await (42);");
24270   verifyFormat("void operator co_await(int);");
24271   verifyFormat("void operator co_await(a);");
24272   verifyFormat("co_await a;");
24273   verifyFormat("co_await missing_await_resume{};");
24274   verifyFormat("co_await a; // comment");
24275   verifyFormat("void test0() { co_await a; }");
24276   verifyFormat("co_await co_await co_await foo();");
24277   verifyFormat("co_await foo().bar();");
24278   verifyFormat("co_await [this]() -> Task { co_return x; }");
24279   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24280                "foo(); }(x, y);");
24281 
24282   FormatStyle Style = getLLVMStyleWithColumns(40);
24283   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24284                "  co_return co_await foo();\n"
24285                "}(x, y);",
24286                Style);
24287   verifyFormat("co_await;");
24288 }
24289 
24290 TEST_F(FormatTest, CoroutineCoYield) {
24291   verifyFormat("int x = co_yield foo();");
24292   verifyFormat("int x = (co_yield foo());");
24293   verifyFormat("co_yield (42);");
24294   verifyFormat("co_yield {42};");
24295   verifyFormat("co_yield 42;");
24296   verifyFormat("co_yield n++;");
24297   verifyFormat("co_yield ++n;");
24298   verifyFormat("co_yield;");
24299 }
24300 
24301 TEST_F(FormatTest, CoroutineCoReturn) {
24302   verifyFormat("co_return (42);");
24303   verifyFormat("co_return;");
24304   verifyFormat("co_return {};");
24305   verifyFormat("co_return x;");
24306   verifyFormat("co_return co_await foo();");
24307   verifyFormat("co_return co_yield foo();");
24308 }
24309 
24310 TEST_F(FormatTest, EmptyShortBlock) {
24311   auto Style = getLLVMStyle();
24312   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24313 
24314   verifyFormat("try {\n"
24315                "  doA();\n"
24316                "} catch (Exception &e) {\n"
24317                "  e.printStackTrace();\n"
24318                "}\n",
24319                Style);
24320 
24321   verifyFormat("try {\n"
24322                "  doA();\n"
24323                "} catch (Exception &e) {}\n",
24324                Style);
24325 }
24326 
24327 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
24328   auto Style = getLLVMStyle();
24329 
24330   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
24331   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
24332   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
24333   verifyFormat("struct Y<[] { return 0; }> {};", Style);
24334 
24335   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
24336   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
24337 }
24338 
24339 TEST_F(FormatTest, InsertBraces) {
24340   FormatStyle Style = getLLVMStyle();
24341   Style.InsertBraces = true;
24342 
24343   verifyFormat("// clang-format off\n"
24344                "// comment\n"
24345                "if (a) f();\n"
24346                "// clang-format on\n"
24347                "if (b) {\n"
24348                "  g();\n"
24349                "}",
24350                "// clang-format off\n"
24351                "// comment\n"
24352                "if (a) f();\n"
24353                "// clang-format on\n"
24354                "if (b) g();",
24355                Style);
24356 
24357   verifyFormat("if (a) {\n"
24358                "  switch (b) {\n"
24359                "  case 1:\n"
24360                "    c = 0;\n"
24361                "    break;\n"
24362                "  default:\n"
24363                "    c = 1;\n"
24364                "  }\n"
24365                "}",
24366                "if (a)\n"
24367                "  switch (b) {\n"
24368                "  case 1:\n"
24369                "    c = 0;\n"
24370                "    break;\n"
24371                "  default:\n"
24372                "    c = 1;\n"
24373                "  }",
24374                Style);
24375 
24376   verifyFormat("for (auto node : nodes) {\n"
24377                "  if (node) {\n"
24378                "    break;\n"
24379                "  }\n"
24380                "}",
24381                "for (auto node : nodes)\n"
24382                "  if (node)\n"
24383                "    break;",
24384                Style);
24385 
24386   verifyFormat("for (auto node : nodes) {\n"
24387                "  if (node)\n"
24388                "}",
24389                "for (auto node : nodes)\n"
24390                "  if (node)",
24391                Style);
24392 
24393   verifyFormat("do {\n"
24394                "  --a;\n"
24395                "} while (a);",
24396                "do\n"
24397                "  --a;\n"
24398                "while (a);",
24399                Style);
24400 
24401   verifyFormat("if (i) {\n"
24402                "  ++i;\n"
24403                "} else {\n"
24404                "  --i;\n"
24405                "}",
24406                "if (i)\n"
24407                "  ++i;\n"
24408                "else {\n"
24409                "  --i;\n"
24410                "}",
24411                Style);
24412 
24413   verifyFormat("void f() {\n"
24414                "  while (j--) {\n"
24415                "    while (i) {\n"
24416                "      --i;\n"
24417                "    }\n"
24418                "  }\n"
24419                "}",
24420                "void f() {\n"
24421                "  while (j--)\n"
24422                "    while (i)\n"
24423                "      --i;\n"
24424                "}",
24425                Style);
24426 
24427   verifyFormat("f({\n"
24428                "  if (a) {\n"
24429                "    g();\n"
24430                "  }\n"
24431                "});",
24432                "f({\n"
24433                "  if (a)\n"
24434                "    g();\n"
24435                "});",
24436                Style);
24437 
24438   verifyFormat("if (a) {\n"
24439                "  f();\n"
24440                "} else if (b) {\n"
24441                "  g();\n"
24442                "} else {\n"
24443                "  h();\n"
24444                "}",
24445                "if (a)\n"
24446                "  f();\n"
24447                "else if (b)\n"
24448                "  g();\n"
24449                "else\n"
24450                "  h();",
24451                Style);
24452 
24453   verifyFormat("if (a) {\n"
24454                "  f();\n"
24455                "}\n"
24456                "// comment\n"
24457                "/* comment */",
24458                "if (a)\n"
24459                "  f();\n"
24460                "// comment\n"
24461                "/* comment */",
24462                Style);
24463 
24464   verifyFormat("if (a) {\n"
24465                "  // foo\n"
24466                "  // bar\n"
24467                "  f();\n"
24468                "}",
24469                "if (a)\n"
24470                "  // foo\n"
24471                "  // bar\n"
24472                "  f();",
24473                Style);
24474 
24475   verifyFormat("if (a) { // comment\n"
24476                "  // comment\n"
24477                "  f();\n"
24478                "}",
24479                "if (a) // comment\n"
24480                "  // comment\n"
24481                "  f();",
24482                Style);
24483 
24484   verifyFormat("if (a) {\n"
24485                "  f();\n"
24486                "}\n"
24487                "#undef A\n"
24488                "#undef B",
24489                "if (a)\n"
24490                "  f();\n"
24491                "#undef A\n"
24492                "#undef B",
24493                Style);
24494 
24495   verifyFormat("if (a)\n"
24496                "#ifdef A\n"
24497                "  f();\n"
24498                "#else\n"
24499                "  g();\n"
24500                "#endif",
24501                Style);
24502 
24503   verifyFormat("#if 0\n"
24504                "#elif 1\n"
24505                "#endif\n"
24506                "void f() {\n"
24507                "  if (a) {\n"
24508                "    g();\n"
24509                "  }\n"
24510                "}",
24511                "#if 0\n"
24512                "#elif 1\n"
24513                "#endif\n"
24514                "void f() {\n"
24515                "  if (a) g();\n"
24516                "}",
24517                Style);
24518 
24519   Style.ColumnLimit = 15;
24520 
24521   verifyFormat("#define A     \\\n"
24522                "  if (a)      \\\n"
24523                "    f();",
24524                Style);
24525 
24526   verifyFormat("if (a + b >\n"
24527                "    c) {\n"
24528                "  f();\n"
24529                "}",
24530                "if (a + b > c)\n"
24531                "  f();",
24532                Style);
24533 }
24534 
24535 TEST_F(FormatTest, RemoveBraces) {
24536   FormatStyle Style = getLLVMStyle();
24537   Style.RemoveBracesLLVM = true;
24538 
24539   // The following eight test cases are fully-braced versions of the examples at
24540   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
24541   // statement-bodies-of-if-else-loop-statements".
24542 
24543   // 1. Omit the braces, since the body is simple and clearly associated with
24544   // the if.
24545   verifyFormat("if (isa<FunctionDecl>(D))\n"
24546                "  handleFunctionDecl(D);\n"
24547                "else if (isa<VarDecl>(D))\n"
24548                "  handleVarDecl(D);",
24549                "if (isa<FunctionDecl>(D)) {\n"
24550                "  handleFunctionDecl(D);\n"
24551                "} else if (isa<VarDecl>(D)) {\n"
24552                "  handleVarDecl(D);\n"
24553                "}",
24554                Style);
24555 
24556   // 2. Here we document the condition itself and not the body.
24557   verifyFormat("if (isa<VarDecl>(D)) {\n"
24558                "  // It is necessary that we explain the situation with this\n"
24559                "  // surprisingly long comment, so it would be unclear\n"
24560                "  // without the braces whether the following statement is in\n"
24561                "  // the scope of the `if`.\n"
24562                "  // Because the condition is documented, we can't really\n"
24563                "  // hoist this comment that applies to the body above the\n"
24564                "  // if.\n"
24565                "  handleOtherDecl(D);\n"
24566                "}",
24567                Style);
24568 
24569   // 3. Use braces on the outer `if` to avoid a potential dangling else
24570   // situation.
24571   verifyFormat("if (isa<VarDecl>(D)) {\n"
24572                "  for (auto *A : D.attrs())\n"
24573                "    if (shouldProcessAttr(A))\n"
24574                "      handleAttr(A);\n"
24575                "}",
24576                "if (isa<VarDecl>(D)) {\n"
24577                "  for (auto *A : D.attrs()) {\n"
24578                "    if (shouldProcessAttr(A)) {\n"
24579                "      handleAttr(A);\n"
24580                "    }\n"
24581                "  }\n"
24582                "}",
24583                Style);
24584 
24585   // 4. Use braces for the `if` block to keep it uniform with the else block.
24586   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24587                "  handleFunctionDecl(D);\n"
24588                "} else {\n"
24589                "  // In this else case, it is necessary that we explain the\n"
24590                "  // situation with this surprisingly long comment, so it\n"
24591                "  // would be unclear without the braces whether the\n"
24592                "  // following statement is in the scope of the `if`.\n"
24593                "  handleOtherDecl(D);\n"
24594                "}",
24595                Style);
24596 
24597   // 5. This should also omit braces.  The `for` loop contains only a single
24598   // statement, so it shouldn't have braces.  The `if` also only contains a
24599   // single simple statement (the for loop), so it also should omit braces.
24600   verifyFormat("if (isa<FunctionDecl>(D))\n"
24601                "  for (auto *A : D.attrs())\n"
24602                "    handleAttr(A);",
24603                "if (isa<FunctionDecl>(D)) {\n"
24604                "  for (auto *A : D.attrs()) {\n"
24605                "    handleAttr(A);\n"
24606                "  }\n"
24607                "}",
24608                Style);
24609 
24610   // 6. Use braces for the outer `if` since the nested `for` is braced.
24611   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24612                "  for (auto *A : D.attrs()) {\n"
24613                "    // In this for loop body, it is necessary that we explain\n"
24614                "    // the situation with this surprisingly long comment,\n"
24615                "    // forcing braces on the `for` block.\n"
24616                "    handleAttr(A);\n"
24617                "  }\n"
24618                "}",
24619                Style);
24620 
24621   // 7. Use braces on the outer block because there are more than two levels of
24622   // nesting.
24623   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
24624                "  for (auto *A : D.attrs())\n"
24625                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
24626                "      handleAttrOnDecl(D, A, i);\n"
24627                "}",
24628                "if (isa<FunctionDecl>(D)) {\n"
24629                "  for (auto *A : D.attrs()) {\n"
24630                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
24631                "      handleAttrOnDecl(D, A, i);\n"
24632                "    }\n"
24633                "  }\n"
24634                "}",
24635                Style);
24636 
24637   // 8. Use braces on the outer block because of a nested `if`, otherwise the
24638   // compiler would warn: `add explicit braces to avoid dangling else`
24639   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
24640                "  if (shouldProcess(D))\n"
24641                "    handleVarDecl(D);\n"
24642                "  else\n"
24643                "    markAsIgnored(D);\n"
24644                "}",
24645                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
24646                "  if (shouldProcess(D)) {\n"
24647                "    handleVarDecl(D);\n"
24648                "  } else {\n"
24649                "    markAsIgnored(D);\n"
24650                "  }\n"
24651                "}",
24652                Style);
24653 
24654   verifyFormat("if (a)\n"
24655                "  b; // comment\n"
24656                "else if (c)\n"
24657                "  d; /* comment */\n"
24658                "else\n"
24659                "  e;",
24660                "if (a) {\n"
24661                "  b; // comment\n"
24662                "} else if (c) {\n"
24663                "  d; /* comment */\n"
24664                "} else {\n"
24665                "  e;\n"
24666                "}",
24667                Style);
24668 
24669   verifyFormat("if (a) {\n"
24670                "  b;\n"
24671                "  c;\n"
24672                "} else if (d) {\n"
24673                "  e;\n"
24674                "}",
24675                Style);
24676 
24677   verifyFormat("if (a) {\n"
24678                "#undef NDEBUG\n"
24679                "  b;\n"
24680                "} else {\n"
24681                "  c;\n"
24682                "}",
24683                Style);
24684 
24685   verifyFormat("if (a) {\n"
24686                "  // comment\n"
24687                "} else if (b) {\n"
24688                "  c;\n"
24689                "}",
24690                Style);
24691 
24692   verifyFormat("if (a) {\n"
24693                "  b;\n"
24694                "} else {\n"
24695                "  { c; }\n"
24696                "}",
24697                Style);
24698 
24699   verifyFormat("if (a) {\n"
24700                "  if (b) // comment\n"
24701                "    c;\n"
24702                "} else if (d) {\n"
24703                "  e;\n"
24704                "}",
24705                "if (a) {\n"
24706                "  if (b) { // comment\n"
24707                "    c;\n"
24708                "  }\n"
24709                "} else if (d) {\n"
24710                "  e;\n"
24711                "}",
24712                Style);
24713 
24714   verifyFormat("if (a) {\n"
24715                "  if (b) {\n"
24716                "    c;\n"
24717                "    // comment\n"
24718                "  } else if (d) {\n"
24719                "    e;\n"
24720                "  }\n"
24721                "}",
24722                Style);
24723 
24724   verifyFormat("if (a) {\n"
24725                "  if (b)\n"
24726                "    c;\n"
24727                "}",
24728                "if (a) {\n"
24729                "  if (b) {\n"
24730                "    c;\n"
24731                "  }\n"
24732                "}",
24733                Style);
24734 
24735   verifyFormat("if (a)\n"
24736                "  if (b)\n"
24737                "    c;\n"
24738                "  else\n"
24739                "    d;\n"
24740                "else\n"
24741                "  e;",
24742                "if (a) {\n"
24743                "  if (b) {\n"
24744                "    c;\n"
24745                "  } else {\n"
24746                "    d;\n"
24747                "  }\n"
24748                "} else {\n"
24749                "  e;\n"
24750                "}",
24751                Style);
24752 
24753   verifyFormat("if (a) {\n"
24754                "  // comment\n"
24755                "  if (b)\n"
24756                "    c;\n"
24757                "  else if (d)\n"
24758                "    e;\n"
24759                "} else {\n"
24760                "  g;\n"
24761                "}",
24762                "if (a) {\n"
24763                "  // comment\n"
24764                "  if (b) {\n"
24765                "    c;\n"
24766                "  } else if (d) {\n"
24767                "    e;\n"
24768                "  }\n"
24769                "} else {\n"
24770                "  g;\n"
24771                "}",
24772                Style);
24773 
24774   verifyFormat("if (a)\n"
24775                "  b;\n"
24776                "else if (c)\n"
24777                "  d;\n"
24778                "else\n"
24779                "  e;",
24780                "if (a) {\n"
24781                "  b;\n"
24782                "} else {\n"
24783                "  if (c) {\n"
24784                "    d;\n"
24785                "  } else {\n"
24786                "    e;\n"
24787                "  }\n"
24788                "}",
24789                Style);
24790 
24791   verifyFormat("if (a) {\n"
24792                "  if (b)\n"
24793                "    c;\n"
24794                "  else if (d)\n"
24795                "    e;\n"
24796                "} else {\n"
24797                "  g;\n"
24798                "}",
24799                "if (a) {\n"
24800                "  if (b)\n"
24801                "    c;\n"
24802                "  else {\n"
24803                "    if (d)\n"
24804                "      e;\n"
24805                "  }\n"
24806                "} else {\n"
24807                "  g;\n"
24808                "}",
24809                Style);
24810 
24811   verifyFormat("if (a)\n"
24812                "  b;\n"
24813                "else if (c)\n"
24814                "  while (d)\n"
24815                "    e;\n"
24816                "// comment",
24817                "if (a)\n"
24818                "{\n"
24819                "  b;\n"
24820                "} else if (c) {\n"
24821                "  while (d) {\n"
24822                "    e;\n"
24823                "  }\n"
24824                "}\n"
24825                "// comment",
24826                Style);
24827 
24828   verifyFormat("if (a) {\n"
24829                "  b;\n"
24830                "} else if (c) {\n"
24831                "  d;\n"
24832                "} else {\n"
24833                "  e;\n"
24834                "  g;\n"
24835                "}",
24836                Style);
24837 
24838   verifyFormat("if (a) {\n"
24839                "  b;\n"
24840                "} else if (c) {\n"
24841                "  d;\n"
24842                "} else {\n"
24843                "  e;\n"
24844                "} // comment",
24845                Style);
24846 
24847   verifyFormat("int abs = [](int i) {\n"
24848                "  if (i >= 0)\n"
24849                "    return i;\n"
24850                "  return -i;\n"
24851                "};",
24852                "int abs = [](int i) {\n"
24853                "  if (i >= 0) {\n"
24854                "    return i;\n"
24855                "  }\n"
24856                "  return -i;\n"
24857                "};",
24858                Style);
24859 
24860   // FIXME: See https://github.com/llvm/llvm-project/issues/53543.
24861 #if 0
24862   Style.ColumnLimit = 65;
24863 
24864   verifyFormat("if (condition) {\n"
24865                "  ff(Indices,\n"
24866                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
24867                "} else {\n"
24868                "  ff(Indices,\n"
24869                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
24870                "}",
24871                Style);
24872 
24873   Style.ColumnLimit = 20;
24874 
24875   verifyFormat("if (a) {\n"
24876                "  b = c + // 1 -\n"
24877                "      d;\n"
24878                "}",
24879                Style);
24880 
24881   verifyFormat("if (a) {\n"
24882                "  b = c >= 0 ? d\n"
24883                "             : e;\n"
24884                "}",
24885                "if (a) {\n"
24886                "  b = c >= 0 ? d : e;\n"
24887                "}",
24888                Style);
24889 #endif
24890 
24891   Style.ColumnLimit = 20;
24892 
24893   verifyFormat("if (a)\n"
24894                "  b = c > 0 ? d : e;",
24895                "if (a) {\n"
24896                "  b = c > 0 ? d : e;\n"
24897                "}",
24898                Style);
24899 
24900   Style.ColumnLimit = 0;
24901 
24902   verifyFormat("if (a)\n"
24903                "  b234567890223456789032345678904234567890 = "
24904                "c234567890223456789032345678904234567890;",
24905                "if (a) {\n"
24906                "  b234567890223456789032345678904234567890 = "
24907                "c234567890223456789032345678904234567890;\n"
24908                "}",
24909                Style);
24910 }
24911 
24912 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
24913   auto Style = getLLVMStyle();
24914 
24915   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
24916                     "void functionDecl(int a, int b, int c);";
24917 
24918   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
24919                      "paramF, paramG, paramH, paramI);\n"
24920                      "void functionDecl(int argumentA, int argumentB, int "
24921                      "argumentC, int argumentD, int argumentE);";
24922 
24923   verifyFormat(Short, Style);
24924 
24925   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
24926                       "paramF, paramG, paramH,\n"
24927                       "             paramI);\n"
24928                       "void functionDecl(int argumentA, int argumentB, int "
24929                       "argumentC, int argumentD,\n"
24930                       "                  int argumentE);";
24931 
24932   verifyFormat(NoBreak, Medium, Style);
24933   verifyFormat(NoBreak,
24934                "functionCall(\n"
24935                "    paramA,\n"
24936                "    paramB,\n"
24937                "    paramC,\n"
24938                "    paramD,\n"
24939                "    paramE,\n"
24940                "    paramF,\n"
24941                "    paramG,\n"
24942                "    paramH,\n"
24943                "    paramI\n"
24944                ");\n"
24945                "void functionDecl(\n"
24946                "    int argumentA,\n"
24947                "    int argumentB,\n"
24948                "    int argumentC,\n"
24949                "    int argumentD,\n"
24950                "    int argumentE\n"
24951                ");",
24952                Style);
24953 
24954   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
24955                "                  nestedLongFunctionCall(argument1, "
24956                "argument2, argument3,\n"
24957                "                                         argument4, "
24958                "argument5));",
24959                Style);
24960 
24961   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
24962 
24963   verifyFormat(Short, Style);
24964   verifyFormat(
24965       "functionCall(\n"
24966       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
24967       "paramI\n"
24968       ");\n"
24969       "void functionDecl(\n"
24970       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
24971       "argumentE\n"
24972       ");",
24973       Medium, Style);
24974 
24975   Style.AllowAllArgumentsOnNextLine = false;
24976   Style.AllowAllParametersOfDeclarationOnNextLine = false;
24977 
24978   verifyFormat(Short, Style);
24979   verifyFormat(
24980       "functionCall(\n"
24981       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
24982       "paramI\n"
24983       ");\n"
24984       "void functionDecl(\n"
24985       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
24986       "argumentE\n"
24987       ");",
24988       Medium, Style);
24989 
24990   Style.BinPackArguments = false;
24991   Style.BinPackParameters = false;
24992 
24993   verifyFormat(Short, Style);
24994 
24995   verifyFormat("functionCall(\n"
24996                "    paramA,\n"
24997                "    paramB,\n"
24998                "    paramC,\n"
24999                "    paramD,\n"
25000                "    paramE,\n"
25001                "    paramF,\n"
25002                "    paramG,\n"
25003                "    paramH,\n"
25004                "    paramI\n"
25005                ");\n"
25006                "void functionDecl(\n"
25007                "    int argumentA,\n"
25008                "    int argumentB,\n"
25009                "    int argumentC,\n"
25010                "    int argumentD,\n"
25011                "    int argumentE\n"
25012                ");",
25013                Medium, Style);
25014 
25015   verifyFormat("outerFunctionCall(\n"
25016                "    nestedFunctionCall(argument1),\n"
25017                "    nestedLongFunctionCall(\n"
25018                "        argument1,\n"
25019                "        argument2,\n"
25020                "        argument3,\n"
25021                "        argument4,\n"
25022                "        argument5\n"
25023                "    )\n"
25024                ");",
25025                Style);
25026 
25027   verifyFormat("int a = (int)b;", Style);
25028   verifyFormat("int a = (int)b;",
25029                "int a = (\n"
25030                "    int\n"
25031                ") b;",
25032                Style);
25033 
25034   verifyFormat("return (true);", Style);
25035   verifyFormat("return (true);",
25036                "return (\n"
25037                "    true\n"
25038                ");",
25039                Style);
25040 
25041   verifyFormat("void foo();", Style);
25042   verifyFormat("void foo();",
25043                "void foo(\n"
25044                ");",
25045                Style);
25046 
25047   verifyFormat("void foo() {}", Style);
25048   verifyFormat("void foo() {}",
25049                "void foo(\n"
25050                ") {\n"
25051                "}",
25052                Style);
25053 
25054   verifyFormat("auto string = std::string();", Style);
25055   verifyFormat("auto string = std::string();",
25056                "auto string = std::string(\n"
25057                ");",
25058                Style);
25059 
25060   verifyFormat("void (*functionPointer)() = nullptr;", Style);
25061   verifyFormat("void (*functionPointer)() = nullptr;",
25062                "void (\n"
25063                "    *functionPointer\n"
25064                ")\n"
25065                "(\n"
25066                ") = nullptr;",
25067                Style);
25068 }
25069 
25070 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
25071   auto Style = getLLVMStyle();
25072 
25073   verifyFormat("if (foo()) {\n"
25074                "  return;\n"
25075                "}",
25076                Style);
25077 
25078   verifyFormat("if (quitelongarg !=\n"
25079                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25080                "comment\n"
25081                "  return;\n"
25082                "}",
25083                Style);
25084 
25085   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25086 
25087   verifyFormat("if (foo()) {\n"
25088                "  return;\n"
25089                "}",
25090                Style);
25091 
25092   verifyFormat("if (quitelongarg !=\n"
25093                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
25094                "comment\n"
25095                "  return;\n"
25096                "}",
25097                Style);
25098 }
25099 
25100 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
25101   auto Style = getLLVMStyle();
25102 
25103   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25104                "  doSomething();\n"
25105                "}",
25106                Style);
25107 
25108   verifyFormat("for (int myReallyLongCountVariable = 0; "
25109                "myReallyLongCountVariable < count;\n"
25110                "     myReallyLongCountVariable++) {\n"
25111                "  doSomething();\n"
25112                "}",
25113                Style);
25114 
25115   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
25116 
25117   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
25118                "  doSomething();\n"
25119                "}",
25120                Style);
25121 
25122   verifyFormat("for (int myReallyLongCountVariable = 0; "
25123                "myReallyLongCountVariable < count;\n"
25124                "     myReallyLongCountVariable++) {\n"
25125                "  doSomething();\n"
25126                "}",
25127                Style);
25128 }
25129 
25130 TEST_F(FormatTest, UnderstandsDigraphs) {
25131   verifyFormat("int arr<:5:> = {};");
25132   verifyFormat("int arr[5] = <%%>;");
25133   verifyFormat("int arr<:::qualified_variable:> = {};");
25134   verifyFormat("int arr[::qualified_variable] = <%%>;");
25135   verifyFormat("%:include <header>");
25136   verifyFormat("%:define A x##y");
25137   verifyFormat("#define A x%:%:y");
25138 }
25139 
25140 } // namespace
25141 } // namespace format
25142 } // namespace clang
25143