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("while (true)\n"
1468                "  ;",
1469                AllowsMergedLoops);
1470   verifyFormat("for (;;)\n"
1471                "  ;",
1472                AllowsMergedLoops);
1473   verifyFormat("for (;;)\n"
1474                "  for (;;) continue;",
1475                AllowsMergedLoops);
1476   verifyFormat("for (;;) // Can't merge this\n"
1477                "  continue;",
1478                AllowsMergedLoops);
1479   verifyFormat("for (;;) /* still don't merge */\n"
1480                "  continue;",
1481                AllowsMergedLoops);
1482   verifyFormat("do a++;\n"
1483                "while (true);",
1484                AllowsMergedLoops);
1485   verifyFormat("do /* Don't merge */\n"
1486                "  a++;\n"
1487                "while (true);",
1488                AllowsMergedLoops);
1489   verifyFormat("do // Don't merge\n"
1490                "  a++;\n"
1491                "while (true);",
1492                AllowsMergedLoops);
1493   verifyFormat("do\n"
1494                "  // Don't merge\n"
1495                "  a++;\n"
1496                "while (true);",
1497                AllowsMergedLoops);
1498   // Without braces labels are interpreted differently.
1499   verifyFormat("{\n"
1500                "  do\n"
1501                "  label:\n"
1502                "    a++;\n"
1503                "  while (true);\n"
1504                "}",
1505                AllowsMergedLoops);
1506 }
1507 
1508 TEST_F(FormatTest, FormatShortBracedStatements) {
1509   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
1510   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1511   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1512   // Not IF to avoid any confusion that IF is somehow special.
1513   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1514   AllowSimpleBracedStatements.ColumnLimit = 40;
1515   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1516       FormatStyle::SBS_Always;
1517 
1518   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1519       FormatStyle::SIS_WithoutElse;
1520   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1521 
1522   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1523   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1524   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1525 
1526   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1527   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1528   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1529   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1530   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1531   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1532   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1533   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1534   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1535   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1536   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1537   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1538   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1539   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1540   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1541   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1542   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1543                AllowSimpleBracedStatements);
1544   verifyFormat("if (true) {\n"
1545                "  ffffffffffffffffffffffff();\n"
1546                "}",
1547                AllowSimpleBracedStatements);
1548   verifyFormat("if (true) {\n"
1549                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1550                "}",
1551                AllowSimpleBracedStatements);
1552   verifyFormat("if (true) { //\n"
1553                "  f();\n"
1554                "}",
1555                AllowSimpleBracedStatements);
1556   verifyFormat("if (true) {\n"
1557                "  f();\n"
1558                "  f();\n"
1559                "}",
1560                AllowSimpleBracedStatements);
1561   verifyFormat("if (true) {\n"
1562                "  f();\n"
1563                "} else {\n"
1564                "  f();\n"
1565                "}",
1566                AllowSimpleBracedStatements);
1567   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1568                AllowSimpleBracedStatements);
1569   verifyFormat("MYIF (true) {\n"
1570                "  ffffffffffffffffffffffff();\n"
1571                "}",
1572                AllowSimpleBracedStatements);
1573   verifyFormat("MYIF (true) {\n"
1574                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1575                "}",
1576                AllowSimpleBracedStatements);
1577   verifyFormat("MYIF (true) { //\n"
1578                "  f();\n"
1579                "}",
1580                AllowSimpleBracedStatements);
1581   verifyFormat("MYIF (true) {\n"
1582                "  f();\n"
1583                "  f();\n"
1584                "}",
1585                AllowSimpleBracedStatements);
1586   verifyFormat("MYIF (true) {\n"
1587                "  f();\n"
1588                "} else {\n"
1589                "  f();\n"
1590                "}",
1591                AllowSimpleBracedStatements);
1592 
1593   verifyFormat("struct A2 {\n"
1594                "  int X;\n"
1595                "};",
1596                AllowSimpleBracedStatements);
1597   verifyFormat("typedef struct A2 {\n"
1598                "  int X;\n"
1599                "} A2_t;",
1600                AllowSimpleBracedStatements);
1601   verifyFormat("template <int> struct A2 {\n"
1602                "  struct B {};\n"
1603                "};",
1604                AllowSimpleBracedStatements);
1605 
1606   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1607       FormatStyle::SIS_Never;
1608   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1609   verifyFormat("if (true) {\n"
1610                "  f();\n"
1611                "}",
1612                AllowSimpleBracedStatements);
1613   verifyFormat("if (true) {\n"
1614                "  f();\n"
1615                "} else {\n"
1616                "  f();\n"
1617                "}",
1618                AllowSimpleBracedStatements);
1619   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1620   verifyFormat("MYIF (true) {\n"
1621                "  f();\n"
1622                "}",
1623                AllowSimpleBracedStatements);
1624   verifyFormat("MYIF (true) {\n"
1625                "  f();\n"
1626                "} else {\n"
1627                "  f();\n"
1628                "}",
1629                AllowSimpleBracedStatements);
1630 
1631   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1632   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1633   verifyFormat("while (true) {\n"
1634                "  f();\n"
1635                "}",
1636                AllowSimpleBracedStatements);
1637   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1638   verifyFormat("for (;;) {\n"
1639                "  f();\n"
1640                "}",
1641                AllowSimpleBracedStatements);
1642 
1643   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1644       FormatStyle::SIS_WithoutElse;
1645   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1646   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1647       FormatStyle::BWACS_Always;
1648 
1649   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1650   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1651   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1652   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1653   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1654   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1655   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1656   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1657   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1658   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1659   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1660   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1661   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1662   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1663   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1664   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1665   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1666                AllowSimpleBracedStatements);
1667   verifyFormat("if (true)\n"
1668                "{\n"
1669                "  ffffffffffffffffffffffff();\n"
1670                "}",
1671                AllowSimpleBracedStatements);
1672   verifyFormat("if (true)\n"
1673                "{\n"
1674                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1675                "}",
1676                AllowSimpleBracedStatements);
1677   verifyFormat("if (true)\n"
1678                "{ //\n"
1679                "  f();\n"
1680                "}",
1681                AllowSimpleBracedStatements);
1682   verifyFormat("if (true)\n"
1683                "{\n"
1684                "  f();\n"
1685                "  f();\n"
1686                "}",
1687                AllowSimpleBracedStatements);
1688   verifyFormat("if (true)\n"
1689                "{\n"
1690                "  f();\n"
1691                "} else\n"
1692                "{\n"
1693                "  f();\n"
1694                "}",
1695                AllowSimpleBracedStatements);
1696   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1697                AllowSimpleBracedStatements);
1698   verifyFormat("MYIF (true)\n"
1699                "{\n"
1700                "  ffffffffffffffffffffffff();\n"
1701                "}",
1702                AllowSimpleBracedStatements);
1703   verifyFormat("MYIF (true)\n"
1704                "{\n"
1705                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1706                "}",
1707                AllowSimpleBracedStatements);
1708   verifyFormat("MYIF (true)\n"
1709                "{ //\n"
1710                "  f();\n"
1711                "}",
1712                AllowSimpleBracedStatements);
1713   verifyFormat("MYIF (true)\n"
1714                "{\n"
1715                "  f();\n"
1716                "  f();\n"
1717                "}",
1718                AllowSimpleBracedStatements);
1719   verifyFormat("MYIF (true)\n"
1720                "{\n"
1721                "  f();\n"
1722                "} else\n"
1723                "{\n"
1724                "  f();\n"
1725                "}",
1726                AllowSimpleBracedStatements);
1727 
1728   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1729       FormatStyle::SIS_Never;
1730   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1731   verifyFormat("if (true)\n"
1732                "{\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("MYIF (true) {}", AllowSimpleBracedStatements);
1745   verifyFormat("MYIF (true)\n"
1746                "{\n"
1747                "  f();\n"
1748                "}",
1749                AllowSimpleBracedStatements);
1750   verifyFormat("MYIF (true)\n"
1751                "{\n"
1752                "  f();\n"
1753                "} else\n"
1754                "{\n"
1755                "  f();\n"
1756                "}",
1757                AllowSimpleBracedStatements);
1758 
1759   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1760   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1761   verifyFormat("while (true)\n"
1762                "{\n"
1763                "  f();\n"
1764                "}",
1765                AllowSimpleBracedStatements);
1766   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1767   verifyFormat("for (;;)\n"
1768                "{\n"
1769                "  f();\n"
1770                "}",
1771                AllowSimpleBracedStatements);
1772 }
1773 
1774 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1775   FormatStyle Style = getLLVMStyleWithColumns(60);
1776   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1777   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1778   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1779   EXPECT_EQ("#define A                                                  \\\n"
1780             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1781             "  {                                                        \\\n"
1782             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1783             "  }\n"
1784             "X;",
1785             format("#define A \\\n"
1786                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1787                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1788                    "   }\n"
1789                    "X;",
1790                    Style));
1791 }
1792 
1793 TEST_F(FormatTest, ParseIfElse) {
1794   verifyFormat("if (true)\n"
1795                "  if (true)\n"
1796                "    if (true)\n"
1797                "      f();\n"
1798                "    else\n"
1799                "      g();\n"
1800                "  else\n"
1801                "    h();\n"
1802                "else\n"
1803                "  i();");
1804   verifyFormat("if (true)\n"
1805                "  if (true)\n"
1806                "    if (true) {\n"
1807                "      if (true)\n"
1808                "        f();\n"
1809                "    } else {\n"
1810                "      g();\n"
1811                "    }\n"
1812                "  else\n"
1813                "    h();\n"
1814                "else {\n"
1815                "  i();\n"
1816                "}");
1817   verifyFormat("if (true)\n"
1818                "  if constexpr (true)\n"
1819                "    if (true) {\n"
1820                "      if constexpr (true)\n"
1821                "        f();\n"
1822                "    } else {\n"
1823                "      g();\n"
1824                "    }\n"
1825                "  else\n"
1826                "    h();\n"
1827                "else {\n"
1828                "  i();\n"
1829                "}");
1830   verifyFormat("if (true)\n"
1831                "  if CONSTEXPR (true)\n"
1832                "    if (true) {\n"
1833                "      if CONSTEXPR (true)\n"
1834                "        f();\n"
1835                "    } else {\n"
1836                "      g();\n"
1837                "    }\n"
1838                "  else\n"
1839                "    h();\n"
1840                "else {\n"
1841                "  i();\n"
1842                "}");
1843   verifyFormat("void f() {\n"
1844                "  if (a) {\n"
1845                "  } else {\n"
1846                "  }\n"
1847                "}");
1848 }
1849 
1850 TEST_F(FormatTest, ElseIf) {
1851   verifyFormat("if (a) {\n} else if (b) {\n}");
1852   verifyFormat("if (a)\n"
1853                "  f();\n"
1854                "else if (b)\n"
1855                "  g();\n"
1856                "else\n"
1857                "  h();");
1858   verifyFormat("if (a)\n"
1859                "  f();\n"
1860                "else // comment\n"
1861                "  if (b) {\n"
1862                "    g();\n"
1863                "    h();\n"
1864                "  }");
1865   verifyFormat("if constexpr (a)\n"
1866                "  f();\n"
1867                "else if constexpr (b)\n"
1868                "  g();\n"
1869                "else\n"
1870                "  h();");
1871   verifyFormat("if CONSTEXPR (a)\n"
1872                "  f();\n"
1873                "else if CONSTEXPR (b)\n"
1874                "  g();\n"
1875                "else\n"
1876                "  h();");
1877   verifyFormat("if (a) {\n"
1878                "  f();\n"
1879                "}\n"
1880                "// or else ..\n"
1881                "else {\n"
1882                "  g()\n"
1883                "}");
1884 
1885   verifyFormat("if (a) {\n"
1886                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1887                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1888                "}");
1889   verifyFormat("if (a) {\n"
1890                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1891                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1892                "}");
1893   verifyFormat("if (a) {\n"
1894                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1895                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1896                "}");
1897   verifyFormat("if (a) {\n"
1898                "} else if (\n"
1899                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1900                "}",
1901                getLLVMStyleWithColumns(62));
1902   verifyFormat("if (a) {\n"
1903                "} else if constexpr (\n"
1904                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1905                "}",
1906                getLLVMStyleWithColumns(62));
1907   verifyFormat("if (a) {\n"
1908                "} else if CONSTEXPR (\n"
1909                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1910                "}",
1911                getLLVMStyleWithColumns(62));
1912 }
1913 
1914 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
1915   FormatStyle Style = getLLVMStyle();
1916   // Check first the default LLVM style
1917   // Style.PointerAlignment = FormatStyle::PAS_Right;
1918   // Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1919   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
1920   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
1921   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
1922   verifyFormat("int *f1(int &a) const &;", Style);
1923   verifyFormat("int *f1(int &a) const & = 0;", Style);
1924   verifyFormat("int *a = f1();", Style);
1925   verifyFormat("int &b = f2();", Style);
1926   verifyFormat("int &&c = f3();", Style);
1927   verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
1928   verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
1929   verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
1930   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
1931   verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
1932   verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
1933   verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
1934   verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
1935   verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
1936   verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
1937   verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
1938   verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
1939   verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
1940   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
1941   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
1942   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
1943 
1944   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1945   verifyFormat("Const unsigned int *c;\n"
1946                "const unsigned int *d;\n"
1947                "Const unsigned int &e;\n"
1948                "const unsigned int &f;\n"
1949                "const unsigned    &&g;\n"
1950                "Const unsigned      h;",
1951                Style);
1952 
1953   Style.PointerAlignment = FormatStyle::PAS_Left;
1954   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1955   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
1956   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
1957   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
1958   verifyFormat("int* f1(int& a) const& = 0;", Style);
1959   verifyFormat("int* a = f1();", Style);
1960   verifyFormat("int& b = f2();", Style);
1961   verifyFormat("int&& c = f3();", Style);
1962   verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
1963   verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
1964   verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
1965   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
1966   verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
1967   verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
1968   verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
1969   verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
1970   verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
1971   verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
1972   verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
1973   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
1974   verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
1975   verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
1976   verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
1977   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
1978   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
1979   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
1980 
1981   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1982   verifyFormat("Const unsigned int* c;\n"
1983                "const unsigned int* d;\n"
1984                "Const unsigned int& e;\n"
1985                "const unsigned int& f;\n"
1986                "const unsigned&&    g;\n"
1987                "Const unsigned      h;",
1988                Style);
1989 
1990   Style.PointerAlignment = FormatStyle::PAS_Right;
1991   Style.ReferenceAlignment = FormatStyle::RAS_Left;
1992   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
1993   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
1994   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
1995   verifyFormat("int *a = f1();", Style);
1996   verifyFormat("int& b = f2();", Style);
1997   verifyFormat("int&& c = f3();", Style);
1998   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
1999   verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2000   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
2001 
2002   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2003   verifyFormat("Const unsigned int *c;\n"
2004                "const unsigned int *d;\n"
2005                "Const unsigned int& e;\n"
2006                "const unsigned int& f;\n"
2007                "const unsigned      g;\n"
2008                "Const unsigned      h;",
2009                Style);
2010 
2011   Style.PointerAlignment = FormatStyle::PAS_Left;
2012   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
2013   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
2014   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
2015   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
2016   verifyFormat("int* a = f1();", Style);
2017   verifyFormat("int & b = f2();", Style);
2018   verifyFormat("int && c = f3();", Style);
2019   verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
2020   verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
2021   verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
2022   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2023   verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
2024   verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
2025   verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
2026   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2027   verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
2028   verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
2029   verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
2030   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
2031   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
2032   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
2033 
2034   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
2035   verifyFormat("Const unsigned int*  c;\n"
2036                "const unsigned int*  d;\n"
2037                "Const unsigned int & e;\n"
2038                "const unsigned int & f;\n"
2039                "const unsigned &&    g;\n"
2040                "Const unsigned       h;",
2041                Style);
2042 
2043   Style.PointerAlignment = FormatStyle::PAS_Middle;
2044   Style.ReferenceAlignment = FormatStyle::RAS_Right;
2045   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
2046   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
2047   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
2048   verifyFormat("int * a = f1();", Style);
2049   verifyFormat("int &b = f2();", Style);
2050   verifyFormat("int &&c = f3();", Style);
2051   verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2052   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2053   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
2054 
2055   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2056   // specifically handled
2057   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2058 }
2059 
2060 TEST_F(FormatTest, FormatsForLoop) {
2061   verifyFormat(
2062       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2063       "     ++VeryVeryLongLoopVariable)\n"
2064       "  ;");
2065   verifyFormat("for (;;)\n"
2066                "  f();");
2067   verifyFormat("for (;;) {\n}");
2068   verifyFormat("for (;;) {\n"
2069                "  f();\n"
2070                "}");
2071   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2072 
2073   verifyFormat(
2074       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2075       "                                          E = UnwrappedLines.end();\n"
2076       "     I != E; ++I) {\n}");
2077 
2078   verifyFormat(
2079       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2080       "     ++IIIII) {\n}");
2081   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2082                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2083                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2084   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2085                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2086                "         E = FD->getDeclsInPrototypeScope().end();\n"
2087                "     I != E; ++I) {\n}");
2088   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2089                "         I = Container.begin(),\n"
2090                "         E = Container.end();\n"
2091                "     I != E; ++I) {\n}",
2092                getLLVMStyleWithColumns(76));
2093 
2094   verifyFormat(
2095       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2096       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2097       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2098       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2099       "     ++aaaaaaaaaaa) {\n}");
2100   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2101                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2102                "     ++i) {\n}");
2103   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2104                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2105                "}");
2106   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2107                "         aaaaaaaaaa);\n"
2108                "     iter; ++iter) {\n"
2109                "}");
2110   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2111                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2112                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2113                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2114 
2115   // These should not be formatted as Objective-C for-in loops.
2116   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2117   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2118   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2119   verifyFormat(
2120       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2121 
2122   FormatStyle NoBinPacking = getLLVMStyle();
2123   NoBinPacking.BinPackParameters = false;
2124   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2125                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2126                "                                           aaaaaaaaaaaaaaaa,\n"
2127                "                                           aaaaaaaaaaaaaaaa,\n"
2128                "                                           aaaaaaaaaaaaaaaa);\n"
2129                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2130                "}",
2131                NoBinPacking);
2132   verifyFormat(
2133       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2134       "                                          E = UnwrappedLines.end();\n"
2135       "     I != E;\n"
2136       "     ++I) {\n}",
2137       NoBinPacking);
2138 
2139   FormatStyle AlignLeft = getLLVMStyle();
2140   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2141   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2142 }
2143 
2144 TEST_F(FormatTest, RangeBasedForLoops) {
2145   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2146                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2147   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2148                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2149   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2150                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2151   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2152                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2153 }
2154 
2155 TEST_F(FormatTest, ForEachLoops) {
2156   verifyFormat("void f() {\n"
2157                "  foreach (Item *item, itemlist) {}\n"
2158                "  Q_FOREACH (Item *item, itemlist) {}\n"
2159                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
2160                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
2161                "}");
2162 
2163   FormatStyle Style = getLLVMStyle();
2164   Style.SpaceBeforeParens =
2165       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2166   verifyFormat("void f() {\n"
2167                "  foreach(Item *item, itemlist) {}\n"
2168                "  Q_FOREACH(Item *item, itemlist) {}\n"
2169                "  BOOST_FOREACH(Item *item, itemlist) {}\n"
2170                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
2171                "}",
2172                Style);
2173 
2174   // As function-like macros.
2175   verifyFormat("#define foreach(x, y)\n"
2176                "#define Q_FOREACH(x, y)\n"
2177                "#define BOOST_FOREACH(x, y)\n"
2178                "#define UNKNOWN_FOREACH(x, y)\n");
2179 
2180   // Not as function-like macros.
2181   verifyFormat("#define foreach (x, y)\n"
2182                "#define Q_FOREACH (x, y)\n"
2183                "#define BOOST_FOREACH (x, y)\n"
2184                "#define UNKNOWN_FOREACH (x, y)\n");
2185 
2186   // handle microsoft non standard extension
2187   verifyFormat("for each (char c in x->MyStringProperty)");
2188 }
2189 
2190 TEST_F(FormatTest, FormatsWhileLoop) {
2191   verifyFormat("while (true) {\n}");
2192   verifyFormat("while (true)\n"
2193                "  f();");
2194   verifyFormat("while () {\n}");
2195   verifyFormat("while () {\n"
2196                "  f();\n"
2197                "}");
2198 }
2199 
2200 TEST_F(FormatTest, FormatsDoWhile) {
2201   verifyFormat("do {\n"
2202                "  do_something();\n"
2203                "} while (something());");
2204   verifyFormat("do\n"
2205                "  do_something();\n"
2206                "while (something());");
2207 }
2208 
2209 TEST_F(FormatTest, FormatsSwitchStatement) {
2210   verifyFormat("switch (x) {\n"
2211                "case 1:\n"
2212                "  f();\n"
2213                "  break;\n"
2214                "case kFoo:\n"
2215                "case ns::kBar:\n"
2216                "case kBaz:\n"
2217                "  break;\n"
2218                "default:\n"
2219                "  g();\n"
2220                "  break;\n"
2221                "}");
2222   verifyFormat("switch (x) {\n"
2223                "case 1: {\n"
2224                "  f();\n"
2225                "  break;\n"
2226                "}\n"
2227                "case 2: {\n"
2228                "  break;\n"
2229                "}\n"
2230                "}");
2231   verifyFormat("switch (x) {\n"
2232                "case 1: {\n"
2233                "  f();\n"
2234                "  {\n"
2235                "    g();\n"
2236                "    h();\n"
2237                "  }\n"
2238                "  break;\n"
2239                "}\n"
2240                "}");
2241   verifyFormat("switch (x) {\n"
2242                "case 1: {\n"
2243                "  f();\n"
2244                "  if (foo) {\n"
2245                "    g();\n"
2246                "    h();\n"
2247                "  }\n"
2248                "  break;\n"
2249                "}\n"
2250                "}");
2251   verifyFormat("switch (x) {\n"
2252                "case 1: {\n"
2253                "  f();\n"
2254                "  g();\n"
2255                "} break;\n"
2256                "}");
2257   verifyFormat("switch (test)\n"
2258                "  ;");
2259   verifyFormat("switch (x) {\n"
2260                "default: {\n"
2261                "  // Do nothing.\n"
2262                "}\n"
2263                "}");
2264   verifyFormat("switch (x) {\n"
2265                "// comment\n"
2266                "// if 1, do f()\n"
2267                "case 1:\n"
2268                "  f();\n"
2269                "}");
2270   verifyFormat("switch (x) {\n"
2271                "case 1:\n"
2272                "  // Do amazing stuff\n"
2273                "  {\n"
2274                "    f();\n"
2275                "    g();\n"
2276                "  }\n"
2277                "  break;\n"
2278                "}");
2279   verifyFormat("#define A          \\\n"
2280                "  switch (x) {     \\\n"
2281                "  case a:          \\\n"
2282                "    foo = b;       \\\n"
2283                "  }",
2284                getLLVMStyleWithColumns(20));
2285   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2286                "  case OP_name:                        \\\n"
2287                "    return operations::Operation##name\n",
2288                getLLVMStyleWithColumns(40));
2289   verifyFormat("switch (x) {\n"
2290                "case 1:;\n"
2291                "default:;\n"
2292                "  int i;\n"
2293                "}");
2294 
2295   verifyGoogleFormat("switch (x) {\n"
2296                      "  case 1:\n"
2297                      "    f();\n"
2298                      "    break;\n"
2299                      "  case kFoo:\n"
2300                      "  case ns::kBar:\n"
2301                      "  case kBaz:\n"
2302                      "    break;\n"
2303                      "  default:\n"
2304                      "    g();\n"
2305                      "    break;\n"
2306                      "}");
2307   verifyGoogleFormat("switch (x) {\n"
2308                      "  case 1: {\n"
2309                      "    f();\n"
2310                      "    break;\n"
2311                      "  }\n"
2312                      "}");
2313   verifyGoogleFormat("switch (test)\n"
2314                      "  ;");
2315 
2316   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2317                      "  case OP_name:              \\\n"
2318                      "    return operations::Operation##name\n");
2319   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2320                      "  // Get the correction operation class.\n"
2321                      "  switch (OpCode) {\n"
2322                      "    CASE(Add);\n"
2323                      "    CASE(Subtract);\n"
2324                      "    default:\n"
2325                      "      return operations::Unknown;\n"
2326                      "  }\n"
2327                      "#undef OPERATION_CASE\n"
2328                      "}");
2329   verifyFormat("DEBUG({\n"
2330                "  switch (x) {\n"
2331                "  case A:\n"
2332                "    f();\n"
2333                "    break;\n"
2334                "    // fallthrough\n"
2335                "  case B:\n"
2336                "    g();\n"
2337                "    break;\n"
2338                "  }\n"
2339                "});");
2340   EXPECT_EQ("DEBUG({\n"
2341             "  switch (x) {\n"
2342             "  case A:\n"
2343             "    f();\n"
2344             "    break;\n"
2345             "  // On B:\n"
2346             "  case B:\n"
2347             "    g();\n"
2348             "    break;\n"
2349             "  }\n"
2350             "});",
2351             format("DEBUG({\n"
2352                    "  switch (x) {\n"
2353                    "  case A:\n"
2354                    "    f();\n"
2355                    "    break;\n"
2356                    "  // On B:\n"
2357                    "  case B:\n"
2358                    "    g();\n"
2359                    "    break;\n"
2360                    "  }\n"
2361                    "});",
2362                    getLLVMStyle()));
2363   EXPECT_EQ("switch (n) {\n"
2364             "case 0: {\n"
2365             "  return false;\n"
2366             "}\n"
2367             "default: {\n"
2368             "  return true;\n"
2369             "}\n"
2370             "}",
2371             format("switch (n)\n"
2372                    "{\n"
2373                    "case 0: {\n"
2374                    "  return false;\n"
2375                    "}\n"
2376                    "default: {\n"
2377                    "  return true;\n"
2378                    "}\n"
2379                    "}",
2380                    getLLVMStyle()));
2381   verifyFormat("switch (a) {\n"
2382                "case (b):\n"
2383                "  return;\n"
2384                "}");
2385 
2386   verifyFormat("switch (a) {\n"
2387                "case some_namespace::\n"
2388                "    some_constant:\n"
2389                "  return;\n"
2390                "}",
2391                getLLVMStyleWithColumns(34));
2392 
2393   FormatStyle Style = getLLVMStyle();
2394   Style.IndentCaseLabels = true;
2395   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2396   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2397   Style.BraceWrapping.AfterCaseLabel = true;
2398   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2399   EXPECT_EQ("switch (n)\n"
2400             "{\n"
2401             "  case 0:\n"
2402             "  {\n"
2403             "    return false;\n"
2404             "  }\n"
2405             "  default:\n"
2406             "  {\n"
2407             "    return true;\n"
2408             "  }\n"
2409             "}",
2410             format("switch (n) {\n"
2411                    "  case 0: {\n"
2412                    "    return false;\n"
2413                    "  }\n"
2414                    "  default: {\n"
2415                    "    return true;\n"
2416                    "  }\n"
2417                    "}",
2418                    Style));
2419   Style.BraceWrapping.AfterCaseLabel = false;
2420   EXPECT_EQ("switch (n)\n"
2421             "{\n"
2422             "  case 0: {\n"
2423             "    return false;\n"
2424             "  }\n"
2425             "  default: {\n"
2426             "    return true;\n"
2427             "  }\n"
2428             "}",
2429             format("switch (n) {\n"
2430                    "  case 0:\n"
2431                    "  {\n"
2432                    "    return false;\n"
2433                    "  }\n"
2434                    "  default:\n"
2435                    "  {\n"
2436                    "    return true;\n"
2437                    "  }\n"
2438                    "}",
2439                    Style));
2440   Style.IndentCaseLabels = false;
2441   Style.IndentCaseBlocks = true;
2442   EXPECT_EQ("switch (n)\n"
2443             "{\n"
2444             "case 0:\n"
2445             "  {\n"
2446             "    return false;\n"
2447             "  }\n"
2448             "case 1:\n"
2449             "  break;\n"
2450             "default:\n"
2451             "  {\n"
2452             "    return true;\n"
2453             "  }\n"
2454             "}",
2455             format("switch (n) {\n"
2456                    "case 0: {\n"
2457                    "  return false;\n"
2458                    "}\n"
2459                    "case 1:\n"
2460                    "  break;\n"
2461                    "default: {\n"
2462                    "  return true;\n"
2463                    "}\n"
2464                    "}",
2465                    Style));
2466   Style.IndentCaseLabels = true;
2467   Style.IndentCaseBlocks = true;
2468   EXPECT_EQ("switch (n)\n"
2469             "{\n"
2470             "  case 0:\n"
2471             "    {\n"
2472             "      return false;\n"
2473             "    }\n"
2474             "  case 1:\n"
2475             "    break;\n"
2476             "  default:\n"
2477             "    {\n"
2478             "      return true;\n"
2479             "    }\n"
2480             "}",
2481             format("switch (n) {\n"
2482                    "case 0: {\n"
2483                    "  return false;\n"
2484                    "}\n"
2485                    "case 1:\n"
2486                    "  break;\n"
2487                    "default: {\n"
2488                    "  return true;\n"
2489                    "}\n"
2490                    "}",
2491                    Style));
2492 }
2493 
2494 TEST_F(FormatTest, CaseRanges) {
2495   verifyFormat("switch (x) {\n"
2496                "case 'A' ... 'Z':\n"
2497                "case 1 ... 5:\n"
2498                "case a ... b:\n"
2499                "  break;\n"
2500                "}");
2501 }
2502 
2503 TEST_F(FormatTest, ShortEnums) {
2504   FormatStyle Style = getLLVMStyle();
2505   Style.AllowShortEnumsOnASingleLine = true;
2506   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2507   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2508   Style.AllowShortEnumsOnASingleLine = false;
2509   verifyFormat("enum {\n"
2510                "  A,\n"
2511                "  B,\n"
2512                "  C\n"
2513                "} ShortEnum1, ShortEnum2;",
2514                Style);
2515   verifyFormat("typedef enum {\n"
2516                "  A,\n"
2517                "  B,\n"
2518                "  C\n"
2519                "} ShortEnum1, ShortEnum2;",
2520                Style);
2521   verifyFormat("enum {\n"
2522                "  A,\n"
2523                "} ShortEnum1, ShortEnum2;",
2524                Style);
2525   verifyFormat("typedef enum {\n"
2526                "  A,\n"
2527                "} ShortEnum1, ShortEnum2;",
2528                Style);
2529   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2530   Style.BraceWrapping.AfterEnum = true;
2531   verifyFormat("enum\n"
2532                "{\n"
2533                "  A,\n"
2534                "  B,\n"
2535                "  C\n"
2536                "} ShortEnum1, ShortEnum2;",
2537                Style);
2538 }
2539 
2540 TEST_F(FormatTest, ShortCaseLabels) {
2541   FormatStyle Style = getLLVMStyle();
2542   Style.AllowShortCaseLabelsOnASingleLine = true;
2543   verifyFormat("switch (a) {\n"
2544                "case 1: x = 1; break;\n"
2545                "case 2: return;\n"
2546                "case 3:\n"
2547                "case 4:\n"
2548                "case 5: return;\n"
2549                "case 6: // comment\n"
2550                "  return;\n"
2551                "case 7:\n"
2552                "  // comment\n"
2553                "  return;\n"
2554                "case 8:\n"
2555                "  x = 8; // comment\n"
2556                "  break;\n"
2557                "default: y = 1; break;\n"
2558                "}",
2559                Style);
2560   verifyFormat("switch (a) {\n"
2561                "case 0: return; // comment\n"
2562                "case 1: break;  // comment\n"
2563                "case 2: return;\n"
2564                "// comment\n"
2565                "case 3: return;\n"
2566                "// comment 1\n"
2567                "// comment 2\n"
2568                "// comment 3\n"
2569                "case 4: break; /* comment */\n"
2570                "case 5:\n"
2571                "  // comment\n"
2572                "  break;\n"
2573                "case 6: /* comment */ x = 1; break;\n"
2574                "case 7: x = /* comment */ 1; break;\n"
2575                "case 8:\n"
2576                "  x = 1; /* comment */\n"
2577                "  break;\n"
2578                "case 9:\n"
2579                "  break; // comment line 1\n"
2580                "         // comment line 2\n"
2581                "}",
2582                Style);
2583   EXPECT_EQ("switch (a) {\n"
2584             "case 1:\n"
2585             "  x = 8;\n"
2586             "  // fall through\n"
2587             "case 2: x = 8;\n"
2588             "// comment\n"
2589             "case 3:\n"
2590             "  return; /* comment line 1\n"
2591             "           * comment line 2 */\n"
2592             "case 4: i = 8;\n"
2593             "// something else\n"
2594             "#if FOO\n"
2595             "case 5: break;\n"
2596             "#endif\n"
2597             "}",
2598             format("switch (a) {\n"
2599                    "case 1: x = 8;\n"
2600                    "  // fall through\n"
2601                    "case 2:\n"
2602                    "  x = 8;\n"
2603                    "// comment\n"
2604                    "case 3:\n"
2605                    "  return; /* comment line 1\n"
2606                    "           * comment line 2 */\n"
2607                    "case 4:\n"
2608                    "  i = 8;\n"
2609                    "// something else\n"
2610                    "#if FOO\n"
2611                    "case 5: break;\n"
2612                    "#endif\n"
2613                    "}",
2614                    Style));
2615   EXPECT_EQ("switch (a) {\n"
2616             "case 0:\n"
2617             "  return; // long long long long long long long long long long "
2618             "long long comment\n"
2619             "          // line\n"
2620             "}",
2621             format("switch (a) {\n"
2622                    "case 0: return; // long long long long long long long long "
2623                    "long long long long comment line\n"
2624                    "}",
2625                    Style));
2626   EXPECT_EQ("switch (a) {\n"
2627             "case 0:\n"
2628             "  return; /* long long long long long long long long long long "
2629             "long long comment\n"
2630             "             line */\n"
2631             "}",
2632             format("switch (a) {\n"
2633                    "case 0: return; /* long long long long long long long long "
2634                    "long long long long comment line */\n"
2635                    "}",
2636                    Style));
2637   verifyFormat("switch (a) {\n"
2638                "#if FOO\n"
2639                "case 0: return 0;\n"
2640                "#endif\n"
2641                "}",
2642                Style);
2643   verifyFormat("switch (a) {\n"
2644                "case 1: {\n"
2645                "}\n"
2646                "case 2: {\n"
2647                "  return;\n"
2648                "}\n"
2649                "case 3: {\n"
2650                "  x = 1;\n"
2651                "  return;\n"
2652                "}\n"
2653                "case 4:\n"
2654                "  if (x)\n"
2655                "    return;\n"
2656                "}",
2657                Style);
2658   Style.ColumnLimit = 21;
2659   verifyFormat("switch (a) {\n"
2660                "case 1: x = 1; break;\n"
2661                "case 2: return;\n"
2662                "case 3:\n"
2663                "case 4:\n"
2664                "case 5: return;\n"
2665                "default:\n"
2666                "  y = 1;\n"
2667                "  break;\n"
2668                "}",
2669                Style);
2670   Style.ColumnLimit = 80;
2671   Style.AllowShortCaseLabelsOnASingleLine = false;
2672   Style.IndentCaseLabels = true;
2673   EXPECT_EQ("switch (n) {\n"
2674             "  default /*comments*/:\n"
2675             "    return true;\n"
2676             "  case 0:\n"
2677             "    return false;\n"
2678             "}",
2679             format("switch (n) {\n"
2680                    "default/*comments*/:\n"
2681                    "  return true;\n"
2682                    "case 0:\n"
2683                    "  return false;\n"
2684                    "}",
2685                    Style));
2686   Style.AllowShortCaseLabelsOnASingleLine = true;
2687   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2688   Style.BraceWrapping.AfterCaseLabel = true;
2689   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2690   EXPECT_EQ("switch (n)\n"
2691             "{\n"
2692             "  case 0:\n"
2693             "  {\n"
2694             "    return false;\n"
2695             "  }\n"
2696             "  default:\n"
2697             "  {\n"
2698             "    return true;\n"
2699             "  }\n"
2700             "}",
2701             format("switch (n) {\n"
2702                    "  case 0: {\n"
2703                    "    return false;\n"
2704                    "  }\n"
2705                    "  default:\n"
2706                    "  {\n"
2707                    "    return true;\n"
2708                    "  }\n"
2709                    "}",
2710                    Style));
2711 }
2712 
2713 TEST_F(FormatTest, FormatsLabels) {
2714   verifyFormat("void f() {\n"
2715                "  some_code();\n"
2716                "test_label:\n"
2717                "  some_other_code();\n"
2718                "  {\n"
2719                "    some_more_code();\n"
2720                "  another_label:\n"
2721                "    some_more_code();\n"
2722                "  }\n"
2723                "}");
2724   verifyFormat("{\n"
2725                "  some_code();\n"
2726                "test_label:\n"
2727                "  some_other_code();\n"
2728                "}");
2729   verifyFormat("{\n"
2730                "  some_code();\n"
2731                "test_label:;\n"
2732                "  int i = 0;\n"
2733                "}");
2734   FormatStyle Style = getLLVMStyle();
2735   Style.IndentGotoLabels = false;
2736   verifyFormat("void f() {\n"
2737                "  some_code();\n"
2738                "test_label:\n"
2739                "  some_other_code();\n"
2740                "  {\n"
2741                "    some_more_code();\n"
2742                "another_label:\n"
2743                "    some_more_code();\n"
2744                "  }\n"
2745                "}",
2746                Style);
2747   verifyFormat("{\n"
2748                "  some_code();\n"
2749                "test_label:\n"
2750                "  some_other_code();\n"
2751                "}",
2752                Style);
2753   verifyFormat("{\n"
2754                "  some_code();\n"
2755                "test_label:;\n"
2756                "  int i = 0;\n"
2757                "}");
2758 }
2759 
2760 TEST_F(FormatTest, MultiLineControlStatements) {
2761   FormatStyle Style = getLLVMStyle();
2762   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2763   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2764   Style.ColumnLimit = 20;
2765   // Short lines should keep opening brace on same line.
2766   EXPECT_EQ("if (foo) {\n"
2767             "  bar();\n"
2768             "}",
2769             format("if(foo){bar();}", Style));
2770   EXPECT_EQ("if (foo) {\n"
2771             "  bar();\n"
2772             "} else {\n"
2773             "  baz();\n"
2774             "}",
2775             format("if(foo){bar();}else{baz();}", Style));
2776   EXPECT_EQ("if (foo && bar) {\n"
2777             "  baz();\n"
2778             "}",
2779             format("if(foo&&bar){baz();}", Style));
2780   EXPECT_EQ("if (foo) {\n"
2781             "  bar();\n"
2782             "} else if (baz) {\n"
2783             "  quux();\n"
2784             "}",
2785             format("if(foo){bar();}else if(baz){quux();}", Style));
2786   EXPECT_EQ(
2787       "if (foo) {\n"
2788       "  bar();\n"
2789       "} else if (baz) {\n"
2790       "  quux();\n"
2791       "} else {\n"
2792       "  foobar();\n"
2793       "}",
2794       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
2795   EXPECT_EQ("for (;;) {\n"
2796             "  foo();\n"
2797             "}",
2798             format("for(;;){foo();}"));
2799   EXPECT_EQ("while (1) {\n"
2800             "  foo();\n"
2801             "}",
2802             format("while(1){foo();}", Style));
2803   EXPECT_EQ("switch (foo) {\n"
2804             "case bar:\n"
2805             "  return;\n"
2806             "}",
2807             format("switch(foo){case bar:return;}", Style));
2808   EXPECT_EQ("try {\n"
2809             "  foo();\n"
2810             "} catch (...) {\n"
2811             "  bar();\n"
2812             "}",
2813             format("try{foo();}catch(...){bar();}", Style));
2814   EXPECT_EQ("do {\n"
2815             "  foo();\n"
2816             "} while (bar &&\n"
2817             "         baz);",
2818             format("do{foo();}while(bar&&baz);", Style));
2819   // Long lines should put opening brace on new line.
2820   EXPECT_EQ("if (foo && bar &&\n"
2821             "    baz)\n"
2822             "{\n"
2823             "  quux();\n"
2824             "}",
2825             format("if(foo&&bar&&baz){quux();}", Style));
2826   EXPECT_EQ("if (foo && bar &&\n"
2827             "    baz)\n"
2828             "{\n"
2829             "  quux();\n"
2830             "}",
2831             format("if (foo && bar &&\n"
2832                    "    baz) {\n"
2833                    "  quux();\n"
2834                    "}",
2835                    Style));
2836   EXPECT_EQ("if (foo) {\n"
2837             "  bar();\n"
2838             "} else if (baz ||\n"
2839             "           quux)\n"
2840             "{\n"
2841             "  foobar();\n"
2842             "}",
2843             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
2844   EXPECT_EQ(
2845       "if (foo) {\n"
2846       "  bar();\n"
2847       "} else if (baz ||\n"
2848       "           quux)\n"
2849       "{\n"
2850       "  foobar();\n"
2851       "} else {\n"
2852       "  barbaz();\n"
2853       "}",
2854       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2855              Style));
2856   EXPECT_EQ("for (int i = 0;\n"
2857             "     i < 10; ++i)\n"
2858             "{\n"
2859             "  foo();\n"
2860             "}",
2861             format("for(int i=0;i<10;++i){foo();}", Style));
2862   EXPECT_EQ("foreach (int i,\n"
2863             "         list)\n"
2864             "{\n"
2865             "  foo();\n"
2866             "}",
2867             format("foreach(int i, list){foo();}", Style));
2868   Style.ColumnLimit =
2869       40; // to concentrate at brace wrapping, not line wrap due to column limit
2870   EXPECT_EQ("foreach (int i, list) {\n"
2871             "  foo();\n"
2872             "}",
2873             format("foreach(int i, list){foo();}", Style));
2874   Style.ColumnLimit =
2875       20; // to concentrate at brace wrapping, not line wrap due to column limit
2876   EXPECT_EQ("while (foo || bar ||\n"
2877             "       baz)\n"
2878             "{\n"
2879             "  quux();\n"
2880             "}",
2881             format("while(foo||bar||baz){quux();}", Style));
2882   EXPECT_EQ("switch (\n"
2883             "    foo = barbaz)\n"
2884             "{\n"
2885             "case quux:\n"
2886             "  return;\n"
2887             "}",
2888             format("switch(foo=barbaz){case quux:return;}", Style));
2889   EXPECT_EQ("try {\n"
2890             "  foo();\n"
2891             "} catch (\n"
2892             "    Exception &bar)\n"
2893             "{\n"
2894             "  baz();\n"
2895             "}",
2896             format("try{foo();}catch(Exception&bar){baz();}", Style));
2897   Style.ColumnLimit =
2898       40; // to concentrate at brace wrapping, not line wrap due to column limit
2899   EXPECT_EQ("try {\n"
2900             "  foo();\n"
2901             "} catch (Exception &bar) {\n"
2902             "  baz();\n"
2903             "}",
2904             format("try{foo();}catch(Exception&bar){baz();}", Style));
2905   Style.ColumnLimit =
2906       20; // to concentrate at brace wrapping, not line wrap due to column limit
2907 
2908   Style.BraceWrapping.BeforeElse = true;
2909   EXPECT_EQ(
2910       "if (foo) {\n"
2911       "  bar();\n"
2912       "}\n"
2913       "else if (baz ||\n"
2914       "         quux)\n"
2915       "{\n"
2916       "  foobar();\n"
2917       "}\n"
2918       "else {\n"
2919       "  barbaz();\n"
2920       "}",
2921       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2922              Style));
2923 
2924   Style.BraceWrapping.BeforeCatch = true;
2925   EXPECT_EQ("try {\n"
2926             "  foo();\n"
2927             "}\n"
2928             "catch (...) {\n"
2929             "  baz();\n"
2930             "}",
2931             format("try{foo();}catch(...){baz();}", Style));
2932 
2933   Style.BraceWrapping.AfterFunction = true;
2934   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2935   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
2936   Style.ColumnLimit = 80;
2937   verifyFormat("void shortfunction() { bar(); }", Style);
2938 
2939   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
2940   verifyFormat("void shortfunction()\n"
2941                "{\n"
2942                "  bar();\n"
2943                "}",
2944                Style);
2945 }
2946 
2947 TEST_F(FormatTest, BeforeWhile) {
2948   FormatStyle Style = getLLVMStyle();
2949   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2950 
2951   verifyFormat("do {\n"
2952                "  foo();\n"
2953                "} while (1);",
2954                Style);
2955   Style.BraceWrapping.BeforeWhile = true;
2956   verifyFormat("do {\n"
2957                "  foo();\n"
2958                "}\n"
2959                "while (1);",
2960                Style);
2961 }
2962 
2963 //===----------------------------------------------------------------------===//
2964 // Tests for classes, namespaces, etc.
2965 //===----------------------------------------------------------------------===//
2966 
2967 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
2968   verifyFormat("class A {};");
2969 }
2970 
2971 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
2972   verifyFormat("class A {\n"
2973                "public:\n"
2974                "public: // comment\n"
2975                "protected:\n"
2976                "private:\n"
2977                "  void f() {}\n"
2978                "};");
2979   verifyFormat("export class A {\n"
2980                "public:\n"
2981                "public: // comment\n"
2982                "protected:\n"
2983                "private:\n"
2984                "  void f() {}\n"
2985                "};");
2986   verifyGoogleFormat("class A {\n"
2987                      " public:\n"
2988                      " protected:\n"
2989                      " private:\n"
2990                      "  void f() {}\n"
2991                      "};");
2992   verifyGoogleFormat("export class A {\n"
2993                      " public:\n"
2994                      " protected:\n"
2995                      " private:\n"
2996                      "  void f() {}\n"
2997                      "};");
2998   verifyFormat("class A {\n"
2999                "public slots:\n"
3000                "  void f1() {}\n"
3001                "public Q_SLOTS:\n"
3002                "  void f2() {}\n"
3003                "protected slots:\n"
3004                "  void f3() {}\n"
3005                "protected Q_SLOTS:\n"
3006                "  void f4() {}\n"
3007                "private slots:\n"
3008                "  void f5() {}\n"
3009                "private Q_SLOTS:\n"
3010                "  void f6() {}\n"
3011                "signals:\n"
3012                "  void g1();\n"
3013                "Q_SIGNALS:\n"
3014                "  void g2();\n"
3015                "};");
3016 
3017   // Don't interpret 'signals' the wrong way.
3018   verifyFormat("signals.set();");
3019   verifyFormat("for (Signals signals : f()) {\n}");
3020   verifyFormat("{\n"
3021                "  signals.set(); // This needs indentation.\n"
3022                "}");
3023   verifyFormat("void f() {\n"
3024                "label:\n"
3025                "  signals.baz();\n"
3026                "}");
3027 }
3028 
3029 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3030   EXPECT_EQ("class A {\n"
3031             "public:\n"
3032             "  void f();\n"
3033             "\n"
3034             "private:\n"
3035             "  void g() {}\n"
3036             "  // test\n"
3037             "protected:\n"
3038             "  int h;\n"
3039             "};",
3040             format("class A {\n"
3041                    "public:\n"
3042                    "void f();\n"
3043                    "private:\n"
3044                    "void g() {}\n"
3045                    "// test\n"
3046                    "protected:\n"
3047                    "int h;\n"
3048                    "};"));
3049   EXPECT_EQ("class A {\n"
3050             "protected:\n"
3051             "public:\n"
3052             "  void f();\n"
3053             "};",
3054             format("class A {\n"
3055                    "protected:\n"
3056                    "\n"
3057                    "public:\n"
3058                    "\n"
3059                    "  void f();\n"
3060                    "};"));
3061 
3062   // Even ensure proper spacing inside macros.
3063   EXPECT_EQ("#define B     \\\n"
3064             "  class A {   \\\n"
3065             "   protected: \\\n"
3066             "   public:    \\\n"
3067             "    void f(); \\\n"
3068             "  };",
3069             format("#define B     \\\n"
3070                    "  class A {   \\\n"
3071                    "   protected: \\\n"
3072                    "              \\\n"
3073                    "   public:    \\\n"
3074                    "              \\\n"
3075                    "    void f(); \\\n"
3076                    "  };",
3077                    getGoogleStyle()));
3078   // But don't remove empty lines after macros ending in access specifiers.
3079   EXPECT_EQ("#define A private:\n"
3080             "\n"
3081             "int i;",
3082             format("#define A         private:\n"
3083                    "\n"
3084                    "int              i;"));
3085 }
3086 
3087 TEST_F(FormatTest, FormatsClasses) {
3088   verifyFormat("class A : public B {};");
3089   verifyFormat("class A : public ::B {};");
3090 
3091   verifyFormat(
3092       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3093       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3094   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3095                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3096                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3097   verifyFormat(
3098       "class A : public B, public C, public D, public E, public F {};");
3099   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3100                "                     public C,\n"
3101                "                     public D,\n"
3102                "                     public E,\n"
3103                "                     public F,\n"
3104                "                     public G {};");
3105 
3106   verifyFormat("class\n"
3107                "    ReallyReallyLongClassName {\n"
3108                "  int i;\n"
3109                "};",
3110                getLLVMStyleWithColumns(32));
3111   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3112                "                           aaaaaaaaaaaaaaaa> {};");
3113   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3114                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3115                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3116   verifyFormat("template <class R, class C>\n"
3117                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3118                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3119   verifyFormat("class ::A::B {};");
3120 }
3121 
3122 TEST_F(FormatTest, BreakInheritanceStyle) {
3123   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3124   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3125       FormatStyle::BILS_BeforeComma;
3126   verifyFormat("class MyClass : public X {};",
3127                StyleWithInheritanceBreakBeforeComma);
3128   verifyFormat("class MyClass\n"
3129                "    : public X\n"
3130                "    , public Y {};",
3131                StyleWithInheritanceBreakBeforeComma);
3132   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3133                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3134                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3135                StyleWithInheritanceBreakBeforeComma);
3136   verifyFormat("struct aaaaaaaaaaaaa\n"
3137                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3138                "          aaaaaaaaaaaaaaaa> {};",
3139                StyleWithInheritanceBreakBeforeComma);
3140 
3141   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3142   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3143       FormatStyle::BILS_AfterColon;
3144   verifyFormat("class MyClass : public X {};",
3145                StyleWithInheritanceBreakAfterColon);
3146   verifyFormat("class MyClass : public X, public Y {};",
3147                StyleWithInheritanceBreakAfterColon);
3148   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3149                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3150                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3151                StyleWithInheritanceBreakAfterColon);
3152   verifyFormat("struct aaaaaaaaaaaaa :\n"
3153                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3154                "        aaaaaaaaaaaaaaaa> {};",
3155                StyleWithInheritanceBreakAfterColon);
3156 
3157   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3158   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3159       FormatStyle::BILS_AfterComma;
3160   verifyFormat("class MyClass : public X {};",
3161                StyleWithInheritanceBreakAfterComma);
3162   verifyFormat("class MyClass : public X,\n"
3163                "                public Y {};",
3164                StyleWithInheritanceBreakAfterComma);
3165   verifyFormat(
3166       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3167       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3168       "{};",
3169       StyleWithInheritanceBreakAfterComma);
3170   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3171                "                           aaaaaaaaaaaaaaaa> {};",
3172                StyleWithInheritanceBreakAfterComma);
3173   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3174                "    : public OnceBreak,\n"
3175                "      public AlwaysBreak,\n"
3176                "      EvenBasesFitInOneLine {};",
3177                StyleWithInheritanceBreakAfterComma);
3178 }
3179 
3180 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
3181   verifyFormat("class A {\n} a, b;");
3182   verifyFormat("struct A {\n} a, b;");
3183   verifyFormat("union A {\n} a;");
3184 }
3185 
3186 TEST_F(FormatTest, FormatsEnum) {
3187   verifyFormat("enum {\n"
3188                "  Zero,\n"
3189                "  One = 1,\n"
3190                "  Two = One + 1,\n"
3191                "  Three = (One + Two),\n"
3192                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3193                "  Five = (One, Two, Three, Four, 5)\n"
3194                "};");
3195   verifyGoogleFormat("enum {\n"
3196                      "  Zero,\n"
3197                      "  One = 1,\n"
3198                      "  Two = One + 1,\n"
3199                      "  Three = (One + Two),\n"
3200                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3201                      "  Five = (One, Two, Three, Four, 5)\n"
3202                      "};");
3203   verifyFormat("enum Enum {};");
3204   verifyFormat("enum {};");
3205   verifyFormat("enum X E {} d;");
3206   verifyFormat("enum __attribute__((...)) E {} d;");
3207   verifyFormat("enum __declspec__((...)) E {} d;");
3208   verifyFormat("enum {\n"
3209                "  Bar = Foo<int, int>::value\n"
3210                "};",
3211                getLLVMStyleWithColumns(30));
3212 
3213   verifyFormat("enum ShortEnum { A, B, C };");
3214   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3215 
3216   EXPECT_EQ("enum KeepEmptyLines {\n"
3217             "  ONE,\n"
3218             "\n"
3219             "  TWO,\n"
3220             "\n"
3221             "  THREE\n"
3222             "}",
3223             format("enum KeepEmptyLines {\n"
3224                    "  ONE,\n"
3225                    "\n"
3226                    "  TWO,\n"
3227                    "\n"
3228                    "\n"
3229                    "  THREE\n"
3230                    "}"));
3231   verifyFormat("enum E { // comment\n"
3232                "  ONE,\n"
3233                "  TWO\n"
3234                "};\n"
3235                "int i;");
3236 
3237   FormatStyle EightIndent = getLLVMStyle();
3238   EightIndent.IndentWidth = 8;
3239   verifyFormat("enum {\n"
3240                "        VOID,\n"
3241                "        CHAR,\n"
3242                "        SHORT,\n"
3243                "        INT,\n"
3244                "        LONG,\n"
3245                "        SIGNED,\n"
3246                "        UNSIGNED,\n"
3247                "        BOOL,\n"
3248                "        FLOAT,\n"
3249                "        DOUBLE,\n"
3250                "        COMPLEX\n"
3251                "};",
3252                EightIndent);
3253 
3254   // Not enums.
3255   verifyFormat("enum X f() {\n"
3256                "  a();\n"
3257                "  return 42;\n"
3258                "}");
3259   verifyFormat("enum X Type::f() {\n"
3260                "  a();\n"
3261                "  return 42;\n"
3262                "}");
3263   verifyFormat("enum ::X f() {\n"
3264                "  a();\n"
3265                "  return 42;\n"
3266                "}");
3267   verifyFormat("enum ns::X f() {\n"
3268                "  a();\n"
3269                "  return 42;\n"
3270                "}");
3271 }
3272 
3273 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3274   verifyFormat("enum Type {\n"
3275                "  One = 0; // These semicolons should be commas.\n"
3276                "  Two = 1;\n"
3277                "};");
3278   verifyFormat("namespace n {\n"
3279                "enum Type {\n"
3280                "  One,\n"
3281                "  Two, // missing };\n"
3282                "  int i;\n"
3283                "}\n"
3284                "void g() {}");
3285 }
3286 
3287 TEST_F(FormatTest, FormatsEnumStruct) {
3288   verifyFormat("enum struct {\n"
3289                "  Zero,\n"
3290                "  One = 1,\n"
3291                "  Two = One + 1,\n"
3292                "  Three = (One + Two),\n"
3293                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3294                "  Five = (One, Two, Three, Four, 5)\n"
3295                "};");
3296   verifyFormat("enum struct Enum {};");
3297   verifyFormat("enum struct {};");
3298   verifyFormat("enum struct X E {} d;");
3299   verifyFormat("enum struct __attribute__((...)) E {} d;");
3300   verifyFormat("enum struct __declspec__((...)) E {} d;");
3301   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3302 }
3303 
3304 TEST_F(FormatTest, FormatsEnumClass) {
3305   verifyFormat("enum class {\n"
3306                "  Zero,\n"
3307                "  One = 1,\n"
3308                "  Two = One + 1,\n"
3309                "  Three = (One + Two),\n"
3310                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3311                "  Five = (One, Two, Three, Four, 5)\n"
3312                "};");
3313   verifyFormat("enum class Enum {};");
3314   verifyFormat("enum class {};");
3315   verifyFormat("enum class X E {} d;");
3316   verifyFormat("enum class __attribute__((...)) E {} d;");
3317   verifyFormat("enum class __declspec__((...)) E {} d;");
3318   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3319 }
3320 
3321 TEST_F(FormatTest, FormatsEnumTypes) {
3322   verifyFormat("enum X : int {\n"
3323                "  A, // Force multiple lines.\n"
3324                "  B\n"
3325                "};");
3326   verifyFormat("enum X : int { A, B };");
3327   verifyFormat("enum X : std::uint32_t { A, B };");
3328 }
3329 
3330 TEST_F(FormatTest, FormatsTypedefEnum) {
3331   FormatStyle Style = getLLVMStyle();
3332   Style.ColumnLimit = 40;
3333   verifyFormat("typedef enum {} EmptyEnum;");
3334   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3335   verifyFormat("typedef enum {\n"
3336                "  ZERO = 0,\n"
3337                "  ONE = 1,\n"
3338                "  TWO = 2,\n"
3339                "  THREE = 3\n"
3340                "} LongEnum;",
3341                Style);
3342   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3343   Style.BraceWrapping.AfterEnum = true;
3344   verifyFormat("typedef enum {} EmptyEnum;");
3345   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3346   verifyFormat("typedef enum\n"
3347                "{\n"
3348                "  ZERO = 0,\n"
3349                "  ONE = 1,\n"
3350                "  TWO = 2,\n"
3351                "  THREE = 3\n"
3352                "} LongEnum;",
3353                Style);
3354 }
3355 
3356 TEST_F(FormatTest, FormatsNSEnums) {
3357   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3358   verifyGoogleFormat(
3359       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3360   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3361                      "  // Information about someDecentlyLongValue.\n"
3362                      "  someDecentlyLongValue,\n"
3363                      "  // Information about anotherDecentlyLongValue.\n"
3364                      "  anotherDecentlyLongValue,\n"
3365                      "  // Information about aThirdDecentlyLongValue.\n"
3366                      "  aThirdDecentlyLongValue\n"
3367                      "};");
3368   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3369                      "  // Information about someDecentlyLongValue.\n"
3370                      "  someDecentlyLongValue,\n"
3371                      "  // Information about anotherDecentlyLongValue.\n"
3372                      "  anotherDecentlyLongValue,\n"
3373                      "  // Information about aThirdDecentlyLongValue.\n"
3374                      "  aThirdDecentlyLongValue\n"
3375                      "};");
3376   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3377                      "  a = 1,\n"
3378                      "  b = 2,\n"
3379                      "  c = 3,\n"
3380                      "};");
3381   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3382                      "  a = 1,\n"
3383                      "  b = 2,\n"
3384                      "  c = 3,\n"
3385                      "};");
3386   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3387                      "  a = 1,\n"
3388                      "  b = 2,\n"
3389                      "  c = 3,\n"
3390                      "};");
3391   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3392                      "  a = 1,\n"
3393                      "  b = 2,\n"
3394                      "  c = 3,\n"
3395                      "};");
3396 }
3397 
3398 TEST_F(FormatTest, FormatsBitfields) {
3399   verifyFormat("struct Bitfields {\n"
3400                "  unsigned sClass : 8;\n"
3401                "  unsigned ValueKind : 2;\n"
3402                "};");
3403   verifyFormat("struct A {\n"
3404                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3405                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3406                "};");
3407   verifyFormat("struct MyStruct {\n"
3408                "  uchar data;\n"
3409                "  uchar : 8;\n"
3410                "  uchar : 8;\n"
3411                "  uchar other;\n"
3412                "};");
3413   FormatStyle Style = getLLVMStyle();
3414   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3415   verifyFormat("struct Bitfields {\n"
3416                "  unsigned sClass:8;\n"
3417                "  unsigned ValueKind:2;\n"
3418                "  uchar other;\n"
3419                "};",
3420                Style);
3421   verifyFormat("struct A {\n"
3422                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3423                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3424                "};",
3425                Style);
3426   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3427   verifyFormat("struct Bitfields {\n"
3428                "  unsigned sClass :8;\n"
3429                "  unsigned ValueKind :2;\n"
3430                "  uchar other;\n"
3431                "};",
3432                Style);
3433   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3434   verifyFormat("struct Bitfields {\n"
3435                "  unsigned sClass: 8;\n"
3436                "  unsigned ValueKind: 2;\n"
3437                "  uchar other;\n"
3438                "};",
3439                Style);
3440 }
3441 
3442 TEST_F(FormatTest, FormatsNamespaces) {
3443   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3444   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3445 
3446   verifyFormat("namespace some_namespace {\n"
3447                "class A {};\n"
3448                "void f() { f(); }\n"
3449                "}",
3450                LLVMWithNoNamespaceFix);
3451   verifyFormat("namespace N::inline D {\n"
3452                "class A {};\n"
3453                "void f() { f(); }\n"
3454                "}",
3455                LLVMWithNoNamespaceFix);
3456   verifyFormat("namespace N::inline D::E {\n"
3457                "class A {};\n"
3458                "void f() { f(); }\n"
3459                "}",
3460                LLVMWithNoNamespaceFix);
3461   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3462                "class A {};\n"
3463                "void f() { f(); }\n"
3464                "}",
3465                LLVMWithNoNamespaceFix);
3466   verifyFormat("/* something */ namespace some_namespace {\n"
3467                "class A {};\n"
3468                "void f() { f(); }\n"
3469                "}",
3470                LLVMWithNoNamespaceFix);
3471   verifyFormat("namespace {\n"
3472                "class A {};\n"
3473                "void f() { f(); }\n"
3474                "}",
3475                LLVMWithNoNamespaceFix);
3476   verifyFormat("/* something */ namespace {\n"
3477                "class A {};\n"
3478                "void f() { f(); }\n"
3479                "}",
3480                LLVMWithNoNamespaceFix);
3481   verifyFormat("inline namespace X {\n"
3482                "class A {};\n"
3483                "void f() { f(); }\n"
3484                "}",
3485                LLVMWithNoNamespaceFix);
3486   verifyFormat("/* something */ inline namespace X {\n"
3487                "class A {};\n"
3488                "void f() { f(); }\n"
3489                "}",
3490                LLVMWithNoNamespaceFix);
3491   verifyFormat("export namespace X {\n"
3492                "class A {};\n"
3493                "void f() { f(); }\n"
3494                "}",
3495                LLVMWithNoNamespaceFix);
3496   verifyFormat("using namespace some_namespace;\n"
3497                "class A {};\n"
3498                "void f() { f(); }",
3499                LLVMWithNoNamespaceFix);
3500 
3501   // This code is more common than we thought; if we
3502   // layout this correctly the semicolon will go into
3503   // its own line, which is undesirable.
3504   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3505   verifyFormat("namespace {\n"
3506                "class A {};\n"
3507                "};",
3508                LLVMWithNoNamespaceFix);
3509 
3510   verifyFormat("namespace {\n"
3511                "int SomeVariable = 0; // comment\n"
3512                "} // namespace",
3513                LLVMWithNoNamespaceFix);
3514   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3515             "#define HEADER_GUARD\n"
3516             "namespace my_namespace {\n"
3517             "int i;\n"
3518             "} // my_namespace\n"
3519             "#endif // HEADER_GUARD",
3520             format("#ifndef HEADER_GUARD\n"
3521                    " #define HEADER_GUARD\n"
3522                    "   namespace my_namespace {\n"
3523                    "int i;\n"
3524                    "}    // my_namespace\n"
3525                    "#endif    // HEADER_GUARD",
3526                    LLVMWithNoNamespaceFix));
3527 
3528   EXPECT_EQ("namespace A::B {\n"
3529             "class C {};\n"
3530             "}",
3531             format("namespace A::B {\n"
3532                    "class C {};\n"
3533                    "}",
3534                    LLVMWithNoNamespaceFix));
3535 
3536   FormatStyle Style = getLLVMStyle();
3537   Style.NamespaceIndentation = FormatStyle::NI_All;
3538   EXPECT_EQ("namespace out {\n"
3539             "  int i;\n"
3540             "  namespace in {\n"
3541             "    int i;\n"
3542             "  } // namespace in\n"
3543             "} // namespace out",
3544             format("namespace out {\n"
3545                    "int i;\n"
3546                    "namespace in {\n"
3547                    "int i;\n"
3548                    "} // namespace in\n"
3549                    "} // namespace out",
3550                    Style));
3551 
3552   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3553   EXPECT_EQ("namespace out {\n"
3554             "int i;\n"
3555             "namespace in {\n"
3556             "  int i;\n"
3557             "} // namespace in\n"
3558             "} // namespace out",
3559             format("namespace out {\n"
3560                    "int i;\n"
3561                    "namespace in {\n"
3562                    "int i;\n"
3563                    "} // namespace in\n"
3564                    "} // namespace out",
3565                    Style));
3566 
3567   Style.NamespaceIndentation = FormatStyle::NI_None;
3568   verifyFormat("template <class T>\n"
3569                "concept a_concept = X<>;\n"
3570                "namespace B {\n"
3571                "struct b_struct {};\n"
3572                "} // namespace B\n",
3573                Style);
3574   verifyFormat("template <int I> constexpr void foo requires(I == 42) {}\n"
3575                "namespace ns {\n"
3576                "void foo() {}\n"
3577                "} // namespace ns\n",
3578                Style);
3579 }
3580 
3581 TEST_F(FormatTest, NamespaceMacros) {
3582   FormatStyle Style = getLLVMStyle();
3583   Style.NamespaceMacros.push_back("TESTSUITE");
3584 
3585   verifyFormat("TESTSUITE(A) {\n"
3586                "int foo();\n"
3587                "} // TESTSUITE(A)",
3588                Style);
3589 
3590   verifyFormat("TESTSUITE(A, B) {\n"
3591                "int foo();\n"
3592                "} // TESTSUITE(A)",
3593                Style);
3594 
3595   // Properly indent according to NamespaceIndentation style
3596   Style.NamespaceIndentation = FormatStyle::NI_All;
3597   verifyFormat("TESTSUITE(A) {\n"
3598                "  int foo();\n"
3599                "} // TESTSUITE(A)",
3600                Style);
3601   verifyFormat("TESTSUITE(A) {\n"
3602                "  namespace B {\n"
3603                "    int foo();\n"
3604                "  } // namespace B\n"
3605                "} // TESTSUITE(A)",
3606                Style);
3607   verifyFormat("namespace A {\n"
3608                "  TESTSUITE(B) {\n"
3609                "    int foo();\n"
3610                "  } // TESTSUITE(B)\n"
3611                "} // namespace A",
3612                Style);
3613 
3614   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3615   verifyFormat("TESTSUITE(A) {\n"
3616                "TESTSUITE(B) {\n"
3617                "  int foo();\n"
3618                "} // TESTSUITE(B)\n"
3619                "} // TESTSUITE(A)",
3620                Style);
3621   verifyFormat("TESTSUITE(A) {\n"
3622                "namespace B {\n"
3623                "  int foo();\n"
3624                "} // namespace B\n"
3625                "} // TESTSUITE(A)",
3626                Style);
3627   verifyFormat("namespace A {\n"
3628                "TESTSUITE(B) {\n"
3629                "  int foo();\n"
3630                "} // TESTSUITE(B)\n"
3631                "} // namespace A",
3632                Style);
3633 
3634   // Properly merge namespace-macros blocks in CompactNamespaces mode
3635   Style.NamespaceIndentation = FormatStyle::NI_None;
3636   Style.CompactNamespaces = true;
3637   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
3638                "}} // TESTSUITE(A::B)",
3639                Style);
3640 
3641   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3642             "}} // TESTSUITE(out::in)",
3643             format("TESTSUITE(out) {\n"
3644                    "TESTSUITE(in) {\n"
3645                    "} // TESTSUITE(in)\n"
3646                    "} // TESTSUITE(out)",
3647                    Style));
3648 
3649   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3650             "}} // TESTSUITE(out::in)",
3651             format("TESTSUITE(out) {\n"
3652                    "TESTSUITE(in) {\n"
3653                    "} // TESTSUITE(in)\n"
3654                    "} // TESTSUITE(out)",
3655                    Style));
3656 
3657   // Do not merge different namespaces/macros
3658   EXPECT_EQ("namespace out {\n"
3659             "TESTSUITE(in) {\n"
3660             "} // TESTSUITE(in)\n"
3661             "} // namespace out",
3662             format("namespace out {\n"
3663                    "TESTSUITE(in) {\n"
3664                    "} // TESTSUITE(in)\n"
3665                    "} // namespace out",
3666                    Style));
3667   EXPECT_EQ("TESTSUITE(out) {\n"
3668             "namespace in {\n"
3669             "} // namespace in\n"
3670             "} // TESTSUITE(out)",
3671             format("TESTSUITE(out) {\n"
3672                    "namespace in {\n"
3673                    "} // namespace in\n"
3674                    "} // TESTSUITE(out)",
3675                    Style));
3676   Style.NamespaceMacros.push_back("FOOBAR");
3677   EXPECT_EQ("TESTSUITE(out) {\n"
3678             "FOOBAR(in) {\n"
3679             "} // FOOBAR(in)\n"
3680             "} // TESTSUITE(out)",
3681             format("TESTSUITE(out) {\n"
3682                    "FOOBAR(in) {\n"
3683                    "} // FOOBAR(in)\n"
3684                    "} // TESTSUITE(out)",
3685                    Style));
3686 }
3687 
3688 TEST_F(FormatTest, FormatsCompactNamespaces) {
3689   FormatStyle Style = getLLVMStyle();
3690   Style.CompactNamespaces = true;
3691   Style.NamespaceMacros.push_back("TESTSUITE");
3692 
3693   verifyFormat("namespace A { namespace B {\n"
3694                "}} // namespace A::B",
3695                Style);
3696 
3697   EXPECT_EQ("namespace out { namespace in {\n"
3698             "}} // namespace out::in",
3699             format("namespace out {\n"
3700                    "namespace in {\n"
3701                    "} // namespace in\n"
3702                    "} // namespace out",
3703                    Style));
3704 
3705   // Only namespaces which have both consecutive opening and end get compacted
3706   EXPECT_EQ("namespace out {\n"
3707             "namespace in1 {\n"
3708             "} // namespace in1\n"
3709             "namespace in2 {\n"
3710             "} // namespace in2\n"
3711             "} // namespace out",
3712             format("namespace out {\n"
3713                    "namespace in1 {\n"
3714                    "} // namespace in1\n"
3715                    "namespace in2 {\n"
3716                    "} // namespace in2\n"
3717                    "} // namespace out",
3718                    Style));
3719 
3720   EXPECT_EQ("namespace out {\n"
3721             "int i;\n"
3722             "namespace in {\n"
3723             "int j;\n"
3724             "} // namespace in\n"
3725             "int k;\n"
3726             "} // namespace out",
3727             format("namespace out { int i;\n"
3728                    "namespace in { int j; } // namespace in\n"
3729                    "int k; } // namespace out",
3730                    Style));
3731 
3732   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
3733             "}}} // namespace A::B::C\n",
3734             format("namespace A { namespace B {\n"
3735                    "namespace C {\n"
3736                    "}} // namespace B::C\n"
3737                    "} // namespace A\n",
3738                    Style));
3739 
3740   Style.ColumnLimit = 40;
3741   EXPECT_EQ("namespace aaaaaaaaaa {\n"
3742             "namespace bbbbbbbbbb {\n"
3743             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
3744             format("namespace aaaaaaaaaa {\n"
3745                    "namespace bbbbbbbbbb {\n"
3746                    "} // namespace bbbbbbbbbb\n"
3747                    "} // namespace aaaaaaaaaa",
3748                    Style));
3749 
3750   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
3751             "namespace cccccc {\n"
3752             "}}} // namespace aaaaaa::bbbbbb::cccccc",
3753             format("namespace aaaaaa {\n"
3754                    "namespace bbbbbb {\n"
3755                    "namespace cccccc {\n"
3756                    "} // namespace cccccc\n"
3757                    "} // namespace bbbbbb\n"
3758                    "} // namespace aaaaaa",
3759                    Style));
3760   Style.ColumnLimit = 80;
3761 
3762   // Extra semicolon after 'inner' closing brace prevents merging
3763   EXPECT_EQ("namespace out { namespace in {\n"
3764             "}; } // namespace out::in",
3765             format("namespace out {\n"
3766                    "namespace in {\n"
3767                    "}; // namespace in\n"
3768                    "} // namespace out",
3769                    Style));
3770 
3771   // Extra semicolon after 'outer' closing brace is conserved
3772   EXPECT_EQ("namespace out { namespace in {\n"
3773             "}}; // namespace out::in",
3774             format("namespace out {\n"
3775                    "namespace in {\n"
3776                    "} // namespace in\n"
3777                    "}; // namespace out",
3778                    Style));
3779 
3780   Style.NamespaceIndentation = FormatStyle::NI_All;
3781   EXPECT_EQ("namespace out { namespace in {\n"
3782             "  int i;\n"
3783             "}} // namespace out::in",
3784             format("namespace out {\n"
3785                    "namespace in {\n"
3786                    "int i;\n"
3787                    "} // namespace in\n"
3788                    "} // namespace out",
3789                    Style));
3790   EXPECT_EQ("namespace out { namespace mid {\n"
3791             "  namespace in {\n"
3792             "    int j;\n"
3793             "  } // namespace in\n"
3794             "  int k;\n"
3795             "}} // namespace out::mid",
3796             format("namespace out { namespace mid {\n"
3797                    "namespace in { int j; } // namespace in\n"
3798                    "int k; }} // namespace out::mid",
3799                    Style));
3800 
3801   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3802   EXPECT_EQ("namespace out { namespace in {\n"
3803             "  int i;\n"
3804             "}} // namespace out::in",
3805             format("namespace out {\n"
3806                    "namespace in {\n"
3807                    "int i;\n"
3808                    "} // namespace in\n"
3809                    "} // namespace out",
3810                    Style));
3811   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
3812             "  int i;\n"
3813             "}}} // namespace out::mid::in",
3814             format("namespace out {\n"
3815                    "namespace mid {\n"
3816                    "namespace in {\n"
3817                    "int i;\n"
3818                    "} // namespace in\n"
3819                    "} // namespace mid\n"
3820                    "} // namespace out",
3821                    Style));
3822 }
3823 
3824 TEST_F(FormatTest, FormatsExternC) {
3825   verifyFormat("extern \"C\" {\nint a;");
3826   verifyFormat("extern \"C\" {}");
3827   verifyFormat("extern \"C\" {\n"
3828                "int foo();\n"
3829                "}");
3830   verifyFormat("extern \"C\" int foo() {}");
3831   verifyFormat("extern \"C\" int foo();");
3832   verifyFormat("extern \"C\" int foo() {\n"
3833                "  int i = 42;\n"
3834                "  return i;\n"
3835                "}");
3836 
3837   FormatStyle Style = getLLVMStyle();
3838   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3839   Style.BraceWrapping.AfterFunction = true;
3840   verifyFormat("extern \"C\" int foo() {}", Style);
3841   verifyFormat("extern \"C\" int foo();", Style);
3842   verifyFormat("extern \"C\" int foo()\n"
3843                "{\n"
3844                "  int i = 42;\n"
3845                "  return i;\n"
3846                "}",
3847                Style);
3848 
3849   Style.BraceWrapping.AfterExternBlock = true;
3850   Style.BraceWrapping.SplitEmptyRecord = false;
3851   verifyFormat("extern \"C\"\n"
3852                "{}",
3853                Style);
3854   verifyFormat("extern \"C\"\n"
3855                "{\n"
3856                "  int foo();\n"
3857                "}",
3858                Style);
3859 }
3860 
3861 TEST_F(FormatTest, IndentExternBlockStyle) {
3862   FormatStyle Style = getLLVMStyle();
3863   Style.IndentWidth = 2;
3864 
3865   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3866   verifyFormat("extern \"C\" { /*9*/\n"
3867                "}",
3868                Style);
3869   verifyFormat("extern \"C\" {\n"
3870                "  int foo10();\n"
3871                "}",
3872                Style);
3873 
3874   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
3875   verifyFormat("extern \"C\" { /*11*/\n"
3876                "}",
3877                Style);
3878   verifyFormat("extern \"C\" {\n"
3879                "int foo12();\n"
3880                "}",
3881                Style);
3882 
3883   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3884   Style.BraceWrapping.AfterExternBlock = true;
3885   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3886   verifyFormat("extern \"C\"\n"
3887                "{ /*13*/\n"
3888                "}",
3889                Style);
3890   verifyFormat("extern \"C\"\n{\n"
3891                "  int foo14();\n"
3892                "}",
3893                Style);
3894 
3895   Style.BraceWrapping.AfterExternBlock = false;
3896   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
3897   verifyFormat("extern \"C\" { /*15*/\n"
3898                "}",
3899                Style);
3900   verifyFormat("extern \"C\" {\n"
3901                "int foo16();\n"
3902                "}",
3903                Style);
3904 
3905   Style.BraceWrapping.AfterExternBlock = true;
3906   verifyFormat("extern \"C\"\n"
3907                "{ /*13*/\n"
3908                "}",
3909                Style);
3910   verifyFormat("extern \"C\"\n"
3911                "{\n"
3912                "int foo14();\n"
3913                "}",
3914                Style);
3915 
3916   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3917   verifyFormat("extern \"C\"\n"
3918                "{ /*13*/\n"
3919                "}",
3920                Style);
3921   verifyFormat("extern \"C\"\n"
3922                "{\n"
3923                "  int foo14();\n"
3924                "}",
3925                Style);
3926 }
3927 
3928 TEST_F(FormatTest, FormatsInlineASM) {
3929   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
3930   verifyFormat("asm(\"nop\" ::: \"memory\");");
3931   verifyFormat(
3932       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
3933       "    \"cpuid\\n\\t\"\n"
3934       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
3935       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
3936       "    : \"a\"(value));");
3937   EXPECT_EQ(
3938       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
3939       "  __asm {\n"
3940       "        mov     edx,[that] // vtable in edx\n"
3941       "        mov     eax,methodIndex\n"
3942       "        call    [edx][eax*4] // stdcall\n"
3943       "  }\n"
3944       "}",
3945       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
3946              "    __asm {\n"
3947              "        mov     edx,[that] // vtable in edx\n"
3948              "        mov     eax,methodIndex\n"
3949              "        call    [edx][eax*4] // stdcall\n"
3950              "    }\n"
3951              "}"));
3952   EXPECT_EQ("_asm {\n"
3953             "  xor eax, eax;\n"
3954             "  cpuid;\n"
3955             "}",
3956             format("_asm {\n"
3957                    "  xor eax, eax;\n"
3958                    "  cpuid;\n"
3959                    "}"));
3960   verifyFormat("void function() {\n"
3961                "  // comment\n"
3962                "  asm(\"\");\n"
3963                "}");
3964   EXPECT_EQ("__asm {\n"
3965             "}\n"
3966             "int i;",
3967             format("__asm   {\n"
3968                    "}\n"
3969                    "int   i;"));
3970 }
3971 
3972 TEST_F(FormatTest, FormatTryCatch) {
3973   verifyFormat("try {\n"
3974                "  throw a * b;\n"
3975                "} catch (int a) {\n"
3976                "  // Do nothing.\n"
3977                "} catch (...) {\n"
3978                "  exit(42);\n"
3979                "}");
3980 
3981   // Function-level try statements.
3982   verifyFormat("int f() try { return 4; } catch (...) {\n"
3983                "  return 5;\n"
3984                "}");
3985   verifyFormat("class A {\n"
3986                "  int a;\n"
3987                "  A() try : a(0) {\n"
3988                "  } catch (...) {\n"
3989                "    throw;\n"
3990                "  }\n"
3991                "};\n");
3992   verifyFormat("class A {\n"
3993                "  int a;\n"
3994                "  A() try : a(0), b{1} {\n"
3995                "  } catch (...) {\n"
3996                "    throw;\n"
3997                "  }\n"
3998                "};\n");
3999   verifyFormat("class A {\n"
4000                "  int a;\n"
4001                "  A() try : a(0), b{1}, c{2} {\n"
4002                "  } catch (...) {\n"
4003                "    throw;\n"
4004                "  }\n"
4005                "};\n");
4006   verifyFormat("class A {\n"
4007                "  int a;\n"
4008                "  A() try : a(0), b{1}, c{2} {\n"
4009                "    { // New scope.\n"
4010                "    }\n"
4011                "  } catch (...) {\n"
4012                "    throw;\n"
4013                "  }\n"
4014                "};\n");
4015 
4016   // Incomplete try-catch blocks.
4017   verifyIncompleteFormat("try {} catch (");
4018 }
4019 
4020 TEST_F(FormatTest, FormatTryAsAVariable) {
4021   verifyFormat("int try;");
4022   verifyFormat("int try, size;");
4023   verifyFormat("try = foo();");
4024   verifyFormat("if (try < size) {\n  return true;\n}");
4025 
4026   verifyFormat("int catch;");
4027   verifyFormat("int catch, size;");
4028   verifyFormat("catch = foo();");
4029   verifyFormat("if (catch < size) {\n  return true;\n}");
4030 
4031   FormatStyle Style = getLLVMStyle();
4032   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4033   Style.BraceWrapping.AfterFunction = true;
4034   Style.BraceWrapping.BeforeCatch = true;
4035   verifyFormat("try {\n"
4036                "  int bar = 1;\n"
4037                "}\n"
4038                "catch (...) {\n"
4039                "  int bar = 1;\n"
4040                "}",
4041                Style);
4042   verifyFormat("#if NO_EX\n"
4043                "try\n"
4044                "#endif\n"
4045                "{\n"
4046                "}\n"
4047                "#if NO_EX\n"
4048                "catch (...) {\n"
4049                "}",
4050                Style);
4051   verifyFormat("try /* abc */ {\n"
4052                "  int bar = 1;\n"
4053                "}\n"
4054                "catch (...) {\n"
4055                "  int bar = 1;\n"
4056                "}",
4057                Style);
4058   verifyFormat("try\n"
4059                "// abc\n"
4060                "{\n"
4061                "  int bar = 1;\n"
4062                "}\n"
4063                "catch (...) {\n"
4064                "  int bar = 1;\n"
4065                "}",
4066                Style);
4067 }
4068 
4069 TEST_F(FormatTest, FormatSEHTryCatch) {
4070   verifyFormat("__try {\n"
4071                "  int a = b * c;\n"
4072                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4073                "  // Do nothing.\n"
4074                "}");
4075 
4076   verifyFormat("__try {\n"
4077                "  int a = b * c;\n"
4078                "} __finally {\n"
4079                "  // Do nothing.\n"
4080                "}");
4081 
4082   verifyFormat("DEBUG({\n"
4083                "  __try {\n"
4084                "  } __finally {\n"
4085                "  }\n"
4086                "});\n");
4087 }
4088 
4089 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4090   verifyFormat("try {\n"
4091                "  f();\n"
4092                "} catch {\n"
4093                "  g();\n"
4094                "}");
4095   verifyFormat("try {\n"
4096                "  f();\n"
4097                "} catch (A a) MACRO(x) {\n"
4098                "  g();\n"
4099                "} catch (B b) MACRO(x) {\n"
4100                "  g();\n"
4101                "}");
4102 }
4103 
4104 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4105   FormatStyle Style = getLLVMStyle();
4106   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4107                           FormatStyle::BS_WebKit}) {
4108     Style.BreakBeforeBraces = BraceStyle;
4109     verifyFormat("try {\n"
4110                  "  // something\n"
4111                  "} catch (...) {\n"
4112                  "  // something\n"
4113                  "}",
4114                  Style);
4115   }
4116   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4117   verifyFormat("try {\n"
4118                "  // something\n"
4119                "}\n"
4120                "catch (...) {\n"
4121                "  // something\n"
4122                "}",
4123                Style);
4124   verifyFormat("__try {\n"
4125                "  // something\n"
4126                "}\n"
4127                "__finally {\n"
4128                "  // something\n"
4129                "}",
4130                Style);
4131   verifyFormat("@try {\n"
4132                "  // something\n"
4133                "}\n"
4134                "@finally {\n"
4135                "  // something\n"
4136                "}",
4137                Style);
4138   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4139   verifyFormat("try\n"
4140                "{\n"
4141                "  // something\n"
4142                "}\n"
4143                "catch (...)\n"
4144                "{\n"
4145                "  // something\n"
4146                "}",
4147                Style);
4148   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4149   verifyFormat("try\n"
4150                "  {\n"
4151                "  // something white\n"
4152                "  }\n"
4153                "catch (...)\n"
4154                "  {\n"
4155                "  // something white\n"
4156                "  }",
4157                Style);
4158   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4159   verifyFormat("try\n"
4160                "  {\n"
4161                "    // something\n"
4162                "  }\n"
4163                "catch (...)\n"
4164                "  {\n"
4165                "    // something\n"
4166                "  }",
4167                Style);
4168   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4169   Style.BraceWrapping.BeforeCatch = true;
4170   verifyFormat("try {\n"
4171                "  // something\n"
4172                "}\n"
4173                "catch (...) {\n"
4174                "  // something\n"
4175                "}",
4176                Style);
4177 }
4178 
4179 TEST_F(FormatTest, StaticInitializers) {
4180   verifyFormat("static SomeClass SC = {1, 'a'};");
4181 
4182   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4183                "    100000000, "
4184                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4185 
4186   // Here, everything other than the "}" would fit on a line.
4187   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4188                "    10000000000000000000000000};");
4189   EXPECT_EQ("S s = {a,\n"
4190             "\n"
4191             "       b};",
4192             format("S s = {\n"
4193                    "  a,\n"
4194                    "\n"
4195                    "  b\n"
4196                    "};"));
4197 
4198   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4199   // line. However, the formatting looks a bit off and this probably doesn't
4200   // happen often in practice.
4201   verifyFormat("static int Variable[1] = {\n"
4202                "    {1000000000000000000000000000000000000}};",
4203                getLLVMStyleWithColumns(40));
4204 }
4205 
4206 TEST_F(FormatTest, DesignatedInitializers) {
4207   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4208   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4209                "                    .bbbbbbbbbb = 2,\n"
4210                "                    .cccccccccc = 3,\n"
4211                "                    .dddddddddd = 4,\n"
4212                "                    .eeeeeeeeee = 5};");
4213   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4214                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4215                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4216                "    .ccccccccccccccccccccccccccc = 3,\n"
4217                "    .ddddddddddddddddddddddddddd = 4,\n"
4218                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4219 
4220   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4221 
4222   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4223   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4224                "                    [2] = bbbbbbbbbb,\n"
4225                "                    [3] = cccccccccc,\n"
4226                "                    [4] = dddddddddd,\n"
4227                "                    [5] = eeeeeeeeee};");
4228   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4229                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4230                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4231                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4232                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4233                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4234 }
4235 
4236 TEST_F(FormatTest, NestedStaticInitializers) {
4237   verifyFormat("static A x = {{{}}};\n");
4238   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4239                "               {init1, init2, init3, init4}}};",
4240                getLLVMStyleWithColumns(50));
4241 
4242   verifyFormat("somes Status::global_reps[3] = {\n"
4243                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4244                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4245                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4246                getLLVMStyleWithColumns(60));
4247   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4248                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4249                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4250                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4251   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4252                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4253                "rect.fTop}};");
4254 
4255   verifyFormat(
4256       "SomeArrayOfSomeType a = {\n"
4257       "    {{1, 2, 3},\n"
4258       "     {1, 2, 3},\n"
4259       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4260       "      333333333333333333333333333333},\n"
4261       "     {1, 2, 3},\n"
4262       "     {1, 2, 3}}};");
4263   verifyFormat(
4264       "SomeArrayOfSomeType a = {\n"
4265       "    {{1, 2, 3}},\n"
4266       "    {{1, 2, 3}},\n"
4267       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4268       "      333333333333333333333333333333}},\n"
4269       "    {{1, 2, 3}},\n"
4270       "    {{1, 2, 3}}};");
4271 
4272   verifyFormat("struct {\n"
4273                "  unsigned bit;\n"
4274                "  const char *const name;\n"
4275                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4276                "                 {kOsWin, \"Windows\"},\n"
4277                "                 {kOsLinux, \"Linux\"},\n"
4278                "                 {kOsCrOS, \"Chrome OS\"}};");
4279   verifyFormat("struct {\n"
4280                "  unsigned bit;\n"
4281                "  const char *const name;\n"
4282                "} kBitsToOs[] = {\n"
4283                "    {kOsMac, \"Mac\"},\n"
4284                "    {kOsWin, \"Windows\"},\n"
4285                "    {kOsLinux, \"Linux\"},\n"
4286                "    {kOsCrOS, \"Chrome OS\"},\n"
4287                "};");
4288 }
4289 
4290 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4291   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4292                "                      \\\n"
4293                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4294 }
4295 
4296 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4297   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4298                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4299 
4300   // Do break defaulted and deleted functions.
4301   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4302                "    default;",
4303                getLLVMStyleWithColumns(40));
4304   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4305                "    delete;",
4306                getLLVMStyleWithColumns(40));
4307 }
4308 
4309 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4310   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4311                getLLVMStyleWithColumns(40));
4312   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4313                getLLVMStyleWithColumns(40));
4314   EXPECT_EQ("#define Q                              \\\n"
4315             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4316             "  \"aaaaaaaa.cpp\"",
4317             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4318                    getLLVMStyleWithColumns(40)));
4319 }
4320 
4321 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4322   EXPECT_EQ("# 123 \"A string literal\"",
4323             format("   #     123    \"A string literal\""));
4324 }
4325 
4326 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4327   EXPECT_EQ("#;", format("#;"));
4328   verifyFormat("#\n;\n;\n;");
4329 }
4330 
4331 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4332   EXPECT_EQ("#line 42 \"test\"\n",
4333             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4334   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4335                                     getLLVMStyleWithColumns(12)));
4336 }
4337 
4338 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4339   EXPECT_EQ("#line 42 \"test\"",
4340             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4341   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4342 }
4343 
4344 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4345   verifyFormat("#define A \\x20");
4346   verifyFormat("#define A \\ x20");
4347   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4348   verifyFormat("#define A ''");
4349   verifyFormat("#define A ''qqq");
4350   verifyFormat("#define A `qqq");
4351   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4352   EXPECT_EQ("const char *c = STRINGIFY(\n"
4353             "\\na : b);",
4354             format("const char * c = STRINGIFY(\n"
4355                    "\\na : b);"));
4356 
4357   verifyFormat("a\r\\");
4358   verifyFormat("a\v\\");
4359   verifyFormat("a\f\\");
4360 }
4361 
4362 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4363   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4364   style.IndentWidth = 4;
4365   style.PPIndentWidth = 1;
4366 
4367   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4368   verifyFormat("#ifdef __linux__\n"
4369                "void foo() {\n"
4370                "    int x = 0;\n"
4371                "}\n"
4372                "#define FOO\n"
4373                "#endif\n"
4374                "void bar() {\n"
4375                "    int y = 0;\n"
4376                "}\n",
4377                style);
4378 
4379   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4380   verifyFormat("#ifdef __linux__\n"
4381                "void foo() {\n"
4382                "    int x = 0;\n"
4383                "}\n"
4384                "# define FOO foo\n"
4385                "#endif\n"
4386                "void bar() {\n"
4387                "    int y = 0;\n"
4388                "}\n",
4389                style);
4390 
4391   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4392   verifyFormat("#ifdef __linux__\n"
4393                "void foo() {\n"
4394                "    int x = 0;\n"
4395                "}\n"
4396                " #define FOO foo\n"
4397                "#endif\n"
4398                "void bar() {\n"
4399                "    int y = 0;\n"
4400                "}\n",
4401                style);
4402 }
4403 
4404 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4405   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4406   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4407   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4408   // FIXME: We never break before the macro name.
4409   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4410 
4411   verifyFormat("#define A A\n#define A A");
4412   verifyFormat("#define A(X) A\n#define A A");
4413 
4414   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4415   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4416 }
4417 
4418 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4419   EXPECT_EQ("// somecomment\n"
4420             "#include \"a.h\"\n"
4421             "#define A(  \\\n"
4422             "    A, B)\n"
4423             "#include \"b.h\"\n"
4424             "// somecomment\n",
4425             format("  // somecomment\n"
4426                    "  #include \"a.h\"\n"
4427                    "#define A(A,\\\n"
4428                    "    B)\n"
4429                    "    #include \"b.h\"\n"
4430                    " // somecomment\n",
4431                    getLLVMStyleWithColumns(13)));
4432 }
4433 
4434 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4435 
4436 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4437   EXPECT_EQ("#define A    \\\n"
4438             "  c;         \\\n"
4439             "  e;\n"
4440             "f;",
4441             format("#define A c; e;\n"
4442                    "f;",
4443                    getLLVMStyleWithColumns(14)));
4444 }
4445 
4446 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4447 
4448 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4449   EXPECT_EQ("int x,\n"
4450             "#define A\n"
4451             "    y;",
4452             format("int x,\n#define A\ny;"));
4453 }
4454 
4455 TEST_F(FormatTest, HashInMacroDefinition) {
4456   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4457   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4458   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4459   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4460   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4461   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4462   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4463   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4464   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4465   verifyFormat("#define A  \\\n"
4466                "  {        \\\n"
4467                "    f(#c); \\\n"
4468                "  }",
4469                getLLVMStyleWithColumns(11));
4470 
4471   verifyFormat("#define A(X)         \\\n"
4472                "  void function##X()",
4473                getLLVMStyleWithColumns(22));
4474 
4475   verifyFormat("#define A(a, b, c)   \\\n"
4476                "  void a##b##c()",
4477                getLLVMStyleWithColumns(22));
4478 
4479   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4480 }
4481 
4482 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4483   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4484   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4485 
4486   FormatStyle Style = getLLVMStyle();
4487   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4488   verifyFormat("#define true ((foo)1)", Style);
4489   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4490   verifyFormat("#define false((foo)0)", Style);
4491 }
4492 
4493 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4494   EXPECT_EQ("#define A b;", format("#define A \\\n"
4495                                    "          \\\n"
4496                                    "  b;",
4497                                    getLLVMStyleWithColumns(25)));
4498   EXPECT_EQ("#define A \\\n"
4499             "          \\\n"
4500             "  a;      \\\n"
4501             "  b;",
4502             format("#define A \\\n"
4503                    "          \\\n"
4504                    "  a;      \\\n"
4505                    "  b;",
4506                    getLLVMStyleWithColumns(11)));
4507   EXPECT_EQ("#define A \\\n"
4508             "  a;      \\\n"
4509             "          \\\n"
4510             "  b;",
4511             format("#define A \\\n"
4512                    "  a;      \\\n"
4513                    "          \\\n"
4514                    "  b;",
4515                    getLLVMStyleWithColumns(11)));
4516 }
4517 
4518 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
4519   verifyIncompleteFormat("#define A :");
4520   verifyFormat("#define SOMECASES  \\\n"
4521                "  case 1:          \\\n"
4522                "  case 2\n",
4523                getLLVMStyleWithColumns(20));
4524   verifyFormat("#define MACRO(a) \\\n"
4525                "  if (a)         \\\n"
4526                "    f();         \\\n"
4527                "  else           \\\n"
4528                "    g()",
4529                getLLVMStyleWithColumns(18));
4530   verifyFormat("#define A template <typename T>");
4531   verifyIncompleteFormat("#define STR(x) #x\n"
4532                          "f(STR(this_is_a_string_literal{));");
4533   verifyFormat("#pragma omp threadprivate( \\\n"
4534                "    y)), // expected-warning",
4535                getLLVMStyleWithColumns(28));
4536   verifyFormat("#d, = };");
4537   verifyFormat("#if \"a");
4538   verifyIncompleteFormat("({\n"
4539                          "#define b     \\\n"
4540                          "  }           \\\n"
4541                          "  a\n"
4542                          "a",
4543                          getLLVMStyleWithColumns(15));
4544   verifyFormat("#define A     \\\n"
4545                "  {           \\\n"
4546                "    {\n"
4547                "#define B     \\\n"
4548                "  }           \\\n"
4549                "  }",
4550                getLLVMStyleWithColumns(15));
4551   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
4552   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
4553   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
4554   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
4555 }
4556 
4557 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
4558   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
4559   EXPECT_EQ("class A : public QObject {\n"
4560             "  Q_OBJECT\n"
4561             "\n"
4562             "  A() {}\n"
4563             "};",
4564             format("class A  :  public QObject {\n"
4565                    "     Q_OBJECT\n"
4566                    "\n"
4567                    "  A() {\n}\n"
4568                    "}  ;"));
4569   EXPECT_EQ("MACRO\n"
4570             "/*static*/ int i;",
4571             format("MACRO\n"
4572                    " /*static*/ int   i;"));
4573   EXPECT_EQ("SOME_MACRO\n"
4574             "namespace {\n"
4575             "void f();\n"
4576             "} // namespace",
4577             format("SOME_MACRO\n"
4578                    "  namespace    {\n"
4579                    "void   f(  );\n"
4580                    "} // namespace"));
4581   // Only if the identifier contains at least 5 characters.
4582   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
4583   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
4584   // Only if everything is upper case.
4585   EXPECT_EQ("class A : public QObject {\n"
4586             "  Q_Object A() {}\n"
4587             "};",
4588             format("class A  :  public QObject {\n"
4589                    "     Q_Object\n"
4590                    "  A() {\n}\n"
4591                    "}  ;"));
4592 
4593   // Only if the next line can actually start an unwrapped line.
4594   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
4595             format("SOME_WEIRD_LOG_MACRO\n"
4596                    "<< SomeThing;"));
4597 
4598   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
4599                "(n, buffers))\n",
4600                getChromiumStyle(FormatStyle::LK_Cpp));
4601 
4602   // See PR41483
4603   EXPECT_EQ("/**/ FOO(a)\n"
4604             "FOO(b)",
4605             format("/**/ FOO(a)\n"
4606                    "FOO(b)"));
4607 }
4608 
4609 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
4610   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4611             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4612             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4613             "class X {};\n"
4614             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4615             "int *createScopDetectionPass() { return 0; }",
4616             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4617                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4618                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4619                    "  class X {};\n"
4620                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4621                    "  int *createScopDetectionPass() { return 0; }"));
4622   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
4623   // braces, so that inner block is indented one level more.
4624   EXPECT_EQ("int q() {\n"
4625             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4626             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4627             "  IPC_END_MESSAGE_MAP()\n"
4628             "}",
4629             format("int q() {\n"
4630                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4631                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4632                    "  IPC_END_MESSAGE_MAP()\n"
4633                    "}"));
4634 
4635   // Same inside macros.
4636   EXPECT_EQ("#define LIST(L) \\\n"
4637             "  L(A)          \\\n"
4638             "  L(B)          \\\n"
4639             "  L(C)",
4640             format("#define LIST(L) \\\n"
4641                    "  L(A) \\\n"
4642                    "  L(B) \\\n"
4643                    "  L(C)",
4644                    getGoogleStyle()));
4645 
4646   // These must not be recognized as macros.
4647   EXPECT_EQ("int q() {\n"
4648             "  f(x);\n"
4649             "  f(x) {}\n"
4650             "  f(x)->g();\n"
4651             "  f(x)->*g();\n"
4652             "  f(x).g();\n"
4653             "  f(x) = x;\n"
4654             "  f(x) += x;\n"
4655             "  f(x) -= x;\n"
4656             "  f(x) *= x;\n"
4657             "  f(x) /= x;\n"
4658             "  f(x) %= x;\n"
4659             "  f(x) &= x;\n"
4660             "  f(x) |= x;\n"
4661             "  f(x) ^= x;\n"
4662             "  f(x) >>= x;\n"
4663             "  f(x) <<= x;\n"
4664             "  f(x)[y].z();\n"
4665             "  LOG(INFO) << x;\n"
4666             "  ifstream(x) >> x;\n"
4667             "}\n",
4668             format("int q() {\n"
4669                    "  f(x)\n;\n"
4670                    "  f(x)\n {}\n"
4671                    "  f(x)\n->g();\n"
4672                    "  f(x)\n->*g();\n"
4673                    "  f(x)\n.g();\n"
4674                    "  f(x)\n = x;\n"
4675                    "  f(x)\n += x;\n"
4676                    "  f(x)\n -= x;\n"
4677                    "  f(x)\n *= x;\n"
4678                    "  f(x)\n /= x;\n"
4679                    "  f(x)\n %= x;\n"
4680                    "  f(x)\n &= x;\n"
4681                    "  f(x)\n |= x;\n"
4682                    "  f(x)\n ^= x;\n"
4683                    "  f(x)\n >>= x;\n"
4684                    "  f(x)\n <<= x;\n"
4685                    "  f(x)\n[y].z();\n"
4686                    "  LOG(INFO)\n << x;\n"
4687                    "  ifstream(x)\n >> x;\n"
4688                    "}\n"));
4689   EXPECT_EQ("int q() {\n"
4690             "  F(x)\n"
4691             "  if (1) {\n"
4692             "  }\n"
4693             "  F(x)\n"
4694             "  while (1) {\n"
4695             "  }\n"
4696             "  F(x)\n"
4697             "  G(x);\n"
4698             "  F(x)\n"
4699             "  try {\n"
4700             "    Q();\n"
4701             "  } catch (...) {\n"
4702             "  }\n"
4703             "}\n",
4704             format("int q() {\n"
4705                    "F(x)\n"
4706                    "if (1) {}\n"
4707                    "F(x)\n"
4708                    "while (1) {}\n"
4709                    "F(x)\n"
4710                    "G(x);\n"
4711                    "F(x)\n"
4712                    "try { Q(); } catch (...) {}\n"
4713                    "}\n"));
4714   EXPECT_EQ("class A {\n"
4715             "  A() : t(0) {}\n"
4716             "  A(int i) noexcept() : {}\n"
4717             "  A(X x)\n" // FIXME: function-level try blocks are broken.
4718             "  try : t(0) {\n"
4719             "  } catch (...) {\n"
4720             "  }\n"
4721             "};",
4722             format("class A {\n"
4723                    "  A()\n : t(0) {}\n"
4724                    "  A(int i)\n noexcept() : {}\n"
4725                    "  A(X x)\n"
4726                    "  try : t(0) {} catch (...) {}\n"
4727                    "};"));
4728   FormatStyle Style = getLLVMStyle();
4729   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4730   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
4731   Style.BraceWrapping.AfterFunction = true;
4732   EXPECT_EQ("void f()\n"
4733             "try\n"
4734             "{\n"
4735             "}",
4736             format("void f() try {\n"
4737                    "}",
4738                    Style));
4739   EXPECT_EQ("class SomeClass {\n"
4740             "public:\n"
4741             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4742             "};",
4743             format("class SomeClass {\n"
4744                    "public:\n"
4745                    "  SomeClass()\n"
4746                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4747                    "};"));
4748   EXPECT_EQ("class SomeClass {\n"
4749             "public:\n"
4750             "  SomeClass()\n"
4751             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4752             "};",
4753             format("class SomeClass {\n"
4754                    "public:\n"
4755                    "  SomeClass()\n"
4756                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4757                    "};",
4758                    getLLVMStyleWithColumns(40)));
4759 
4760   verifyFormat("MACRO(>)");
4761 
4762   // Some macros contain an implicit semicolon.
4763   Style = getLLVMStyle();
4764   Style.StatementMacros.push_back("FOO");
4765   verifyFormat("FOO(a) int b = 0;");
4766   verifyFormat("FOO(a)\n"
4767                "int b = 0;",
4768                Style);
4769   verifyFormat("FOO(a);\n"
4770                "int b = 0;",
4771                Style);
4772   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
4773                "int b = 0;",
4774                Style);
4775   verifyFormat("FOO()\n"
4776                "int b = 0;",
4777                Style);
4778   verifyFormat("FOO\n"
4779                "int b = 0;",
4780                Style);
4781   verifyFormat("void f() {\n"
4782                "  FOO(a)\n"
4783                "  return a;\n"
4784                "}",
4785                Style);
4786   verifyFormat("FOO(a)\n"
4787                "FOO(b)",
4788                Style);
4789   verifyFormat("int a = 0;\n"
4790                "FOO(b)\n"
4791                "int c = 0;",
4792                Style);
4793   verifyFormat("int a = 0;\n"
4794                "int x = FOO(a)\n"
4795                "int b = 0;",
4796                Style);
4797   verifyFormat("void foo(int a) { FOO(a) }\n"
4798                "uint32_t bar() {}",
4799                Style);
4800 }
4801 
4802 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
4803   verifyFormat("#define A \\\n"
4804                "  f({     \\\n"
4805                "    g();  \\\n"
4806                "  });",
4807                getLLVMStyleWithColumns(11));
4808 }
4809 
4810 TEST_F(FormatTest, IndentPreprocessorDirectives) {
4811   FormatStyle Style = getLLVMStyle();
4812   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
4813   Style.ColumnLimit = 40;
4814   verifyFormat("#ifdef _WIN32\n"
4815                "#define A 0\n"
4816                "#ifdef VAR2\n"
4817                "#define B 1\n"
4818                "#include <someheader.h>\n"
4819                "#define MACRO                          \\\n"
4820                "  some_very_long_func_aaaaaaaaaa();\n"
4821                "#endif\n"
4822                "#else\n"
4823                "#define A 1\n"
4824                "#endif",
4825                Style);
4826   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4827   verifyFormat("#ifdef _WIN32\n"
4828                "#  define A 0\n"
4829                "#  ifdef VAR2\n"
4830                "#    define B 1\n"
4831                "#    include <someheader.h>\n"
4832                "#    define MACRO                      \\\n"
4833                "      some_very_long_func_aaaaaaaaaa();\n"
4834                "#  endif\n"
4835                "#else\n"
4836                "#  define A 1\n"
4837                "#endif",
4838                Style);
4839   verifyFormat("#if A\n"
4840                "#  define MACRO                        \\\n"
4841                "    void a(int x) {                    \\\n"
4842                "      b();                             \\\n"
4843                "      c();                             \\\n"
4844                "      d();                             \\\n"
4845                "      e();                             \\\n"
4846                "      f();                             \\\n"
4847                "    }\n"
4848                "#endif",
4849                Style);
4850   // Comments before include guard.
4851   verifyFormat("// file comment\n"
4852                "// file comment\n"
4853                "#ifndef HEADER_H\n"
4854                "#define HEADER_H\n"
4855                "code();\n"
4856                "#endif",
4857                Style);
4858   // Test with include guards.
4859   verifyFormat("#ifndef HEADER_H\n"
4860                "#define HEADER_H\n"
4861                "code();\n"
4862                "#endif",
4863                Style);
4864   // Include guards must have a #define with the same variable immediately
4865   // after #ifndef.
4866   verifyFormat("#ifndef NOT_GUARD\n"
4867                "#  define FOO\n"
4868                "code();\n"
4869                "#endif",
4870                Style);
4871 
4872   // Include guards must cover the entire file.
4873   verifyFormat("code();\n"
4874                "code();\n"
4875                "#ifndef NOT_GUARD\n"
4876                "#  define NOT_GUARD\n"
4877                "code();\n"
4878                "#endif",
4879                Style);
4880   verifyFormat("#ifndef NOT_GUARD\n"
4881                "#  define NOT_GUARD\n"
4882                "code();\n"
4883                "#endif\n"
4884                "code();",
4885                Style);
4886   // Test with trailing blank lines.
4887   verifyFormat("#ifndef HEADER_H\n"
4888                "#define HEADER_H\n"
4889                "code();\n"
4890                "#endif\n",
4891                Style);
4892   // Include guards don't have #else.
4893   verifyFormat("#ifndef NOT_GUARD\n"
4894                "#  define NOT_GUARD\n"
4895                "code();\n"
4896                "#else\n"
4897                "#endif",
4898                Style);
4899   verifyFormat("#ifndef NOT_GUARD\n"
4900                "#  define NOT_GUARD\n"
4901                "code();\n"
4902                "#elif FOO\n"
4903                "#endif",
4904                Style);
4905   // Non-identifier #define after potential include guard.
4906   verifyFormat("#ifndef FOO\n"
4907                "#  define 1\n"
4908                "#endif\n",
4909                Style);
4910   // #if closes past last non-preprocessor line.
4911   verifyFormat("#ifndef FOO\n"
4912                "#define FOO\n"
4913                "#if 1\n"
4914                "int i;\n"
4915                "#  define A 0\n"
4916                "#endif\n"
4917                "#endif\n",
4918                Style);
4919   // Don't crash if there is an #elif directive without a condition.
4920   verifyFormat("#if 1\n"
4921                "int x;\n"
4922                "#elif\n"
4923                "int y;\n"
4924                "#else\n"
4925                "int z;\n"
4926                "#endif",
4927                Style);
4928   // FIXME: This doesn't handle the case where there's code between the
4929   // #ifndef and #define but all other conditions hold. This is because when
4930   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
4931   // previous code line yet, so we can't detect it.
4932   EXPECT_EQ("#ifndef NOT_GUARD\n"
4933             "code();\n"
4934             "#define NOT_GUARD\n"
4935             "code();\n"
4936             "#endif",
4937             format("#ifndef NOT_GUARD\n"
4938                    "code();\n"
4939                    "#  define NOT_GUARD\n"
4940                    "code();\n"
4941                    "#endif",
4942                    Style));
4943   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
4944   // be outside an include guard. Examples are #pragma once and
4945   // #pragma GCC diagnostic, or anything else that does not change the meaning
4946   // of the file if it's included multiple times.
4947   EXPECT_EQ("#ifdef WIN32\n"
4948             "#  pragma once\n"
4949             "#endif\n"
4950             "#ifndef HEADER_H\n"
4951             "#  define HEADER_H\n"
4952             "code();\n"
4953             "#endif",
4954             format("#ifdef WIN32\n"
4955                    "#  pragma once\n"
4956                    "#endif\n"
4957                    "#ifndef HEADER_H\n"
4958                    "#define HEADER_H\n"
4959                    "code();\n"
4960                    "#endif",
4961                    Style));
4962   // FIXME: This does not detect when there is a single non-preprocessor line
4963   // in front of an include-guard-like structure where other conditions hold
4964   // because ScopedLineState hides the line.
4965   EXPECT_EQ("code();\n"
4966             "#ifndef HEADER_H\n"
4967             "#define HEADER_H\n"
4968             "code();\n"
4969             "#endif",
4970             format("code();\n"
4971                    "#ifndef HEADER_H\n"
4972                    "#  define HEADER_H\n"
4973                    "code();\n"
4974                    "#endif",
4975                    Style));
4976   // Keep comments aligned with #, otherwise indent comments normally. These
4977   // tests cannot use verifyFormat because messUp manipulates leading
4978   // whitespace.
4979   {
4980     const char *Expected = ""
4981                            "void f() {\n"
4982                            "#if 1\n"
4983                            "// Preprocessor aligned.\n"
4984                            "#  define A 0\n"
4985                            "  // Code. Separated by blank line.\n"
4986                            "\n"
4987                            "#  define B 0\n"
4988                            "  // Code. Not aligned with #\n"
4989                            "#  define C 0\n"
4990                            "#endif";
4991     const char *ToFormat = ""
4992                            "void f() {\n"
4993                            "#if 1\n"
4994                            "// Preprocessor aligned.\n"
4995                            "#  define A 0\n"
4996                            "// Code. Separated by blank line.\n"
4997                            "\n"
4998                            "#  define B 0\n"
4999                            "   // Code. Not aligned with #\n"
5000                            "#  define C 0\n"
5001                            "#endif";
5002     EXPECT_EQ(Expected, format(ToFormat, Style));
5003     EXPECT_EQ(Expected, format(Expected, Style));
5004   }
5005   // Keep block quotes aligned.
5006   {
5007     const char *Expected = ""
5008                            "void f() {\n"
5009                            "#if 1\n"
5010                            "/* Preprocessor aligned. */\n"
5011                            "#  define A 0\n"
5012                            "  /* Code. Separated by blank line. */\n"
5013                            "\n"
5014                            "#  define B 0\n"
5015                            "  /* Code. Not aligned with # */\n"
5016                            "#  define C 0\n"
5017                            "#endif";
5018     const char *ToFormat = ""
5019                            "void f() {\n"
5020                            "#if 1\n"
5021                            "/* Preprocessor aligned. */\n"
5022                            "#  define A 0\n"
5023                            "/* Code. Separated by blank line. */\n"
5024                            "\n"
5025                            "#  define B 0\n"
5026                            "   /* Code. Not aligned with # */\n"
5027                            "#  define C 0\n"
5028                            "#endif";
5029     EXPECT_EQ(Expected, format(ToFormat, Style));
5030     EXPECT_EQ(Expected, format(Expected, Style));
5031   }
5032   // Keep comments aligned with un-indented directives.
5033   {
5034     const char *Expected = ""
5035                            "void f() {\n"
5036                            "// Preprocessor aligned.\n"
5037                            "#define A 0\n"
5038                            "  // Code. Separated by blank line.\n"
5039                            "\n"
5040                            "#define B 0\n"
5041                            "  // Code. Not aligned with #\n"
5042                            "#define C 0\n";
5043     const char *ToFormat = ""
5044                            "void f() {\n"
5045                            "// Preprocessor aligned.\n"
5046                            "#define A 0\n"
5047                            "// Code. Separated by blank line.\n"
5048                            "\n"
5049                            "#define B 0\n"
5050                            "   // Code. Not aligned with #\n"
5051                            "#define C 0\n";
5052     EXPECT_EQ(Expected, format(ToFormat, Style));
5053     EXPECT_EQ(Expected, format(Expected, Style));
5054   }
5055   // Test AfterHash with tabs.
5056   {
5057     FormatStyle Tabbed = Style;
5058     Tabbed.UseTab = FormatStyle::UT_Always;
5059     Tabbed.IndentWidth = 8;
5060     Tabbed.TabWidth = 8;
5061     verifyFormat("#ifdef _WIN32\n"
5062                  "#\tdefine A 0\n"
5063                  "#\tifdef VAR2\n"
5064                  "#\t\tdefine B 1\n"
5065                  "#\t\tinclude <someheader.h>\n"
5066                  "#\t\tdefine MACRO          \\\n"
5067                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5068                  "#\tendif\n"
5069                  "#else\n"
5070                  "#\tdefine A 1\n"
5071                  "#endif",
5072                  Tabbed);
5073   }
5074 
5075   // Regression test: Multiline-macro inside include guards.
5076   verifyFormat("#ifndef HEADER_H\n"
5077                "#define HEADER_H\n"
5078                "#define A()        \\\n"
5079                "  int i;           \\\n"
5080                "  int j;\n"
5081                "#endif // HEADER_H",
5082                getLLVMStyleWithColumns(20));
5083 
5084   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5085   // Basic before hash indent tests
5086   verifyFormat("#ifdef _WIN32\n"
5087                "  #define A 0\n"
5088                "  #ifdef VAR2\n"
5089                "    #define B 1\n"
5090                "    #include <someheader.h>\n"
5091                "    #define MACRO                      \\\n"
5092                "      some_very_long_func_aaaaaaaaaa();\n"
5093                "  #endif\n"
5094                "#else\n"
5095                "  #define A 1\n"
5096                "#endif",
5097                Style);
5098   verifyFormat("#if A\n"
5099                "  #define MACRO                        \\\n"
5100                "    void a(int x) {                    \\\n"
5101                "      b();                             \\\n"
5102                "      c();                             \\\n"
5103                "      d();                             \\\n"
5104                "      e();                             \\\n"
5105                "      f();                             \\\n"
5106                "    }\n"
5107                "#endif",
5108                Style);
5109   // Keep comments aligned with indented directives. These
5110   // tests cannot use verifyFormat because messUp manipulates leading
5111   // whitespace.
5112   {
5113     const char *Expected = "void f() {\n"
5114                            "// Aligned to preprocessor.\n"
5115                            "#if 1\n"
5116                            "  // Aligned to code.\n"
5117                            "  int a;\n"
5118                            "  #if 1\n"
5119                            "    // Aligned to preprocessor.\n"
5120                            "    #define A 0\n"
5121                            "  // Aligned to code.\n"
5122                            "  int b;\n"
5123                            "  #endif\n"
5124                            "#endif\n"
5125                            "}";
5126     const char *ToFormat = "void f() {\n"
5127                            "// Aligned to preprocessor.\n"
5128                            "#if 1\n"
5129                            "// Aligned to code.\n"
5130                            "int a;\n"
5131                            "#if 1\n"
5132                            "// Aligned to preprocessor.\n"
5133                            "#define A 0\n"
5134                            "// Aligned to code.\n"
5135                            "int b;\n"
5136                            "#endif\n"
5137                            "#endif\n"
5138                            "}";
5139     EXPECT_EQ(Expected, format(ToFormat, Style));
5140     EXPECT_EQ(Expected, format(Expected, Style));
5141   }
5142   {
5143     const char *Expected = "void f() {\n"
5144                            "/* Aligned to preprocessor. */\n"
5145                            "#if 1\n"
5146                            "  /* Aligned to code. */\n"
5147                            "  int a;\n"
5148                            "  #if 1\n"
5149                            "    /* Aligned to preprocessor. */\n"
5150                            "    #define A 0\n"
5151                            "  /* Aligned to code. */\n"
5152                            "  int b;\n"
5153                            "  #endif\n"
5154                            "#endif\n"
5155                            "}";
5156     const char *ToFormat = "void f() {\n"
5157                            "/* Aligned to preprocessor. */\n"
5158                            "#if 1\n"
5159                            "/* Aligned to code. */\n"
5160                            "int a;\n"
5161                            "#if 1\n"
5162                            "/* Aligned to preprocessor. */\n"
5163                            "#define A 0\n"
5164                            "/* Aligned to code. */\n"
5165                            "int b;\n"
5166                            "#endif\n"
5167                            "#endif\n"
5168                            "}";
5169     EXPECT_EQ(Expected, format(ToFormat, Style));
5170     EXPECT_EQ(Expected, format(Expected, Style));
5171   }
5172 
5173   // Test single comment before preprocessor
5174   verifyFormat("// Comment\n"
5175                "\n"
5176                "#if 1\n"
5177                "#endif",
5178                Style);
5179 }
5180 
5181 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5182   verifyFormat("{\n  { a #c; }\n}");
5183 }
5184 
5185 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5186   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5187             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5188   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5189             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5190 }
5191 
5192 TEST_F(FormatTest, EscapedNewlines) {
5193   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5194   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5195             format("#define A \\\nint i;\\\n  int j;", Narrow));
5196   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5197   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5198   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5199   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5200 
5201   FormatStyle AlignLeft = getLLVMStyle();
5202   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5203   EXPECT_EQ("#define MACRO(x) \\\n"
5204             "private:         \\\n"
5205             "  int x(int a);\n",
5206             format("#define MACRO(x) \\\n"
5207                    "private:         \\\n"
5208                    "  int x(int a);\n",
5209                    AlignLeft));
5210 
5211   // CRLF line endings
5212   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5213             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5214   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5215   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5216   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5217   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5218   EXPECT_EQ("#define MACRO(x) \\\r\n"
5219             "private:         \\\r\n"
5220             "  int x(int a);\r\n",
5221             format("#define MACRO(x) \\\r\n"
5222                    "private:         \\\r\n"
5223                    "  int x(int a);\r\n",
5224                    AlignLeft));
5225 
5226   FormatStyle DontAlign = getLLVMStyle();
5227   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5228   DontAlign.MaxEmptyLinesToKeep = 3;
5229   // FIXME: can't use verifyFormat here because the newline before
5230   // "public:" is not inserted the first time it's reformatted
5231   EXPECT_EQ("#define A \\\n"
5232             "  class Foo { \\\n"
5233             "    void bar(); \\\n"
5234             "\\\n"
5235             "\\\n"
5236             "\\\n"
5237             "  public: \\\n"
5238             "    void baz(); \\\n"
5239             "  };",
5240             format("#define A \\\n"
5241                    "  class Foo { \\\n"
5242                    "    void bar(); \\\n"
5243                    "\\\n"
5244                    "\\\n"
5245                    "\\\n"
5246                    "  public: \\\n"
5247                    "    void baz(); \\\n"
5248                    "  };",
5249                    DontAlign));
5250 }
5251 
5252 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5253   verifyFormat("#define A \\\n"
5254                "  int v(  \\\n"
5255                "      a); \\\n"
5256                "  int i;",
5257                getLLVMStyleWithColumns(11));
5258 }
5259 
5260 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5261   EXPECT_EQ(
5262       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5263       "                      \\\n"
5264       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5265       "\n"
5266       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5267       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5268       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5269              "\\\n"
5270              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5271              "  \n"
5272              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5273              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5274 }
5275 
5276 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5277   EXPECT_EQ("int\n"
5278             "#define A\n"
5279             "    a;",
5280             format("int\n#define A\na;"));
5281   verifyFormat("functionCallTo(\n"
5282                "    someOtherFunction(\n"
5283                "        withSomeParameters, whichInSequence,\n"
5284                "        areLongerThanALine(andAnotherCall,\n"
5285                "#define A B\n"
5286                "                           withMoreParamters,\n"
5287                "                           whichStronglyInfluenceTheLayout),\n"
5288                "        andMoreParameters),\n"
5289                "    trailing);",
5290                getLLVMStyleWithColumns(69));
5291   verifyFormat("Foo::Foo()\n"
5292                "#ifdef BAR\n"
5293                "    : baz(0)\n"
5294                "#endif\n"
5295                "{\n"
5296                "}");
5297   verifyFormat("void f() {\n"
5298                "  if (true)\n"
5299                "#ifdef A\n"
5300                "    f(42);\n"
5301                "  x();\n"
5302                "#else\n"
5303                "    g();\n"
5304                "  x();\n"
5305                "#endif\n"
5306                "}");
5307   verifyFormat("void f(param1, param2,\n"
5308                "       param3,\n"
5309                "#ifdef A\n"
5310                "       param4(param5,\n"
5311                "#ifdef A1\n"
5312                "              param6,\n"
5313                "#ifdef A2\n"
5314                "              param7),\n"
5315                "#else\n"
5316                "              param8),\n"
5317                "       param9,\n"
5318                "#endif\n"
5319                "       param10,\n"
5320                "#endif\n"
5321                "       param11)\n"
5322                "#else\n"
5323                "       param12)\n"
5324                "#endif\n"
5325                "{\n"
5326                "  x();\n"
5327                "}",
5328                getLLVMStyleWithColumns(28));
5329   verifyFormat("#if 1\n"
5330                "int i;");
5331   verifyFormat("#if 1\n"
5332                "#endif\n"
5333                "#if 1\n"
5334                "#else\n"
5335                "#endif\n");
5336   verifyFormat("DEBUG({\n"
5337                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5338                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5339                "});\n"
5340                "#if a\n"
5341                "#else\n"
5342                "#endif");
5343 
5344   verifyIncompleteFormat("void f(\n"
5345                          "#if A\n"
5346                          ");\n"
5347                          "#else\n"
5348                          "#endif");
5349 }
5350 
5351 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5352   verifyFormat("#endif\n"
5353                "#if B");
5354 }
5355 
5356 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5357   FormatStyle SingleLine = getLLVMStyle();
5358   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5359   verifyFormat("#if 0\n"
5360                "#elif 1\n"
5361                "#endif\n"
5362                "void foo() {\n"
5363                "  if (test) foo2();\n"
5364                "}",
5365                SingleLine);
5366 }
5367 
5368 TEST_F(FormatTest, LayoutBlockInsideParens) {
5369   verifyFormat("functionCall({ int i; });");
5370   verifyFormat("functionCall({\n"
5371                "  int i;\n"
5372                "  int j;\n"
5373                "});");
5374   verifyFormat("functionCall(\n"
5375                "    {\n"
5376                "      int i;\n"
5377                "      int j;\n"
5378                "    },\n"
5379                "    aaaa, bbbb, cccc);");
5380   verifyFormat("functionA(functionB({\n"
5381                "            int i;\n"
5382                "            int j;\n"
5383                "          }),\n"
5384                "          aaaa, bbbb, cccc);");
5385   verifyFormat("functionCall(\n"
5386                "    {\n"
5387                "      int i;\n"
5388                "      int j;\n"
5389                "    },\n"
5390                "    aaaa, bbbb, // comment\n"
5391                "    cccc);");
5392   verifyFormat("functionA(functionB({\n"
5393                "            int i;\n"
5394                "            int j;\n"
5395                "          }),\n"
5396                "          aaaa, bbbb, // comment\n"
5397                "          cccc);");
5398   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5399   verifyFormat("functionCall(aaaa, bbbb, {\n"
5400                "  int i;\n"
5401                "  int j;\n"
5402                "});");
5403   verifyFormat(
5404       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5405       "    {\n"
5406       "      int i; // break\n"
5407       "    },\n"
5408       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5409       "                                     ccccccccccccccccc));");
5410   verifyFormat("DEBUG({\n"
5411                "  if (a)\n"
5412                "    f();\n"
5413                "});");
5414 }
5415 
5416 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5417   EXPECT_EQ("SOME_MACRO { int i; }\n"
5418             "int i;",
5419             format("  SOME_MACRO  {int i;}  int i;"));
5420 }
5421 
5422 TEST_F(FormatTest, LayoutNestedBlocks) {
5423   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5424                "  struct s {\n"
5425                "    int i;\n"
5426                "  };\n"
5427                "  s kBitsToOs[] = {{10}};\n"
5428                "  for (int i = 0; i < 10; ++i)\n"
5429                "    return;\n"
5430                "}");
5431   verifyFormat("call(parameter, {\n"
5432                "  something();\n"
5433                "  // Comment using all columns.\n"
5434                "  somethingelse();\n"
5435                "});",
5436                getLLVMStyleWithColumns(40));
5437   verifyFormat("DEBUG( //\n"
5438                "    { f(); }, a);");
5439   verifyFormat("DEBUG( //\n"
5440                "    {\n"
5441                "      f(); //\n"
5442                "    },\n"
5443                "    a);");
5444 
5445   EXPECT_EQ("call(parameter, {\n"
5446             "  something();\n"
5447             "  // Comment too\n"
5448             "  // looooooooooong.\n"
5449             "  somethingElse();\n"
5450             "});",
5451             format("call(parameter, {\n"
5452                    "  something();\n"
5453                    "  // Comment too looooooooooong.\n"
5454                    "  somethingElse();\n"
5455                    "});",
5456                    getLLVMStyleWithColumns(29)));
5457   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5458   EXPECT_EQ("DEBUG({ // comment\n"
5459             "  int i;\n"
5460             "});",
5461             format("DEBUG({ // comment\n"
5462                    "int  i;\n"
5463                    "});"));
5464   EXPECT_EQ("DEBUG({\n"
5465             "  int i;\n"
5466             "\n"
5467             "  // comment\n"
5468             "  int j;\n"
5469             "});",
5470             format("DEBUG({\n"
5471                    "  int  i;\n"
5472                    "\n"
5473                    "  // comment\n"
5474                    "  int  j;\n"
5475                    "});"));
5476 
5477   verifyFormat("DEBUG({\n"
5478                "  if (a)\n"
5479                "    return;\n"
5480                "});");
5481   verifyGoogleFormat("DEBUG({\n"
5482                      "  if (a) return;\n"
5483                      "});");
5484   FormatStyle Style = getGoogleStyle();
5485   Style.ColumnLimit = 45;
5486   verifyFormat("Debug(\n"
5487                "    aaaaa,\n"
5488                "    {\n"
5489                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5490                "    },\n"
5491                "    a);",
5492                Style);
5493 
5494   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5495 
5496   verifyNoCrash("^{v^{a}}");
5497 }
5498 
5499 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
5500   EXPECT_EQ("#define MACRO()                     \\\n"
5501             "  Debug(aaa, /* force line break */ \\\n"
5502             "        {                           \\\n"
5503             "          int i;                    \\\n"
5504             "          int j;                    \\\n"
5505             "        })",
5506             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
5507                    "          {  int   i;  int  j;   })",
5508                    getGoogleStyle()));
5509 
5510   EXPECT_EQ("#define A                                       \\\n"
5511             "  [] {                                          \\\n"
5512             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
5513             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
5514             "  }",
5515             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5516                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
5517                    getGoogleStyle()));
5518 }
5519 
5520 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
5521   EXPECT_EQ("{}", format("{}"));
5522   verifyFormat("enum E {};");
5523   verifyFormat("enum E {}");
5524   FormatStyle Style = getLLVMStyle();
5525   Style.SpaceInEmptyBlock = true;
5526   EXPECT_EQ("void f() { }", format("void f() {}", Style));
5527   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
5528   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
5529   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5530   Style.BraceWrapping.BeforeElse = false;
5531   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5532   verifyFormat("if (a)\n"
5533                "{\n"
5534                "} else if (b)\n"
5535                "{\n"
5536                "} else\n"
5537                "{ }",
5538                Style);
5539   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
5540   verifyFormat("if (a) {\n"
5541                "} else if (b) {\n"
5542                "} else {\n"
5543                "}",
5544                Style);
5545   Style.BraceWrapping.BeforeElse = true;
5546   verifyFormat("if (a) { }\n"
5547                "else if (b) { }\n"
5548                "else { }",
5549                Style);
5550 }
5551 
5552 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
5553   FormatStyle Style = getLLVMStyle();
5554   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
5555   Style.MacroBlockEnd = "^[A-Z_]+_END$";
5556   verifyFormat("FOO_BEGIN\n"
5557                "  FOO_ENTRY\n"
5558                "FOO_END",
5559                Style);
5560   verifyFormat("FOO_BEGIN\n"
5561                "  NESTED_FOO_BEGIN\n"
5562                "    NESTED_FOO_ENTRY\n"
5563                "  NESTED_FOO_END\n"
5564                "FOO_END",
5565                Style);
5566   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
5567                "  int x;\n"
5568                "  x = 1;\n"
5569                "FOO_END(Baz)",
5570                Style);
5571 }
5572 
5573 //===----------------------------------------------------------------------===//
5574 // Line break tests.
5575 //===----------------------------------------------------------------------===//
5576 
5577 TEST_F(FormatTest, PreventConfusingIndents) {
5578   verifyFormat(
5579       "void f() {\n"
5580       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
5581       "                         parameter, parameter, parameter)),\n"
5582       "                     SecondLongCall(parameter));\n"
5583       "}");
5584   verifyFormat(
5585       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5586       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5587       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5588       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
5589   verifyFormat(
5590       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5591       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
5592       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5593       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
5594   verifyFormat(
5595       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5596       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
5597       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
5598       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
5599   verifyFormat("int a = bbbb && ccc &&\n"
5600                "        fffff(\n"
5601                "#define A Just forcing a new line\n"
5602                "            ddd);");
5603 }
5604 
5605 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
5606   verifyFormat(
5607       "bool aaaaaaa =\n"
5608       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
5609       "    bbbbbbbb();");
5610   verifyFormat(
5611       "bool aaaaaaa =\n"
5612       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
5613       "    bbbbbbbb();");
5614 
5615   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5616                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
5617                "    ccccccccc == ddddddddddd;");
5618   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5619                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
5620                "    ccccccccc == ddddddddddd;");
5621   verifyFormat(
5622       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
5623       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
5624       "    ccccccccc == ddddddddddd;");
5625 
5626   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5627                "                 aaaaaa) &&\n"
5628                "         bbbbbb && cccccc;");
5629   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5630                "                 aaaaaa) >>\n"
5631                "         bbbbbb;");
5632   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
5633                "    SourceMgr.getSpellingColumnNumber(\n"
5634                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
5635                "    1);");
5636 
5637   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5638                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
5639                "    cccccc) {\n}");
5640   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5641                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5642                "              cccccc) {\n}");
5643   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5644                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5645                "              cccccc) {\n}");
5646   verifyFormat("b = a &&\n"
5647                "    // Comment\n"
5648                "    b.c && d;");
5649 
5650   // If the LHS of a comparison is not a binary expression itself, the
5651   // additional linebreak confuses many people.
5652   verifyFormat(
5653       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5654       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
5655       "}");
5656   verifyFormat(
5657       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5658       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5659       "}");
5660   verifyFormat(
5661       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
5662       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5663       "}");
5664   verifyFormat(
5665       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5666       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
5667       "}");
5668   // Even explicit parentheses stress the precedence enough to make the
5669   // additional break unnecessary.
5670   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5671                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5672                "}");
5673   // This cases is borderline, but with the indentation it is still readable.
5674   verifyFormat(
5675       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5676       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5677       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
5678       "}",
5679       getLLVMStyleWithColumns(75));
5680 
5681   // If the LHS is a binary expression, we should still use the additional break
5682   // as otherwise the formatting hides the operator precedence.
5683   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5684                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5685                "    5) {\n"
5686                "}");
5687   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5688                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
5689                "    5) {\n"
5690                "}");
5691 
5692   FormatStyle OnePerLine = getLLVMStyle();
5693   OnePerLine.BinPackParameters = false;
5694   verifyFormat(
5695       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5696       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5697       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
5698       OnePerLine);
5699 
5700   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
5701                "                .aaa(aaaaaaaaaaaaa) *\n"
5702                "            aaaaaaa +\n"
5703                "        aaaaaaa;",
5704                getLLVMStyleWithColumns(40));
5705 }
5706 
5707 TEST_F(FormatTest, ExpressionIndentation) {
5708   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5709                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5710                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5711                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5712                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
5713                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
5714                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5715                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
5716                "                 ccccccccccccccccccccccccccccccccccccccccc;");
5717   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5718                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5719                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5720                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5721   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5722                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5723                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5724                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5725   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5726                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5727                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5728                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5729   verifyFormat("if () {\n"
5730                "} else if (aaaaa && bbbbb > // break\n"
5731                "                        ccccc) {\n"
5732                "}");
5733   verifyFormat("if () {\n"
5734                "} else if constexpr (aaaaa && bbbbb > // break\n"
5735                "                                  ccccc) {\n"
5736                "}");
5737   verifyFormat("if () {\n"
5738                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
5739                "                                  ccccc) {\n"
5740                "}");
5741   verifyFormat("if () {\n"
5742                "} else if (aaaaa &&\n"
5743                "           bbbbb > // break\n"
5744                "               ccccc &&\n"
5745                "           ddddd) {\n"
5746                "}");
5747 
5748   // Presence of a trailing comment used to change indentation of b.
5749   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
5750                "       b;\n"
5751                "return aaaaaaaaaaaaaaaaaaa +\n"
5752                "       b; //",
5753                getLLVMStyleWithColumns(30));
5754 }
5755 
5756 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
5757   // Not sure what the best system is here. Like this, the LHS can be found
5758   // immediately above an operator (everything with the same or a higher
5759   // indent). The RHS is aligned right of the operator and so compasses
5760   // everything until something with the same indent as the operator is found.
5761   // FIXME: Is this a good system?
5762   FormatStyle Style = getLLVMStyle();
5763   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5764   verifyFormat(
5765       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5766       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5767       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5768       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5769       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5770       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5771       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5772       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5773       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
5774       Style);
5775   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5776                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5777                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5778                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5779                Style);
5780   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5781                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5782                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5783                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5784                Style);
5785   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5786                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5787                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5788                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5789                Style);
5790   verifyFormat("if () {\n"
5791                "} else if (aaaaa\n"
5792                "           && bbbbb // break\n"
5793                "                  > ccccc) {\n"
5794                "}",
5795                Style);
5796   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5797                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5798                Style);
5799   verifyFormat("return (a)\n"
5800                "       // comment\n"
5801                "       + b;",
5802                Style);
5803   verifyFormat(
5804       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5805       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5806       "             + cc;",
5807       Style);
5808 
5809   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5810                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5811                Style);
5812 
5813   // Forced by comments.
5814   verifyFormat(
5815       "unsigned ContentSize =\n"
5816       "    sizeof(int16_t)   // DWARF ARange version number\n"
5817       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5818       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5819       "    + sizeof(int8_t); // Segment Size (in bytes)");
5820 
5821   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5822                "       == boost::fusion::at_c<1>(iiii).second;",
5823                Style);
5824 
5825   Style.ColumnLimit = 60;
5826   verifyFormat("zzzzzzzzzz\n"
5827                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5828                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5829                Style);
5830 
5831   Style.ColumnLimit = 80;
5832   Style.IndentWidth = 4;
5833   Style.TabWidth = 4;
5834   Style.UseTab = FormatStyle::UT_Always;
5835   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5836   Style.AlignOperands = FormatStyle::OAS_DontAlign;
5837   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
5838             "\t&& (someOtherLongishConditionPart1\n"
5839             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
5840             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
5841                    "(someOtherLongishConditionPart1 || "
5842                    "someOtherEvenLongerNestedConditionPart2);",
5843                    Style));
5844 }
5845 
5846 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
5847   FormatStyle Style = getLLVMStyle();
5848   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5849   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
5850 
5851   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5852                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5853                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5854                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5855                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5856                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5857                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5858                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5859                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
5860                Style);
5861   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5862                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5863                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5864                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5865                Style);
5866   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5867                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5868                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5869                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5870                Style);
5871   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5872                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5873                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5874                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5875                Style);
5876   verifyFormat("if () {\n"
5877                "} else if (aaaaa\n"
5878                "           && bbbbb // break\n"
5879                "                  > ccccc) {\n"
5880                "}",
5881                Style);
5882   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5883                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5884                Style);
5885   verifyFormat("return (a)\n"
5886                "     // comment\n"
5887                "     + b;",
5888                Style);
5889   verifyFormat(
5890       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5891       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5892       "           + cc;",
5893       Style);
5894   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
5895                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
5896                "                        : 3333333333333333;",
5897                Style);
5898   verifyFormat(
5899       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
5900       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
5901       "                                             : eeeeeeeeeeeeeeeeee)\n"
5902       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
5903       "                        : 3333333333333333;",
5904       Style);
5905   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5906                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5907                Style);
5908 
5909   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5910                "    == boost::fusion::at_c<1>(iiii).second;",
5911                Style);
5912 
5913   Style.ColumnLimit = 60;
5914   verifyFormat("zzzzzzzzzzzzz\n"
5915                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5916                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5917                Style);
5918 
5919   // Forced by comments.
5920   Style.ColumnLimit = 80;
5921   verifyFormat(
5922       "unsigned ContentSize\n"
5923       "    = sizeof(int16_t) // DWARF ARange version number\n"
5924       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5925       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5926       "    + sizeof(int8_t); // Segment Size (in bytes)",
5927       Style);
5928 
5929   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5930   verifyFormat(
5931       "unsigned ContentSize =\n"
5932       "    sizeof(int16_t)   // DWARF ARange version number\n"
5933       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5934       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5935       "    + sizeof(int8_t); // Segment Size (in bytes)",
5936       Style);
5937 
5938   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
5939   verifyFormat(
5940       "unsigned ContentSize =\n"
5941       "    sizeof(int16_t)   // DWARF ARange version number\n"
5942       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5943       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5944       "    + sizeof(int8_t); // Segment Size (in bytes)",
5945       Style);
5946 }
5947 
5948 TEST_F(FormatTest, EnforcedOperatorWraps) {
5949   // Here we'd like to wrap after the || operators, but a comment is forcing an
5950   // earlier wrap.
5951   verifyFormat("bool x = aaaaa //\n"
5952                "         || bbbbb\n"
5953                "         //\n"
5954                "         || cccc;");
5955 }
5956 
5957 TEST_F(FormatTest, NoOperandAlignment) {
5958   FormatStyle Style = getLLVMStyle();
5959   Style.AlignOperands = FormatStyle::OAS_DontAlign;
5960   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
5961                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5962                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5963                Style);
5964   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5965   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5966                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5967                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5968                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5969                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5970                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5971                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5972                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5973                "        > ccccccccccccccccccccccccccccccccccccccccc;",
5974                Style);
5975 
5976   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5977                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5978                "    + cc;",
5979                Style);
5980   verifyFormat("int a = aa\n"
5981                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5982                "        * cccccccccccccccccccccccccccccccccccc;\n",
5983                Style);
5984 
5985   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5986   verifyFormat("return (a > b\n"
5987                "    // comment1\n"
5988                "    // comment2\n"
5989                "    || c);",
5990                Style);
5991 }
5992 
5993 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
5994   FormatStyle Style = getLLVMStyle();
5995   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5996   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5997                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5998                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5999                Style);
6000 }
6001 
6002 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6003   FormatStyle Style = getLLVMStyle();
6004   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6005   Style.BinPackArguments = false;
6006   Style.ColumnLimit = 40;
6007   verifyFormat("void test() {\n"
6008                "  someFunction(\n"
6009                "      this + argument + is + quite\n"
6010                "      + long + so + it + gets + wrapped\n"
6011                "      + but + remains + bin - packed);\n"
6012                "}",
6013                Style);
6014   verifyFormat("void test() {\n"
6015                "  someFunction(arg1,\n"
6016                "               this + argument + is\n"
6017                "                   + quite + long + so\n"
6018                "                   + it + gets + wrapped\n"
6019                "                   + but + remains + bin\n"
6020                "                   - packed,\n"
6021                "               arg3);\n"
6022                "}",
6023                Style);
6024   verifyFormat("void test() {\n"
6025                "  someFunction(\n"
6026                "      arg1,\n"
6027                "      this + argument + has\n"
6028                "          + anotherFunc(nested,\n"
6029                "                        calls + whose\n"
6030                "                            + arguments\n"
6031                "                            + are + also\n"
6032                "                            + wrapped,\n"
6033                "                        in + addition)\n"
6034                "          + to + being + bin - packed,\n"
6035                "      arg3);\n"
6036                "}",
6037                Style);
6038 
6039   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6040   verifyFormat("void test() {\n"
6041                "  someFunction(\n"
6042                "      arg1,\n"
6043                "      this + argument + has +\n"
6044                "          anotherFunc(nested,\n"
6045                "                      calls + whose +\n"
6046                "                          arguments +\n"
6047                "                          are + also +\n"
6048                "                          wrapped,\n"
6049                "                      in + addition) +\n"
6050                "          to + being + bin - packed,\n"
6051                "      arg3);\n"
6052                "}",
6053                Style);
6054 }
6055 
6056 TEST_F(FormatTest, ConstructorInitializers) {
6057   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6058   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6059                getLLVMStyleWithColumns(45));
6060   verifyFormat("Constructor()\n"
6061                "    : Inttializer(FitsOnTheLine) {}",
6062                getLLVMStyleWithColumns(44));
6063   verifyFormat("Constructor()\n"
6064                "    : Inttializer(FitsOnTheLine) {}",
6065                getLLVMStyleWithColumns(43));
6066 
6067   verifyFormat("template <typename T>\n"
6068                "Constructor() : Initializer(FitsOnTheLine) {}",
6069                getLLVMStyleWithColumns(45));
6070 
6071   verifyFormat(
6072       "SomeClass::Constructor()\n"
6073       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6074 
6075   verifyFormat(
6076       "SomeClass::Constructor()\n"
6077       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6078       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6079   verifyFormat(
6080       "SomeClass::Constructor()\n"
6081       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6082       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6083   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6084                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6085                "    : aaaaaaaaaa(aaaaaa) {}");
6086 
6087   verifyFormat("Constructor()\n"
6088                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6089                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6090                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6091                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6092 
6093   verifyFormat("Constructor()\n"
6094                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6095                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6096 
6097   verifyFormat("Constructor(int Parameter = 0)\n"
6098                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6099                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6100   verifyFormat("Constructor()\n"
6101                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6102                "}",
6103                getLLVMStyleWithColumns(60));
6104   verifyFormat("Constructor()\n"
6105                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6106                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6107 
6108   // Here a line could be saved by splitting the second initializer onto two
6109   // lines, but that is not desirable.
6110   verifyFormat("Constructor()\n"
6111                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6112                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6113                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6114 
6115   FormatStyle OnePerLine = getLLVMStyle();
6116   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6117   verifyFormat("MyClass::MyClass()\n"
6118                "    : a(a),\n"
6119                "      b(b),\n"
6120                "      c(c) {}",
6121                OnePerLine);
6122   verifyFormat("MyClass::MyClass()\n"
6123                "    : a(a), // comment\n"
6124                "      b(b),\n"
6125                "      c(c) {}",
6126                OnePerLine);
6127   verifyFormat("MyClass::MyClass(int a)\n"
6128                "    : b(a),      // comment\n"
6129                "      c(a + 1) { // lined up\n"
6130                "}",
6131                OnePerLine);
6132   verifyFormat("Constructor()\n"
6133                "    : a(b, b, b) {}",
6134                OnePerLine);
6135   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6136   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6137   verifyFormat("SomeClass::Constructor()\n"
6138                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6139                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6140                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6141                OnePerLine);
6142   verifyFormat("SomeClass::Constructor()\n"
6143                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6144                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6145                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6146                OnePerLine);
6147   verifyFormat("MyClass::MyClass(int var)\n"
6148                "    : some_var_(var),            // 4 space indent\n"
6149                "      some_other_var_(var + 1) { // lined up\n"
6150                "}",
6151                OnePerLine);
6152   verifyFormat("Constructor()\n"
6153                "    : aaaaa(aaaaaa),\n"
6154                "      aaaaa(aaaaaa),\n"
6155                "      aaaaa(aaaaaa),\n"
6156                "      aaaaa(aaaaaa),\n"
6157                "      aaaaa(aaaaaa) {}",
6158                OnePerLine);
6159   verifyFormat("Constructor()\n"
6160                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6161                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6162                OnePerLine);
6163   OnePerLine.BinPackParameters = false;
6164   verifyFormat(
6165       "Constructor()\n"
6166       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6167       "          aaaaaaaaaaa().aaa(),\n"
6168       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6169       OnePerLine);
6170   OnePerLine.ColumnLimit = 60;
6171   verifyFormat("Constructor()\n"
6172                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6173                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6174                OnePerLine);
6175 
6176   EXPECT_EQ("Constructor()\n"
6177             "    : // Comment forcing unwanted break.\n"
6178             "      aaaa(aaaa) {}",
6179             format("Constructor() :\n"
6180                    "    // Comment forcing unwanted break.\n"
6181                    "    aaaa(aaaa) {}"));
6182 }
6183 
6184 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6185   FormatStyle Style = getLLVMStyle();
6186   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6187   Style.ColumnLimit = 60;
6188   Style.BinPackParameters = false;
6189 
6190   for (int i = 0; i < 4; ++i) {
6191     // Test all combinations of parameters that should not have an effect.
6192     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6193     Style.AllowAllArgumentsOnNextLine = i & 2;
6194 
6195     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6196     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6197     verifyFormat("Constructor()\n"
6198                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6199                  Style);
6200     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6201 
6202     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6203     verifyFormat("Constructor()\n"
6204                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6205                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6206                  Style);
6207     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6208 
6209     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6210     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6211     verifyFormat("Constructor()\n"
6212                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6213                  Style);
6214 
6215     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6216     verifyFormat("Constructor()\n"
6217                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6218                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6219                  Style);
6220 
6221     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6222     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6223     verifyFormat("Constructor() :\n"
6224                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6225                  Style);
6226 
6227     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6228     verifyFormat("Constructor() :\n"
6229                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6230                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6231                  Style);
6232   }
6233 
6234   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6235   // AllowAllConstructorInitializersOnNextLine in all
6236   // BreakConstructorInitializers modes
6237   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6238   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6239   verifyFormat("SomeClassWithALongName::Constructor(\n"
6240                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6241                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6242                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6243                Style);
6244 
6245   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6246   verifyFormat("SomeClassWithALongName::Constructor(\n"
6247                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6248                "    int bbbbbbbbbbbbb,\n"
6249                "    int cccccccccccccccc)\n"
6250                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6251                Style);
6252 
6253   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6254   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6255   verifyFormat("SomeClassWithALongName::Constructor(\n"
6256                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6257                "    int bbbbbbbbbbbbb)\n"
6258                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6259                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6260                Style);
6261 
6262   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6263 
6264   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6265   verifyFormat("SomeClassWithALongName::Constructor(\n"
6266                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6267                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6268                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6269                Style);
6270 
6271   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6272   verifyFormat("SomeClassWithALongName::Constructor(\n"
6273                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6274                "    int bbbbbbbbbbbbb,\n"
6275                "    int cccccccccccccccc)\n"
6276                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6277                Style);
6278 
6279   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6280   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6281   verifyFormat("SomeClassWithALongName::Constructor(\n"
6282                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6283                "    int bbbbbbbbbbbbb)\n"
6284                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6285                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6286                Style);
6287 
6288   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6289   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6290   verifyFormat("SomeClassWithALongName::Constructor(\n"
6291                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6292                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6293                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6294                Style);
6295 
6296   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6297   verifyFormat("SomeClassWithALongName::Constructor(\n"
6298                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6299                "    int bbbbbbbbbbbbb,\n"
6300                "    int cccccccccccccccc) :\n"
6301                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6302                Style);
6303 
6304   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6305   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6306   verifyFormat("SomeClassWithALongName::Constructor(\n"
6307                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6308                "    int bbbbbbbbbbbbb) :\n"
6309                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6310                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6311                Style);
6312 }
6313 
6314 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6315   FormatStyle Style = getLLVMStyle();
6316   Style.ColumnLimit = 60;
6317   Style.BinPackArguments = false;
6318   for (int i = 0; i < 4; ++i) {
6319     // Test all combinations of parameters that should not have an effect.
6320     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6321     Style.PackConstructorInitializers =
6322         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6323 
6324     Style.AllowAllArgumentsOnNextLine = true;
6325     verifyFormat("void foo() {\n"
6326                  "  FunctionCallWithReallyLongName(\n"
6327                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6328                  "}",
6329                  Style);
6330     Style.AllowAllArgumentsOnNextLine = false;
6331     verifyFormat("void foo() {\n"
6332                  "  FunctionCallWithReallyLongName(\n"
6333                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6334                  "      bbbbbbbbbbbb);\n"
6335                  "}",
6336                  Style);
6337 
6338     Style.AllowAllArgumentsOnNextLine = true;
6339     verifyFormat("void foo() {\n"
6340                  "  auto VariableWithReallyLongName = {\n"
6341                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6342                  "}",
6343                  Style);
6344     Style.AllowAllArgumentsOnNextLine = false;
6345     verifyFormat("void foo() {\n"
6346                  "  auto VariableWithReallyLongName = {\n"
6347                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6348                  "      bbbbbbbbbbbb};\n"
6349                  "}",
6350                  Style);
6351   }
6352 
6353   // This parameter should not affect declarations.
6354   Style.BinPackParameters = false;
6355   Style.AllowAllArgumentsOnNextLine = false;
6356   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6357   verifyFormat("void FunctionCallWithReallyLongName(\n"
6358                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6359                Style);
6360   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6361   verifyFormat("void FunctionCallWithReallyLongName(\n"
6362                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6363                "    int bbbbbbbbbbbb);",
6364                Style);
6365 }
6366 
6367 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6368   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6369   // and BAS_Align.
6370   auto Style = getLLVMStyle();
6371   Style.ColumnLimit = 35;
6372   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6373                     "void functionDecl(int A, int B, int C);";
6374   Style.AllowAllArgumentsOnNextLine = false;
6375   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6376   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6377                       "    paramC);\n"
6378                       "void functionDecl(int A, int B,\n"
6379                       "    int C);"),
6380             format(Input, Style));
6381   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6382   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6383                       "             paramC);\n"
6384                       "void functionDecl(int A, int B,\n"
6385                       "                  int C);"),
6386             format(Input, Style));
6387   // However, BAS_AlwaysBreak should take precedence over
6388   // AllowAllArgumentsOnNextLine.
6389   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6390   EXPECT_EQ(StringRef("functionCall(\n"
6391                       "    paramA, paramB, paramC);\n"
6392                       "void functionDecl(\n"
6393                       "    int A, int B, int C);"),
6394             format(Input, Style));
6395 
6396   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6397   // first argument.
6398   Style.AllowAllArgumentsOnNextLine = true;
6399   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6400   EXPECT_EQ(StringRef("functionCall(\n"
6401                       "    paramA, paramB, paramC);\n"
6402                       "void functionDecl(\n"
6403                       "    int A, int B, int C);"),
6404             format(Input, Style));
6405   // It wouldn't fit on one line with aligned parameters so this setting
6406   // doesn't change anything for BAS_Align.
6407   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6408   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6409                       "             paramC);\n"
6410                       "void functionDecl(int A, int B,\n"
6411                       "                  int C);"),
6412             format(Input, Style));
6413   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6414   EXPECT_EQ(StringRef("functionCall(\n"
6415                       "    paramA, paramB, paramC);\n"
6416                       "void functionDecl(\n"
6417                       "    int A, int B, int C);"),
6418             format(Input, Style));
6419 }
6420 
6421 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6422   FormatStyle Style = getLLVMStyle();
6423   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6424 
6425   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6426   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6427                getStyleWithColumns(Style, 45));
6428   verifyFormat("Constructor() :\n"
6429                "    Initializer(FitsOnTheLine) {}",
6430                getStyleWithColumns(Style, 44));
6431   verifyFormat("Constructor() :\n"
6432                "    Initializer(FitsOnTheLine) {}",
6433                getStyleWithColumns(Style, 43));
6434 
6435   verifyFormat("template <typename T>\n"
6436                "Constructor() : Initializer(FitsOnTheLine) {}",
6437                getStyleWithColumns(Style, 50));
6438   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6439   verifyFormat(
6440       "SomeClass::Constructor() :\n"
6441       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6442       Style);
6443 
6444   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6445   verifyFormat(
6446       "SomeClass::Constructor() :\n"
6447       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6448       Style);
6449 
6450   verifyFormat(
6451       "SomeClass::Constructor() :\n"
6452       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6453       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6454       Style);
6455   verifyFormat(
6456       "SomeClass::Constructor() :\n"
6457       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6458       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6459       Style);
6460   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6461                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6462                "    aaaaaaaaaa(aaaaaa) {}",
6463                Style);
6464 
6465   verifyFormat("Constructor() :\n"
6466                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6467                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6468                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6469                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
6470                Style);
6471 
6472   verifyFormat("Constructor() :\n"
6473                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6474                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6475                Style);
6476 
6477   verifyFormat("Constructor(int Parameter = 0) :\n"
6478                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6479                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
6480                Style);
6481   verifyFormat("Constructor() :\n"
6482                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6483                "}",
6484                getStyleWithColumns(Style, 60));
6485   verifyFormat("Constructor() :\n"
6486                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6487                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
6488                Style);
6489 
6490   // Here a line could be saved by splitting the second initializer onto two
6491   // lines, but that is not desirable.
6492   verifyFormat("Constructor() :\n"
6493                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6494                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
6495                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6496                Style);
6497 
6498   FormatStyle OnePerLine = Style;
6499   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6500   verifyFormat("SomeClass::Constructor() :\n"
6501                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6502                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6503                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6504                OnePerLine);
6505   verifyFormat("SomeClass::Constructor() :\n"
6506                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6507                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6508                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6509                OnePerLine);
6510   verifyFormat("MyClass::MyClass(int var) :\n"
6511                "    some_var_(var),            // 4 space indent\n"
6512                "    some_other_var_(var + 1) { // lined up\n"
6513                "}",
6514                OnePerLine);
6515   verifyFormat("Constructor() :\n"
6516                "    aaaaa(aaaaaa),\n"
6517                "    aaaaa(aaaaaa),\n"
6518                "    aaaaa(aaaaaa),\n"
6519                "    aaaaa(aaaaaa),\n"
6520                "    aaaaa(aaaaaa) {}",
6521                OnePerLine);
6522   verifyFormat("Constructor() :\n"
6523                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6524                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
6525                OnePerLine);
6526   OnePerLine.BinPackParameters = false;
6527   verifyFormat("Constructor() :\n"
6528                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6529                "        aaaaaaaaaaa().aaa(),\n"
6530                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6531                OnePerLine);
6532   OnePerLine.ColumnLimit = 60;
6533   verifyFormat("Constructor() :\n"
6534                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6535                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6536                OnePerLine);
6537 
6538   EXPECT_EQ("Constructor() :\n"
6539             "    // Comment forcing unwanted break.\n"
6540             "    aaaa(aaaa) {}",
6541             format("Constructor() :\n"
6542                    "    // Comment forcing unwanted break.\n"
6543                    "    aaaa(aaaa) {}",
6544                    Style));
6545 
6546   Style.ColumnLimit = 0;
6547   verifyFormat("SomeClass::Constructor() :\n"
6548                "    a(a) {}",
6549                Style);
6550   verifyFormat("SomeClass::Constructor() noexcept :\n"
6551                "    a(a) {}",
6552                Style);
6553   verifyFormat("SomeClass::Constructor() :\n"
6554                "    a(a), b(b), c(c) {}",
6555                Style);
6556   verifyFormat("SomeClass::Constructor() :\n"
6557                "    a(a) {\n"
6558                "  foo();\n"
6559                "  bar();\n"
6560                "}",
6561                Style);
6562 
6563   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6564   verifyFormat("SomeClass::Constructor() :\n"
6565                "    a(a), b(b), c(c) {\n"
6566                "}",
6567                Style);
6568   verifyFormat("SomeClass::Constructor() :\n"
6569                "    a(a) {\n"
6570                "}",
6571                Style);
6572 
6573   Style.ColumnLimit = 80;
6574   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
6575   Style.ConstructorInitializerIndentWidth = 2;
6576   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
6577   verifyFormat("SomeClass::Constructor() :\n"
6578                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6579                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
6580                Style);
6581 
6582   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
6583   // well
6584   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
6585   verifyFormat(
6586       "class SomeClass\n"
6587       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6588       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6589       Style);
6590   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
6591   verifyFormat(
6592       "class SomeClass\n"
6593       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6594       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6595       Style);
6596   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
6597   verifyFormat(
6598       "class SomeClass :\n"
6599       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6600       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6601       Style);
6602   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
6603   verifyFormat(
6604       "class SomeClass\n"
6605       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6606       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6607       Style);
6608 }
6609 
6610 #ifndef EXPENSIVE_CHECKS
6611 // Expensive checks enables libstdc++ checking which includes validating the
6612 // state of ranges used in std::priority_queue - this blows out the
6613 // runtime/scalability of the function and makes this test unacceptably slow.
6614 TEST_F(FormatTest, MemoizationTests) {
6615   // This breaks if the memoization lookup does not take \c Indent and
6616   // \c LastSpace into account.
6617   verifyFormat(
6618       "extern CFRunLoopTimerRef\n"
6619       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
6620       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
6621       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
6622       "                     CFRunLoopTimerContext *context) {}");
6623 
6624   // Deep nesting somewhat works around our memoization.
6625   verifyFormat(
6626       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6627       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6628       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6629       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6630       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
6631       getLLVMStyleWithColumns(65));
6632   verifyFormat(
6633       "aaaaa(\n"
6634       "    aaaaa,\n"
6635       "    aaaaa(\n"
6636       "        aaaaa,\n"
6637       "        aaaaa(\n"
6638       "            aaaaa,\n"
6639       "            aaaaa(\n"
6640       "                aaaaa,\n"
6641       "                aaaaa(\n"
6642       "                    aaaaa,\n"
6643       "                    aaaaa(\n"
6644       "                        aaaaa,\n"
6645       "                        aaaaa(\n"
6646       "                            aaaaa,\n"
6647       "                            aaaaa(\n"
6648       "                                aaaaa,\n"
6649       "                                aaaaa(\n"
6650       "                                    aaaaa,\n"
6651       "                                    aaaaa(\n"
6652       "                                        aaaaa,\n"
6653       "                                        aaaaa(\n"
6654       "                                            aaaaa,\n"
6655       "                                            aaaaa(\n"
6656       "                                                aaaaa,\n"
6657       "                                                aaaaa))))))))))));",
6658       getLLVMStyleWithColumns(65));
6659   verifyFormat(
6660       "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"
6661       "                                  a),\n"
6662       "                                a),\n"
6663       "                              a),\n"
6664       "                            a),\n"
6665       "                          a),\n"
6666       "                        a),\n"
6667       "                      a),\n"
6668       "                    a),\n"
6669       "                  a),\n"
6670       "                a),\n"
6671       "              a),\n"
6672       "            a),\n"
6673       "          a),\n"
6674       "        a),\n"
6675       "      a),\n"
6676       "    a),\n"
6677       "  a)",
6678       getLLVMStyleWithColumns(65));
6679 
6680   // This test takes VERY long when memoization is broken.
6681   FormatStyle OnePerLine = getLLVMStyle();
6682   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6683   OnePerLine.BinPackParameters = false;
6684   std::string input = "Constructor()\n"
6685                       "    : aaaa(a,\n";
6686   for (unsigned i = 0, e = 80; i != e; ++i) {
6687     input += "           a,\n";
6688   }
6689   input += "           a) {}";
6690   verifyFormat(input, OnePerLine);
6691 }
6692 #endif
6693 
6694 TEST_F(FormatTest, BreaksAsHighAsPossible) {
6695   verifyFormat(
6696       "void f() {\n"
6697       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
6698       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
6699       "    f();\n"
6700       "}");
6701   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
6702                "    Intervals[i - 1].getRange().getLast()) {\n}");
6703 }
6704 
6705 TEST_F(FormatTest, BreaksFunctionDeclarations) {
6706   // Principially, we break function declarations in a certain order:
6707   // 1) break amongst arguments.
6708   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
6709                "                              Cccccccccccccc cccccccccccccc);");
6710   verifyFormat("template <class TemplateIt>\n"
6711                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
6712                "                            TemplateIt *stop) {}");
6713 
6714   // 2) break after return type.
6715   verifyFormat(
6716       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6717       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
6718       getGoogleStyle());
6719 
6720   // 3) break after (.
6721   verifyFormat(
6722       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
6723       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
6724       getGoogleStyle());
6725 
6726   // 4) break before after nested name specifiers.
6727   verifyFormat(
6728       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6729       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
6730       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
6731       getGoogleStyle());
6732 
6733   // However, there are exceptions, if a sufficient amount of lines can be
6734   // saved.
6735   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
6736   // more adjusting.
6737   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6738                "                                  Cccccccccccccc cccccccccc,\n"
6739                "                                  Cccccccccccccc cccccccccc,\n"
6740                "                                  Cccccccccccccc cccccccccc,\n"
6741                "                                  Cccccccccccccc cccccccccc);");
6742   verifyFormat(
6743       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6744       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6745       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6746       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
6747       getGoogleStyle());
6748   verifyFormat(
6749       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6750       "                                          Cccccccccccccc cccccccccc,\n"
6751       "                                          Cccccccccccccc cccccccccc,\n"
6752       "                                          Cccccccccccccc cccccccccc,\n"
6753       "                                          Cccccccccccccc cccccccccc,\n"
6754       "                                          Cccccccccccccc cccccccccc,\n"
6755       "                                          Cccccccccccccc cccccccccc);");
6756   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6757                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6758                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6759                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6760                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
6761 
6762   // Break after multi-line parameters.
6763   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6764                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6765                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6766                "    bbbb bbbb);");
6767   verifyFormat("void SomeLoooooooooooongFunction(\n"
6768                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6769                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6770                "    int bbbbbbbbbbbbb);");
6771 
6772   // Treat overloaded operators like other functions.
6773   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6774                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
6775   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6776                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
6777   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6778                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
6779   verifyGoogleFormat(
6780       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
6781       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6782   verifyGoogleFormat(
6783       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
6784       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6785   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6786                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6787   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
6788                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6789   verifyGoogleFormat(
6790       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
6791       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6792       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
6793   verifyGoogleFormat("template <typename T>\n"
6794                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6795                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
6796                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
6797 
6798   FormatStyle Style = getLLVMStyle();
6799   Style.PointerAlignment = FormatStyle::PAS_Left;
6800   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6801                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
6802                Style);
6803   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
6804                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6805                Style);
6806 }
6807 
6808 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
6809   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
6810   // Prefer keeping `::` followed by `operator` together.
6811   EXPECT_EQ("const aaaa::bbbbbbb &\n"
6812             "ccccccccc::operator++() {\n"
6813             "  stuff();\n"
6814             "}",
6815             format("const aaaa::bbbbbbb\n"
6816                    "&ccccccccc::operator++() { stuff(); }",
6817                    getLLVMStyleWithColumns(40)));
6818 }
6819 
6820 TEST_F(FormatTest, TrailingReturnType) {
6821   verifyFormat("auto foo() -> int;\n");
6822   // correct trailing return type spacing
6823   verifyFormat("auto operator->() -> int;\n");
6824   verifyFormat("auto operator++(int) -> int;\n");
6825 
6826   verifyFormat("struct S {\n"
6827                "  auto bar() const -> int;\n"
6828                "};");
6829   verifyFormat("template <size_t Order, typename T>\n"
6830                "auto load_img(const std::string &filename)\n"
6831                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
6832   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
6833                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
6834   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
6835   verifyFormat("template <typename T>\n"
6836                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
6837                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
6838 
6839   // Not trailing return types.
6840   verifyFormat("void f() { auto a = b->c(); }");
6841   verifyFormat("auto a = p->foo();");
6842   verifyFormat("int a = p->foo();");
6843   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
6844 }
6845 
6846 TEST_F(FormatTest, DeductionGuides) {
6847   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
6848   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
6849   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
6850   verifyFormat(
6851       "template <class... T>\n"
6852       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
6853   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
6854   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
6855   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
6856   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
6857   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
6858   verifyFormat("template <class T> x() -> x<1>;");
6859   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
6860 
6861   // Ensure not deduction guides.
6862   verifyFormat("c()->f<int>();");
6863   verifyFormat("x()->foo<1>;");
6864   verifyFormat("x = p->foo<3>();");
6865   verifyFormat("x()->x<1>();");
6866   verifyFormat("x()->x<1>;");
6867 }
6868 
6869 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
6870   // Avoid breaking before trailing 'const' or other trailing annotations, if
6871   // they are not function-like.
6872   FormatStyle Style = getGoogleStyle();
6873   Style.ColumnLimit = 47;
6874   verifyFormat("void someLongFunction(\n"
6875                "    int someLoooooooooooooongParameter) const {\n}",
6876                getLLVMStyleWithColumns(47));
6877   verifyFormat("LoooooongReturnType\n"
6878                "someLoooooooongFunction() const {}",
6879                getLLVMStyleWithColumns(47));
6880   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
6881                "    const {}",
6882                Style);
6883   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6884                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
6885   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6886                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
6887   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6888                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
6889   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
6890                "                   aaaaaaaaaaa aaaaa) const override;");
6891   verifyGoogleFormat(
6892       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6893       "    const override;");
6894 
6895   // Even if the first parameter has to be wrapped.
6896   verifyFormat("void someLongFunction(\n"
6897                "    int someLongParameter) const {}",
6898                getLLVMStyleWithColumns(46));
6899   verifyFormat("void someLongFunction(\n"
6900                "    int someLongParameter) const {}",
6901                Style);
6902   verifyFormat("void someLongFunction(\n"
6903                "    int someLongParameter) override {}",
6904                Style);
6905   verifyFormat("void someLongFunction(\n"
6906                "    int someLongParameter) OVERRIDE {}",
6907                Style);
6908   verifyFormat("void someLongFunction(\n"
6909                "    int someLongParameter) final {}",
6910                Style);
6911   verifyFormat("void someLongFunction(\n"
6912                "    int someLongParameter) FINAL {}",
6913                Style);
6914   verifyFormat("void someLongFunction(\n"
6915                "    int parameter) const override {}",
6916                Style);
6917 
6918   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
6919   verifyFormat("void someLongFunction(\n"
6920                "    int someLongParameter) const\n"
6921                "{\n"
6922                "}",
6923                Style);
6924 
6925   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
6926   verifyFormat("void someLongFunction(\n"
6927                "    int someLongParameter) const\n"
6928                "  {\n"
6929                "  }",
6930                Style);
6931 
6932   // Unless these are unknown annotations.
6933   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
6934                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6935                "    LONG_AND_UGLY_ANNOTATION;");
6936 
6937   // Breaking before function-like trailing annotations is fine to keep them
6938   // close to their arguments.
6939   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6940                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
6941   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
6942                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
6943   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
6944                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
6945   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
6946                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
6947   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
6948 
6949   verifyFormat(
6950       "void aaaaaaaaaaaaaaaaaa()\n"
6951       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
6952       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
6953   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6954                "    __attribute__((unused));");
6955   verifyGoogleFormat(
6956       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6957       "    GUARDED_BY(aaaaaaaaaaaa);");
6958   verifyGoogleFormat(
6959       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6960       "    GUARDED_BY(aaaaaaaaaaaa);");
6961   verifyGoogleFormat(
6962       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6963       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6964   verifyGoogleFormat(
6965       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6966       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
6967 }
6968 
6969 TEST_F(FormatTest, FunctionAnnotations) {
6970   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6971                "int OldFunction(const string &parameter) {}");
6972   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6973                "string OldFunction(const string &parameter) {}");
6974   verifyFormat("template <typename T>\n"
6975                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6976                "string OldFunction(const string &parameter) {}");
6977 
6978   // Not function annotations.
6979   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6980                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
6981   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
6982                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
6983   verifyFormat("MACRO(abc).function() // wrap\n"
6984                "    << abc;");
6985   verifyFormat("MACRO(abc)->function() // wrap\n"
6986                "    << abc;");
6987   verifyFormat("MACRO(abc)::function() // wrap\n"
6988                "    << abc;");
6989 }
6990 
6991 TEST_F(FormatTest, BreaksDesireably) {
6992   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6993                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6994                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
6995   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6996                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
6997                "}");
6998 
6999   verifyFormat(
7000       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7001       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7002 
7003   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7004                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7005                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7006 
7007   verifyFormat(
7008       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7009       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7010       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7011       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7012       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7013 
7014   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7015                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7016 
7017   verifyFormat(
7018       "void f() {\n"
7019       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7020       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7021       "}");
7022   verifyFormat(
7023       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7024       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7025   verifyFormat(
7026       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7027       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7028   verifyFormat(
7029       "aaaaaa(aaa,\n"
7030       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7031       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7032       "       aaaa);");
7033   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7034                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7035                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7036 
7037   // Indent consistently independent of call expression and unary operator.
7038   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7039                "    dddddddddddddddddddddddddddddd));");
7040   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7041                "    dddddddddddddddddddddddddddddd));");
7042   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7043                "    dddddddddddddddddddddddddddddd));");
7044 
7045   // This test case breaks on an incorrect memoization, i.e. an optimization not
7046   // taking into account the StopAt value.
7047   verifyFormat(
7048       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7049       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7050       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7051       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7052 
7053   verifyFormat("{\n  {\n    {\n"
7054                "      Annotation.SpaceRequiredBefore =\n"
7055                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7056                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7057                "    }\n  }\n}");
7058 
7059   // Break on an outer level if there was a break on an inner level.
7060   EXPECT_EQ("f(g(h(a, // comment\n"
7061             "      b, c),\n"
7062             "    d, e),\n"
7063             "  x, y);",
7064             format("f(g(h(a, // comment\n"
7065                    "    b, c), d, e), x, y);"));
7066 
7067   // Prefer breaking similar line breaks.
7068   verifyFormat(
7069       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7070       "                             NSTrackingMouseEnteredAndExited |\n"
7071       "                             NSTrackingActiveAlways;");
7072 }
7073 
7074 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7075   FormatStyle NoBinPacking = getGoogleStyle();
7076   NoBinPacking.BinPackParameters = false;
7077   NoBinPacking.BinPackArguments = true;
7078   verifyFormat("void f() {\n"
7079                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7080                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7081                "}",
7082                NoBinPacking);
7083   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7084                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7085                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7086                NoBinPacking);
7087 
7088   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7089   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7090                "                        vector<int> bbbbbbbbbbbbbbb);",
7091                NoBinPacking);
7092   // FIXME: This behavior difference is probably not wanted. However, currently
7093   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7094   // template arguments from BreakBeforeParameter being set because of the
7095   // one-per-line formatting.
7096   verifyFormat(
7097       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7098       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7099       NoBinPacking);
7100   verifyFormat(
7101       "void fffffffffff(\n"
7102       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7103       "        aaaaaaaaaa);");
7104 }
7105 
7106 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7107   FormatStyle NoBinPacking = getGoogleStyle();
7108   NoBinPacking.BinPackParameters = false;
7109   NoBinPacking.BinPackArguments = false;
7110   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7111                "  aaaaaaaaaaaaaaaaaaaa,\n"
7112                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7113                NoBinPacking);
7114   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7115                "        aaaaaaaaaaaaa,\n"
7116                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7117                NoBinPacking);
7118   verifyFormat(
7119       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7120       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7121       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7122       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7123       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7124       NoBinPacking);
7125   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7126                "    .aaaaaaaaaaaaaaaaaa();",
7127                NoBinPacking);
7128   verifyFormat("void f() {\n"
7129                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7130                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7131                "}",
7132                NoBinPacking);
7133 
7134   verifyFormat(
7135       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7136       "             aaaaaaaaaaaa,\n"
7137       "             aaaaaaaaaaaa);",
7138       NoBinPacking);
7139   verifyFormat(
7140       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7141       "                               ddddddddddddddddddddddddddddd),\n"
7142       "             test);",
7143       NoBinPacking);
7144 
7145   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7146                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7147                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7148                "    aaaaaaaaaaaaaaaaaa;",
7149                NoBinPacking);
7150   verifyFormat("a(\"a\"\n"
7151                "  \"a\",\n"
7152                "  a);");
7153 
7154   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7155   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7156                "                aaaaaaaaa,\n"
7157                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7158                NoBinPacking);
7159   verifyFormat(
7160       "void f() {\n"
7161       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7162       "      .aaaaaaa();\n"
7163       "}",
7164       NoBinPacking);
7165   verifyFormat(
7166       "template <class SomeType, class SomeOtherType>\n"
7167       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7168       NoBinPacking);
7169 }
7170 
7171 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7172   FormatStyle Style = getLLVMStyleWithColumns(15);
7173   Style.ExperimentalAutoDetectBinPacking = true;
7174   EXPECT_EQ("aaa(aaaa,\n"
7175             "    aaaa,\n"
7176             "    aaaa);\n"
7177             "aaa(aaaa,\n"
7178             "    aaaa,\n"
7179             "    aaaa);",
7180             format("aaa(aaaa,\n" // one-per-line
7181                    "  aaaa,\n"
7182                    "    aaaa  );\n"
7183                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7184                    Style));
7185   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7186             "    aaaa);\n"
7187             "aaa(aaaa, aaaa,\n"
7188             "    aaaa);",
7189             format("aaa(aaaa,  aaaa,\n" // bin-packed
7190                    "    aaaa  );\n"
7191                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7192                    Style));
7193 }
7194 
7195 TEST_F(FormatTest, FormatsBuilderPattern) {
7196   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7197                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7198                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7199                "    .StartsWith(\".init\", ORDER_INIT)\n"
7200                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7201                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7202                "    .Default(ORDER_TEXT);\n");
7203 
7204   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7205                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7206   verifyFormat("aaaaaaa->aaaaaaa\n"
7207                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7208                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7209                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7210   verifyFormat(
7211       "aaaaaaa->aaaaaaa\n"
7212       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7213       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7214   verifyFormat(
7215       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7216       "    aaaaaaaaaaaaaa);");
7217   verifyFormat(
7218       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7219       "    aaaaaa->aaaaaaaaaaaa()\n"
7220       "        ->aaaaaaaaaaaaaaaa(\n"
7221       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7222       "        ->aaaaaaaaaaaaaaaaa();");
7223   verifyGoogleFormat(
7224       "void f() {\n"
7225       "  someo->Add((new util::filetools::Handler(dir))\n"
7226       "                 ->OnEvent1(NewPermanentCallback(\n"
7227       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7228       "                 ->OnEvent2(NewPermanentCallback(\n"
7229       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7230       "                 ->OnEvent3(NewPermanentCallback(\n"
7231       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7232       "                 ->OnEvent5(NewPermanentCallback(\n"
7233       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7234       "                 ->OnEvent6(NewPermanentCallback(\n"
7235       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7236       "}");
7237 
7238   verifyFormat(
7239       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7240   verifyFormat("aaaaaaaaaaaaaaa()\n"
7241                "    .aaaaaaaaaaaaaaa()\n"
7242                "    .aaaaaaaaaaaaaaa()\n"
7243                "    .aaaaaaaaaaaaaaa()\n"
7244                "    .aaaaaaaaaaaaaaa();");
7245   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7246                "    .aaaaaaaaaaaaaaa()\n"
7247                "    .aaaaaaaaaaaaaaa()\n"
7248                "    .aaaaaaaaaaaaaaa();");
7249   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7250                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7251                "    .aaaaaaaaaaaaaaa();");
7252   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7253                "    ->aaaaaaaaaaaaaae(0)\n"
7254                "    ->aaaaaaaaaaaaaaa();");
7255 
7256   // Don't linewrap after very short segments.
7257   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7258                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7259                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7260   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7261                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7262                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7263   verifyFormat("aaa()\n"
7264                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7265                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7266                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7267 
7268   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7269                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7270                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7271   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7272                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7273                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7274 
7275   // Prefer not to break after empty parentheses.
7276   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7277                "    First->LastNewlineOffset);");
7278 
7279   // Prefer not to create "hanging" indents.
7280   verifyFormat(
7281       "return !soooooooooooooome_map\n"
7282       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7283       "            .second;");
7284   verifyFormat(
7285       "return aaaaaaaaaaaaaaaa\n"
7286       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7287       "    .aaaa(aaaaaaaaaaaaaa);");
7288   // No hanging indent here.
7289   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7290                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7291   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7292                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7293   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7294                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7295                getLLVMStyleWithColumns(60));
7296   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7297                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7298                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7299                getLLVMStyleWithColumns(59));
7300   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7301                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7302                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7303 
7304   // Dont break if only closing statements before member call
7305   verifyFormat("test() {\n"
7306                "  ([]() -> {\n"
7307                "    int b = 32;\n"
7308                "    return 3;\n"
7309                "  }).foo();\n"
7310                "}");
7311   verifyFormat("test() {\n"
7312                "  (\n"
7313                "      []() -> {\n"
7314                "        int b = 32;\n"
7315                "        return 3;\n"
7316                "      },\n"
7317                "      foo, bar)\n"
7318                "      .foo();\n"
7319                "}");
7320   verifyFormat("test() {\n"
7321                "  ([]() -> {\n"
7322                "    int b = 32;\n"
7323                "    return 3;\n"
7324                "  })\n"
7325                "      .foo()\n"
7326                "      .bar();\n"
7327                "}");
7328   verifyFormat("test() {\n"
7329                "  ([]() -> {\n"
7330                "    int b = 32;\n"
7331                "    return 3;\n"
7332                "  })\n"
7333                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7334                "           \"bbbb\");\n"
7335                "}",
7336                getLLVMStyleWithColumns(30));
7337 }
7338 
7339 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7340   verifyFormat(
7341       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7342       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7343   verifyFormat(
7344       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7345       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7346 
7347   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7348                "    ccccccccccccccccccccccccc) {\n}");
7349   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7350                "    ccccccccccccccccccccccccc) {\n}");
7351 
7352   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7353                "    ccccccccccccccccccccccccc) {\n}");
7354   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7355                "    ccccccccccccccccccccccccc) {\n}");
7356 
7357   verifyFormat(
7358       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7359       "    ccccccccccccccccccccccccc) {\n}");
7360   verifyFormat(
7361       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7362       "    ccccccccccccccccccccccccc) {\n}");
7363 
7364   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7365                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7366                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7367                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7368   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7369                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7370                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7371                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7372 
7373   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7374                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7375                "    aaaaaaaaaaaaaaa != aa) {\n}");
7376   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7377                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7378                "    aaaaaaaaaaaaaaa != aa) {\n}");
7379 }
7380 
7381 TEST_F(FormatTest, BreaksAfterAssignments) {
7382   verifyFormat(
7383       "unsigned Cost =\n"
7384       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7385       "                        SI->getPointerAddressSpaceee());\n");
7386   verifyFormat(
7387       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7388       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7389 
7390   verifyFormat(
7391       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7392       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7393   verifyFormat("unsigned OriginalStartColumn =\n"
7394                "    SourceMgr.getSpellingColumnNumber(\n"
7395                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7396                "    1;");
7397 }
7398 
7399 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7400   FormatStyle Style = getLLVMStyle();
7401   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7402                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7403                Style);
7404 
7405   Style.PenaltyBreakAssignment = 20;
7406   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7407                "                                 cccccccccccccccccccccccccc;",
7408                Style);
7409 }
7410 
7411 TEST_F(FormatTest, AlignsAfterAssignments) {
7412   verifyFormat(
7413       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7414       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7415   verifyFormat(
7416       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7417       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7418   verifyFormat(
7419       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7420       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7421   verifyFormat(
7422       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7423       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7424   verifyFormat(
7425       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7426       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7427       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7428 }
7429 
7430 TEST_F(FormatTest, AlignsAfterReturn) {
7431   verifyFormat(
7432       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7433       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7434   verifyFormat(
7435       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7436       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7437   verifyFormat(
7438       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7439       "       aaaaaaaaaaaaaaaaaaaaaa();");
7440   verifyFormat(
7441       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7442       "        aaaaaaaaaaaaaaaaaaaaaa());");
7443   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7444                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7445   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7446                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7447                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7448   verifyFormat("return\n"
7449                "    // true if code is one of a or b.\n"
7450                "    code == a || code == b;");
7451 }
7452 
7453 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7454   verifyFormat(
7455       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7456       "                                                aaaaaaaaa aaaaaaa) {}");
7457   verifyFormat(
7458       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7459       "                                               aaaaaaaaaaa aaaaaaaaa);");
7460   verifyFormat(
7461       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7462       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7463   FormatStyle Style = getLLVMStyle();
7464   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7465   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7466                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7467                Style);
7468   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7469                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
7470                Style);
7471   verifyFormat("SomeLongVariableName->someFunction(\n"
7472                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
7473                Style);
7474   verifyFormat(
7475       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7476       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7477       Style);
7478   verifyFormat(
7479       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7480       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7481       Style);
7482   verifyFormat(
7483       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7484       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7485       Style);
7486 
7487   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
7488                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
7489                "        b));",
7490                Style);
7491 
7492   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7493   Style.BinPackArguments = false;
7494   Style.BinPackParameters = false;
7495   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7496                "    aaaaaaaaaaa aaaaaaaa,\n"
7497                "    aaaaaaaaa aaaaaaa,\n"
7498                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7499                Style);
7500   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7501                "    aaaaaaaaaaa aaaaaaaaa,\n"
7502                "    aaaaaaaaaaa aaaaaaaaa,\n"
7503                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7504                Style);
7505   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
7506                "    aaaaaaaaaaaaaaa,\n"
7507                "    aaaaaaaaaaaaaaaaaaaaa,\n"
7508                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7509                Style);
7510   verifyFormat(
7511       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
7512       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7513       Style);
7514   verifyFormat(
7515       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
7516       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7517       Style);
7518   verifyFormat(
7519       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7520       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7521       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
7522       "    aaaaaaaaaaaaaaaa);",
7523       Style);
7524   verifyFormat(
7525       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7526       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7527       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
7528       "    aaaaaaaaaaaaaaaa);",
7529       Style);
7530 }
7531 
7532 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
7533   FormatStyle Style = getLLVMStyleWithColumns(40);
7534   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7535                "          bbbbbbbbbbbbbbbbbbbbbb);",
7536                Style);
7537   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7538   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7539   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7540                "          bbbbbbbbbbbbbbbbbbbbbb);",
7541                Style);
7542   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7543   Style.AlignOperands = FormatStyle::OAS_Align;
7544   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7545                "          bbbbbbbbbbbbbbbbbbbbbb);",
7546                Style);
7547   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7548   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7549   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7550                "    bbbbbbbbbbbbbbbbbbbbbb);",
7551                Style);
7552 }
7553 
7554 TEST_F(FormatTest, BreaksConditionalExpressions) {
7555   verifyFormat(
7556       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7557       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7558       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7559   verifyFormat(
7560       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7561       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7562       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7563   verifyFormat(
7564       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7565       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7566   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
7567                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7568                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7569   verifyFormat(
7570       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
7571       "                                                    : aaaaaaaaaaaaa);");
7572   verifyFormat(
7573       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7574       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7575       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7576       "                   aaaaaaaaaaaaa);");
7577   verifyFormat(
7578       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7579       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7580       "                   aaaaaaaaaaaaa);");
7581   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7582                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7583                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7584                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7585                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7586   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7587                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7588                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7589                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7590                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7591                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7592                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7593   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7594                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7595                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7596                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7597                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7598   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7599                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7600                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7601   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7602                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7603                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7604                "        : aaaaaaaaaaaaaaaa;");
7605   verifyFormat(
7606       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7607       "    ? aaaaaaaaaaaaaaa\n"
7608       "    : aaaaaaaaaaaaaaa;");
7609   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7610                "          aaaaaaaaa\n"
7611                "      ? b\n"
7612                "      : c);");
7613   verifyFormat("return aaaa == bbbb\n"
7614                "           // comment\n"
7615                "           ? aaaa\n"
7616                "           : bbbb;");
7617   verifyFormat("unsigned Indent =\n"
7618                "    format(TheLine.First,\n"
7619                "           IndentForLevel[TheLine.Level] >= 0\n"
7620                "               ? IndentForLevel[TheLine.Level]\n"
7621                "               : TheLine * 2,\n"
7622                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7623                getLLVMStyleWithColumns(60));
7624   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7625                "                  ? aaaaaaaaaaaaaaa\n"
7626                "                  : bbbbbbbbbbbbbbb //\n"
7627                "                        ? ccccccccccccccc\n"
7628                "                        : ddddddddddddddd;");
7629   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7630                "                  ? aaaaaaaaaaaaaaa\n"
7631                "                  : (bbbbbbbbbbbbbbb //\n"
7632                "                         ? ccccccccccccccc\n"
7633                "                         : ddddddddddddddd);");
7634   verifyFormat(
7635       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7636       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7637       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
7638       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
7639       "                                      : aaaaaaaaaa;");
7640   verifyFormat(
7641       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7642       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
7643       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7644 
7645   FormatStyle NoBinPacking = getLLVMStyle();
7646   NoBinPacking.BinPackArguments = false;
7647   verifyFormat(
7648       "void f() {\n"
7649       "  g(aaa,\n"
7650       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7651       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7652       "        ? aaaaaaaaaaaaaaa\n"
7653       "        : aaaaaaaaaaaaaaa);\n"
7654       "}",
7655       NoBinPacking);
7656   verifyFormat(
7657       "void f() {\n"
7658       "  g(aaa,\n"
7659       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7660       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7661       "        ?: aaaaaaaaaaaaaaa);\n"
7662       "}",
7663       NoBinPacking);
7664 
7665   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
7666                "             // comment.\n"
7667                "             ccccccccccccccccccccccccccccccccccccccc\n"
7668                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7669                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
7670 
7671   // Assignments in conditional expressions. Apparently not uncommon :-(.
7672   verifyFormat("return a != b\n"
7673                "           // comment\n"
7674                "           ? a = b\n"
7675                "           : a = b;");
7676   verifyFormat("return a != b\n"
7677                "           // comment\n"
7678                "           ? a = a != b\n"
7679                "                     // comment\n"
7680                "                     ? a = b\n"
7681                "                     : a\n"
7682                "           : a;\n");
7683   verifyFormat("return a != b\n"
7684                "           // comment\n"
7685                "           ? a\n"
7686                "           : a = a != b\n"
7687                "                     // comment\n"
7688                "                     ? a = b\n"
7689                "                     : a;");
7690 
7691   // Chained conditionals
7692   FormatStyle Style = getLLVMStyle();
7693   Style.ColumnLimit = 70;
7694   Style.AlignOperands = FormatStyle::OAS_Align;
7695   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7696                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7697                "                        : 3333333333333333;",
7698                Style);
7699   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7700                "       : bbbbbbbbbb     ? 2222222222222222\n"
7701                "                        : 3333333333333333;",
7702                Style);
7703   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
7704                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
7705                "                          : 3333333333333333;",
7706                Style);
7707   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7708                "       : bbbbbbbbbbbbbb ? 222222\n"
7709                "                        : 333333;",
7710                Style);
7711   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7712                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7713                "       : cccccccccccccc ? 3333333333333333\n"
7714                "                        : 4444444444444444;",
7715                Style);
7716   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
7717                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7718                "                        : 3333333333333333;",
7719                Style);
7720   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7721                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7722                "                        : (aaa ? bbb : ccc);",
7723                Style);
7724   verifyFormat(
7725       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7726       "                                             : cccccccccccccccccc)\n"
7727       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7728       "                        : 3333333333333333;",
7729       Style);
7730   verifyFormat(
7731       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7732       "                                             : cccccccccccccccccc)\n"
7733       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7734       "                        : 3333333333333333;",
7735       Style);
7736   verifyFormat(
7737       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7738       "                                             : dddddddddddddddddd)\n"
7739       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7740       "                        : 3333333333333333;",
7741       Style);
7742   verifyFormat(
7743       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7744       "                                             : dddddddddddddddddd)\n"
7745       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7746       "                        : 3333333333333333;",
7747       Style);
7748   verifyFormat(
7749       "return aaaaaaaaa        ? 1111111111111111\n"
7750       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7751       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7752       "                                             : dddddddddddddddddd)\n",
7753       Style);
7754   verifyFormat(
7755       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7756       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7757       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7758       "                                             : cccccccccccccccccc);",
7759       Style);
7760   verifyFormat(
7761       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7762       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7763       "                                             : eeeeeeeeeeeeeeeeee)\n"
7764       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7765       "                        : 3333333333333333;",
7766       Style);
7767   verifyFormat(
7768       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
7769       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7770       "                                             : eeeeeeeeeeeeeeeeee)\n"
7771       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7772       "                        : 3333333333333333;",
7773       Style);
7774   verifyFormat(
7775       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7776       "                           : cccccccccccc    ? dddddddddddddddddd\n"
7777       "                                             : eeeeeeeeeeeeeeeeee)\n"
7778       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7779       "                        : 3333333333333333;",
7780       Style);
7781   verifyFormat(
7782       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7783       "                                             : cccccccccccccccccc\n"
7784       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7785       "                        : 3333333333333333;",
7786       Style);
7787   verifyFormat(
7788       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7789       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
7790       "                                             : eeeeeeeeeeeeeeeeee\n"
7791       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7792       "                        : 3333333333333333;",
7793       Style);
7794   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
7795                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
7796                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
7797                "                                   : eeeeeeeeeeeeeeeeee)\n"
7798                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7799                "                             : 3333333333333333;",
7800                Style);
7801   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
7802                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7803                "             : cccccccccccccccc ? dddddddddddddddddd\n"
7804                "                                : eeeeeeeeeeeeeeeeee\n"
7805                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7806                "                                 : 3333333333333333;",
7807                Style);
7808 
7809   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7810   Style.BreakBeforeTernaryOperators = false;
7811   // FIXME: Aligning the question marks is weird given DontAlign.
7812   // Consider disabling this alignment in this case. Also check whether this
7813   // will render the adjustment from https://reviews.llvm.org/D82199
7814   // unnecessary.
7815   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
7816                "    bbbb                ? cccccccccccccccccc :\n"
7817                "                          ddddd;\n",
7818                Style);
7819 
7820   EXPECT_EQ(
7821       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7822       "    /*\n"
7823       "     */\n"
7824       "    function() {\n"
7825       "      try {\n"
7826       "        return JJJJJJJJJJJJJJ(\n"
7827       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7828       "      }\n"
7829       "    } :\n"
7830       "    function() {};",
7831       format(
7832           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7833           "     /*\n"
7834           "      */\n"
7835           "     function() {\n"
7836           "      try {\n"
7837           "        return JJJJJJJJJJJJJJ(\n"
7838           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7839           "      }\n"
7840           "    } :\n"
7841           "    function() {};",
7842           getGoogleStyle(FormatStyle::LK_JavaScript)));
7843 }
7844 
7845 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
7846   FormatStyle Style = getLLVMStyle();
7847   Style.BreakBeforeTernaryOperators = false;
7848   Style.ColumnLimit = 70;
7849   verifyFormat(
7850       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7851       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7852       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7853       Style);
7854   verifyFormat(
7855       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7856       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7857       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7858       Style);
7859   verifyFormat(
7860       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7861       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7862       Style);
7863   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
7864                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7865                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7866                Style);
7867   verifyFormat(
7868       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
7869       "                                                      aaaaaaaaaaaaa);",
7870       Style);
7871   verifyFormat(
7872       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7873       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7874       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7875       "                   aaaaaaaaaaaaa);",
7876       Style);
7877   verifyFormat(
7878       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7879       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7880       "                   aaaaaaaaaaaaa);",
7881       Style);
7882   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7883                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7884                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7885                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7886                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7887                Style);
7888   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7889                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7890                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7891                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7892                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7893                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7894                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7895                Style);
7896   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7897                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
7898                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7899                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7900                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7901                Style);
7902   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7903                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7904                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7905                Style);
7906   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7907                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7908                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7909                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7910                Style);
7911   verifyFormat(
7912       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7913       "    aaaaaaaaaaaaaaa :\n"
7914       "    aaaaaaaaaaaaaaa;",
7915       Style);
7916   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7917                "          aaaaaaaaa ?\n"
7918                "      b :\n"
7919                "      c);",
7920                Style);
7921   verifyFormat("unsigned Indent =\n"
7922                "    format(TheLine.First,\n"
7923                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
7924                "               IndentForLevel[TheLine.Level] :\n"
7925                "               TheLine * 2,\n"
7926                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7927                Style);
7928   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
7929                "                  aaaaaaaaaaaaaaa :\n"
7930                "                  bbbbbbbbbbbbbbb ? //\n"
7931                "                      ccccccccccccccc :\n"
7932                "                      ddddddddddddddd;",
7933                Style);
7934   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
7935                "                  aaaaaaaaaaaaaaa :\n"
7936                "                  (bbbbbbbbbbbbbbb ? //\n"
7937                "                       ccccccccccccccc :\n"
7938                "                       ddddddddddddddd);",
7939                Style);
7940   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7941                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
7942                "            ccccccccccccccccccccccccccc;",
7943                Style);
7944   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7945                "           aaaaa :\n"
7946                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
7947                Style);
7948 
7949   // Chained conditionals
7950   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7951                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7952                "                          3333333333333333;",
7953                Style);
7954   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7955                "       bbbbbbbbbb       ? 2222222222222222 :\n"
7956                "                          3333333333333333;",
7957                Style);
7958   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
7959                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7960                "                          3333333333333333;",
7961                Style);
7962   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7963                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
7964                "                          333333;",
7965                Style);
7966   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7967                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7968                "       cccccccccccccccc ? 3333333333333333 :\n"
7969                "                          4444444444444444;",
7970                Style);
7971   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
7972                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7973                "                          3333333333333333;",
7974                Style);
7975   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7976                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7977                "                          (aaa ? bbb : ccc);",
7978                Style);
7979   verifyFormat(
7980       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7981       "                                               cccccccccccccccccc) :\n"
7982       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7983       "                          3333333333333333;",
7984       Style);
7985   verifyFormat(
7986       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7987       "                                               cccccccccccccccccc) :\n"
7988       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7989       "                          3333333333333333;",
7990       Style);
7991   verifyFormat(
7992       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7993       "                                               dddddddddddddddddd) :\n"
7994       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7995       "                          3333333333333333;",
7996       Style);
7997   verifyFormat(
7998       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7999       "                                               dddddddddddddddddd) :\n"
8000       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8001       "                          3333333333333333;",
8002       Style);
8003   verifyFormat(
8004       "return aaaaaaaaa        ? 1111111111111111 :\n"
8005       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8006       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8007       "                                               dddddddddddddddddd)\n",
8008       Style);
8009   verifyFormat(
8010       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8011       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8012       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8013       "                                               cccccccccccccccccc);",
8014       Style);
8015   verifyFormat(
8016       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8017       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8018       "                                               eeeeeeeeeeeeeeeeee) :\n"
8019       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8020       "                          3333333333333333;",
8021       Style);
8022   verifyFormat(
8023       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8024       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8025       "                                               eeeeeeeeeeeeeeeeee) :\n"
8026       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8027       "                          3333333333333333;",
8028       Style);
8029   verifyFormat(
8030       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8031       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8032       "                                               eeeeeeeeeeeeeeeeee) :\n"
8033       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8034       "                          3333333333333333;",
8035       Style);
8036   verifyFormat(
8037       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8038       "                                               cccccccccccccccccc :\n"
8039       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8040       "                          3333333333333333;",
8041       Style);
8042   verifyFormat(
8043       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8044       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8045       "                                               eeeeeeeeeeeeeeeeee :\n"
8046       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8047       "                          3333333333333333;",
8048       Style);
8049   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8050                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8051                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8052                "                                 eeeeeeeeeeeeeeeeee) :\n"
8053                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8054                "                               3333333333333333;",
8055                Style);
8056   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8057                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8058                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8059                "                                  eeeeeeeeeeeeeeeeee :\n"
8060                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8061                "                               3333333333333333;",
8062                Style);
8063 }
8064 
8065 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8066   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8067                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8068   verifyFormat("bool a = true, b = false;");
8069 
8070   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8071                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8072                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8073                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8074   verifyFormat(
8075       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8076       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8077       "     d = e && f;");
8078   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8079                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8080   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8081                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8082   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8083                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8084 
8085   FormatStyle Style = getGoogleStyle();
8086   Style.PointerAlignment = FormatStyle::PAS_Left;
8087   Style.DerivePointerAlignment = false;
8088   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8089                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8090                "    *b = bbbbbbbbbbbbbbbbbbb;",
8091                Style);
8092   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8093                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8094                Style);
8095   verifyFormat("vector<int*> a, b;", Style);
8096   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8097 }
8098 
8099 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8100   verifyFormat("arr[foo ? bar : baz];");
8101   verifyFormat("f()[foo ? bar : baz];");
8102   verifyFormat("(a + b)[foo ? bar : baz];");
8103   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8104 }
8105 
8106 TEST_F(FormatTest, AlignsStringLiterals) {
8107   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8108                "                                      \"short literal\");");
8109   verifyFormat(
8110       "looooooooooooooooooooooooongFunction(\n"
8111       "    \"short literal\"\n"
8112       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8113   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8114                "             \" string literals\",\n"
8115                "             and, other, parameters);");
8116   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8117             "      \"5678\";",
8118             format("fun + \"1243\" /* comment */\n"
8119                    "    \"5678\";",
8120                    getLLVMStyleWithColumns(28)));
8121   EXPECT_EQ(
8122       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8123       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8124       "         \"aaaaaaaaaaaaaaaa\";",
8125       format("aaaaaa ="
8126              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8127              "aaaaaaaaaaaaaaaaaaaaa\" "
8128              "\"aaaaaaaaaaaaaaaa\";"));
8129   verifyFormat("a = a + \"a\"\n"
8130                "        \"a\"\n"
8131                "        \"a\";");
8132   verifyFormat("f(\"a\", \"b\"\n"
8133                "       \"c\");");
8134 
8135   verifyFormat(
8136       "#define LL_FORMAT \"ll\"\n"
8137       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8138       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8139 
8140   verifyFormat("#define A(X)          \\\n"
8141                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8142                "  \"ccccc\"",
8143                getLLVMStyleWithColumns(23));
8144   verifyFormat("#define A \"def\"\n"
8145                "f(\"abc\" A \"ghi\"\n"
8146                "  \"jkl\");");
8147 
8148   verifyFormat("f(L\"a\"\n"
8149                "  L\"b\");");
8150   verifyFormat("#define A(X)            \\\n"
8151                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8152                "  L\"ccccc\"",
8153                getLLVMStyleWithColumns(25));
8154 
8155   verifyFormat("f(@\"a\"\n"
8156                "  @\"b\");");
8157   verifyFormat("NSString s = @\"a\"\n"
8158                "             @\"b\"\n"
8159                "             @\"c\";");
8160   verifyFormat("NSString s = @\"a\"\n"
8161                "              \"b\"\n"
8162                "              \"c\";");
8163 }
8164 
8165 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8166   FormatStyle Style = getLLVMStyle();
8167   // No declarations or definitions should be moved to own line.
8168   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8169   verifyFormat("class A {\n"
8170                "  int f() { return 1; }\n"
8171                "  int g();\n"
8172                "};\n"
8173                "int f() { return 1; }\n"
8174                "int g();\n",
8175                Style);
8176 
8177   // All declarations and definitions should have the return type moved to its
8178   // own line.
8179   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8180   Style.TypenameMacros = {"LIST"};
8181   verifyFormat("SomeType\n"
8182                "funcdecl(LIST(uint64_t));",
8183                Style);
8184   verifyFormat("class E {\n"
8185                "  int\n"
8186                "  f() {\n"
8187                "    return 1;\n"
8188                "  }\n"
8189                "  int\n"
8190                "  g();\n"
8191                "};\n"
8192                "int\n"
8193                "f() {\n"
8194                "  return 1;\n"
8195                "}\n"
8196                "int\n"
8197                "g();\n",
8198                Style);
8199 
8200   // Top-level definitions, and no kinds of declarations should have the
8201   // return type moved to its own line.
8202   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8203   verifyFormat("class B {\n"
8204                "  int f() { return 1; }\n"
8205                "  int g();\n"
8206                "};\n"
8207                "int\n"
8208                "f() {\n"
8209                "  return 1;\n"
8210                "}\n"
8211                "int g();\n",
8212                Style);
8213 
8214   // Top-level definitions and declarations should have the return type moved
8215   // to its own line.
8216   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8217   verifyFormat("class C {\n"
8218                "  int f() { return 1; }\n"
8219                "  int g();\n"
8220                "};\n"
8221                "int\n"
8222                "f() {\n"
8223                "  return 1;\n"
8224                "}\n"
8225                "int\n"
8226                "g();\n",
8227                Style);
8228 
8229   // All definitions should have the return type moved to its own line, but no
8230   // kinds of declarations.
8231   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8232   verifyFormat("class D {\n"
8233                "  int\n"
8234                "  f() {\n"
8235                "    return 1;\n"
8236                "  }\n"
8237                "  int g();\n"
8238                "};\n"
8239                "int\n"
8240                "f() {\n"
8241                "  return 1;\n"
8242                "}\n"
8243                "int g();\n",
8244                Style);
8245   verifyFormat("const char *\n"
8246                "f(void) {\n" // Break here.
8247                "  return \"\";\n"
8248                "}\n"
8249                "const char *bar(void);\n", // No break here.
8250                Style);
8251   verifyFormat("template <class T>\n"
8252                "T *\n"
8253                "f(T &c) {\n" // Break here.
8254                "  return NULL;\n"
8255                "}\n"
8256                "template <class T> T *f(T &c);\n", // No break here.
8257                Style);
8258   verifyFormat("class C {\n"
8259                "  int\n"
8260                "  operator+() {\n"
8261                "    return 1;\n"
8262                "  }\n"
8263                "  int\n"
8264                "  operator()() {\n"
8265                "    return 1;\n"
8266                "  }\n"
8267                "};\n",
8268                Style);
8269   verifyFormat("void\n"
8270                "A::operator()() {}\n"
8271                "void\n"
8272                "A::operator>>() {}\n"
8273                "void\n"
8274                "A::operator+() {}\n"
8275                "void\n"
8276                "A::operator*() {}\n"
8277                "void\n"
8278                "A::operator->() {}\n"
8279                "void\n"
8280                "A::operator void *() {}\n"
8281                "void\n"
8282                "A::operator void &() {}\n"
8283                "void\n"
8284                "A::operator void &&() {}\n"
8285                "void\n"
8286                "A::operator char *() {}\n"
8287                "void\n"
8288                "A::operator[]() {}\n"
8289                "void\n"
8290                "A::operator!() {}\n"
8291                "void\n"
8292                "A::operator**() {}\n"
8293                "void\n"
8294                "A::operator<Foo> *() {}\n"
8295                "void\n"
8296                "A::operator<Foo> **() {}\n"
8297                "void\n"
8298                "A::operator<Foo> &() {}\n"
8299                "void\n"
8300                "A::operator void **() {}\n",
8301                Style);
8302   verifyFormat("constexpr auto\n"
8303                "operator()() const -> reference {}\n"
8304                "constexpr auto\n"
8305                "operator>>() const -> reference {}\n"
8306                "constexpr auto\n"
8307                "operator+() const -> reference {}\n"
8308                "constexpr auto\n"
8309                "operator*() const -> reference {}\n"
8310                "constexpr auto\n"
8311                "operator->() const -> reference {}\n"
8312                "constexpr auto\n"
8313                "operator++() const -> reference {}\n"
8314                "constexpr auto\n"
8315                "operator void *() const -> reference {}\n"
8316                "constexpr auto\n"
8317                "operator void **() const -> reference {}\n"
8318                "constexpr auto\n"
8319                "operator void *() const -> reference {}\n"
8320                "constexpr auto\n"
8321                "operator void &() const -> reference {}\n"
8322                "constexpr auto\n"
8323                "operator void &&() const -> reference {}\n"
8324                "constexpr auto\n"
8325                "operator char *() const -> reference {}\n"
8326                "constexpr auto\n"
8327                "operator!() const -> reference {}\n"
8328                "constexpr auto\n"
8329                "operator[]() const -> reference {}\n",
8330                Style);
8331   verifyFormat("void *operator new(std::size_t s);", // No break here.
8332                Style);
8333   verifyFormat("void *\n"
8334                "operator new(std::size_t s) {}",
8335                Style);
8336   verifyFormat("void *\n"
8337                "operator delete[](void *ptr) {}",
8338                Style);
8339   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8340   verifyFormat("const char *\n"
8341                "f(void)\n" // Break here.
8342                "{\n"
8343                "  return \"\";\n"
8344                "}\n"
8345                "const char *bar(void);\n", // No break here.
8346                Style);
8347   verifyFormat("template <class T>\n"
8348                "T *\n"     // Problem here: no line break
8349                "f(T &c)\n" // Break here.
8350                "{\n"
8351                "  return NULL;\n"
8352                "}\n"
8353                "template <class T> T *f(T &c);\n", // No break here.
8354                Style);
8355   verifyFormat("int\n"
8356                "foo(A<bool> a)\n"
8357                "{\n"
8358                "  return a;\n"
8359                "}\n",
8360                Style);
8361   verifyFormat("int\n"
8362                "foo(A<8> a)\n"
8363                "{\n"
8364                "  return a;\n"
8365                "}\n",
8366                Style);
8367   verifyFormat("int\n"
8368                "foo(A<B<bool>, 8> a)\n"
8369                "{\n"
8370                "  return a;\n"
8371                "}\n",
8372                Style);
8373   verifyFormat("int\n"
8374                "foo(A<B<8>, bool> a)\n"
8375                "{\n"
8376                "  return a;\n"
8377                "}\n",
8378                Style);
8379   verifyFormat("int\n"
8380                "foo(A<B<bool>, bool> a)\n"
8381                "{\n"
8382                "  return a;\n"
8383                "}\n",
8384                Style);
8385   verifyFormat("int\n"
8386                "foo(A<B<8>, 8> a)\n"
8387                "{\n"
8388                "  return a;\n"
8389                "}\n",
8390                Style);
8391 
8392   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8393   Style.BraceWrapping.AfterFunction = true;
8394   verifyFormat("int f(i);\n" // No break here.
8395                "int\n"       // Break here.
8396                "f(i)\n"
8397                "{\n"
8398                "  return i + 1;\n"
8399                "}\n"
8400                "int\n" // Break here.
8401                "f(i)\n"
8402                "{\n"
8403                "  return i + 1;\n"
8404                "};",
8405                Style);
8406   verifyFormat("int f(a, b, c);\n" // No break here.
8407                "int\n"             // Break here.
8408                "f(a, b, c)\n"      // Break here.
8409                "short a, b;\n"
8410                "float c;\n"
8411                "{\n"
8412                "  return a + b < c;\n"
8413                "}\n"
8414                "int\n"        // Break here.
8415                "f(a, b, c)\n" // Break here.
8416                "short a, b;\n"
8417                "float c;\n"
8418                "{\n"
8419                "  return a + b < c;\n"
8420                "};",
8421                Style);
8422   verifyFormat("byte *\n" // Break here.
8423                "f(a)\n"   // Break here.
8424                "byte a[];\n"
8425                "{\n"
8426                "  return a;\n"
8427                "}",
8428                Style);
8429   verifyFormat("bool f(int a, int) override;\n"
8430                "Bar g(int a, Bar) final;\n"
8431                "Bar h(a, Bar) final;",
8432                Style);
8433   verifyFormat("int\n"
8434                "f(a)",
8435                Style);
8436   verifyFormat("bool\n"
8437                "f(size_t = 0, bool b = false)\n"
8438                "{\n"
8439                "  return !b;\n"
8440                "}",
8441                Style);
8442 
8443   // The return breaking style doesn't affect:
8444   // * function and object definitions with attribute-like macros
8445   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8446                "    ABSL_GUARDED_BY(mutex) = {};",
8447                getGoogleStyleWithColumns(40));
8448   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8449                "    ABSL_GUARDED_BY(mutex);  // comment",
8450                getGoogleStyleWithColumns(40));
8451   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8452                "    ABSL_GUARDED_BY(mutex1)\n"
8453                "        ABSL_GUARDED_BY(mutex2);",
8454                getGoogleStyleWithColumns(40));
8455   verifyFormat("Tttttt f(int a, int b)\n"
8456                "    ABSL_GUARDED_BY(mutex1)\n"
8457                "        ABSL_GUARDED_BY(mutex2);",
8458                getGoogleStyleWithColumns(40));
8459   // * typedefs
8460   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
8461 
8462   Style = getGNUStyle();
8463 
8464   // Test for comments at the end of function declarations.
8465   verifyFormat("void\n"
8466                "foo (int a, /*abc*/ int b) // def\n"
8467                "{\n"
8468                "}\n",
8469                Style);
8470 
8471   verifyFormat("void\n"
8472                "foo (int a, /* abc */ int b) /* def */\n"
8473                "{\n"
8474                "}\n",
8475                Style);
8476 
8477   // Definitions that should not break after return type
8478   verifyFormat("void foo (int a, int b); // def\n", Style);
8479   verifyFormat("void foo (int a, int b); /* def */\n", Style);
8480   verifyFormat("void foo (int a, int b);\n", Style);
8481 }
8482 
8483 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
8484   FormatStyle NoBreak = getLLVMStyle();
8485   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
8486   FormatStyle Break = getLLVMStyle();
8487   Break.AlwaysBreakBeforeMultilineStrings = true;
8488   verifyFormat("aaaa = \"bbbb\"\n"
8489                "       \"cccc\";",
8490                NoBreak);
8491   verifyFormat("aaaa =\n"
8492                "    \"bbbb\"\n"
8493                "    \"cccc\";",
8494                Break);
8495   verifyFormat("aaaa(\"bbbb\"\n"
8496                "     \"cccc\");",
8497                NoBreak);
8498   verifyFormat("aaaa(\n"
8499                "    \"bbbb\"\n"
8500                "    \"cccc\");",
8501                Break);
8502   verifyFormat("aaaa(qqq, \"bbbb\"\n"
8503                "          \"cccc\");",
8504                NoBreak);
8505   verifyFormat("aaaa(qqq,\n"
8506                "     \"bbbb\"\n"
8507                "     \"cccc\");",
8508                Break);
8509   verifyFormat("aaaa(qqq,\n"
8510                "     L\"bbbb\"\n"
8511                "     L\"cccc\");",
8512                Break);
8513   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
8514                "                      \"bbbb\"));",
8515                Break);
8516   verifyFormat("string s = someFunction(\n"
8517                "    \"abc\"\n"
8518                "    \"abc\");",
8519                Break);
8520 
8521   // As we break before unary operators, breaking right after them is bad.
8522   verifyFormat("string foo = abc ? \"x\"\n"
8523                "                   \"blah blah blah blah blah blah\"\n"
8524                "                 : \"y\";",
8525                Break);
8526 
8527   // Don't break if there is no column gain.
8528   verifyFormat("f(\"aaaa\"\n"
8529                "  \"bbbb\");",
8530                Break);
8531 
8532   // Treat literals with escaped newlines like multi-line string literals.
8533   EXPECT_EQ("x = \"a\\\n"
8534             "b\\\n"
8535             "c\";",
8536             format("x = \"a\\\n"
8537                    "b\\\n"
8538                    "c\";",
8539                    NoBreak));
8540   EXPECT_EQ("xxxx =\n"
8541             "    \"a\\\n"
8542             "b\\\n"
8543             "c\";",
8544             format("xxxx = \"a\\\n"
8545                    "b\\\n"
8546                    "c\";",
8547                    Break));
8548 
8549   EXPECT_EQ("NSString *const kString =\n"
8550             "    @\"aaaa\"\n"
8551             "    @\"bbbb\";",
8552             format("NSString *const kString = @\"aaaa\"\n"
8553                    "@\"bbbb\";",
8554                    Break));
8555 
8556   Break.ColumnLimit = 0;
8557   verifyFormat("const char *hello = \"hello llvm\";", Break);
8558 }
8559 
8560 TEST_F(FormatTest, AlignsPipes) {
8561   verifyFormat(
8562       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8563       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8564       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8565   verifyFormat(
8566       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
8567       "                     << aaaaaaaaaaaaaaaaaaaa;");
8568   verifyFormat(
8569       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8570       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8571   verifyFormat(
8572       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
8573       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8574   verifyFormat(
8575       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
8576       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
8577       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
8578   verifyFormat(
8579       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8580       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8581       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8582   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8583                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8584                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8585                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8586   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
8587                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
8588   verifyFormat(
8589       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8590       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8591   verifyFormat(
8592       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
8593       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
8594 
8595   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
8596                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
8597   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8598                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8599                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
8600                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
8601   verifyFormat("LOG_IF(aaa == //\n"
8602                "       bbb)\n"
8603                "    << a << b;");
8604 
8605   // But sometimes, breaking before the first "<<" is desirable.
8606   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8607                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
8608   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
8609                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8610                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8611   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
8612                "    << BEF << IsTemplate << Description << E->getType();");
8613   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8614                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8615                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8616   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8617                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8618                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8619                "    << aaa;");
8620 
8621   verifyFormat(
8622       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8623       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8624 
8625   // Incomplete string literal.
8626   EXPECT_EQ("llvm::errs() << \"\n"
8627             "             << a;",
8628             format("llvm::errs() << \"\n<<a;"));
8629 
8630   verifyFormat("void f() {\n"
8631                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
8632                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
8633                "}");
8634 
8635   // Handle 'endl'.
8636   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
8637                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8638   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8639 
8640   // Handle '\n'.
8641   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
8642                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8643   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
8644                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
8645   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
8646                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
8647   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8648 }
8649 
8650 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
8651   verifyFormat("return out << \"somepacket = {\\n\"\n"
8652                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
8653                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
8654                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
8655                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
8656                "           << \"}\";");
8657 
8658   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8659                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8660                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
8661   verifyFormat(
8662       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
8663       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
8664       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
8665       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
8666       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
8667   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
8668                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8669   verifyFormat(
8670       "void f() {\n"
8671       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
8672       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
8673       "}");
8674 
8675   // Breaking before the first "<<" is generally not desirable.
8676   verifyFormat(
8677       "llvm::errs()\n"
8678       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8679       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8680       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8681       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8682       getLLVMStyleWithColumns(70));
8683   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8684                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8685                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8686                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8687                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8688                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8689                getLLVMStyleWithColumns(70));
8690 
8691   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8692                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8693                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
8694   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8695                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8696                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
8697   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
8698                "           (aaaa + aaaa);",
8699                getLLVMStyleWithColumns(40));
8700   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
8701                "                  (aaaaaaa + aaaaa));",
8702                getLLVMStyleWithColumns(40));
8703   verifyFormat(
8704       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
8705       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
8706       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
8707 }
8708 
8709 TEST_F(FormatTest, UnderstandsEquals) {
8710   verifyFormat(
8711       "aaaaaaaaaaaaaaaaa =\n"
8712       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8713   verifyFormat(
8714       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8715       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8716   verifyFormat(
8717       "if (a) {\n"
8718       "  f();\n"
8719       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8720       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
8721       "}");
8722 
8723   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8724                "        100000000 + 10000000) {\n}");
8725 }
8726 
8727 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
8728   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8729                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
8730 
8731   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8732                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
8733 
8734   verifyFormat(
8735       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
8736       "                                                          Parameter2);");
8737 
8738   verifyFormat(
8739       "ShortObject->shortFunction(\n"
8740       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
8741       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
8742 
8743   verifyFormat("loooooooooooooongFunction(\n"
8744                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
8745 
8746   verifyFormat(
8747       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
8748       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
8749 
8750   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8751                "    .WillRepeatedly(Return(SomeValue));");
8752   verifyFormat("void f() {\n"
8753                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8754                "      .Times(2)\n"
8755                "      .WillRepeatedly(Return(SomeValue));\n"
8756                "}");
8757   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
8758                "    ccccccccccccccccccccccc);");
8759   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8760                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8761                "          .aaaaa(aaaaa),\n"
8762                "      aaaaaaaaaaaaaaaaaaaaa);");
8763   verifyFormat("void f() {\n"
8764                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8765                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
8766                "}");
8767   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8768                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8769                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8770                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8771                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
8772   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8773                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8774                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8775                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
8776                "}");
8777 
8778   // Here, it is not necessary to wrap at "." or "->".
8779   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
8780                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8781   verifyFormat(
8782       "aaaaaaaaaaa->aaaaaaaaa(\n"
8783       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8784       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
8785 
8786   verifyFormat(
8787       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8788       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
8789   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
8790                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8791   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
8792                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8793 
8794   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8795                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8796                "    .a();");
8797 
8798   FormatStyle NoBinPacking = getLLVMStyle();
8799   NoBinPacking.BinPackParameters = false;
8800   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8801                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8802                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
8803                "                         aaaaaaaaaaaaaaaaaaa,\n"
8804                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8805                NoBinPacking);
8806 
8807   // If there is a subsequent call, change to hanging indentation.
8808   verifyFormat(
8809       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8810       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
8811       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8812   verifyFormat(
8813       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8814       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
8815   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8816                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8817                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8818   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8819                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8820                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
8821 }
8822 
8823 TEST_F(FormatTest, WrapsTemplateDeclarations) {
8824   verifyFormat("template <typename T>\n"
8825                "virtual void loooooooooooongFunction(int Param1, int Param2);");
8826   verifyFormat("template <typename T>\n"
8827                "// T should be one of {A, B}.\n"
8828                "virtual void loooooooooooongFunction(int Param1, int Param2);");
8829   verifyFormat(
8830       "template <typename T>\n"
8831       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
8832   verifyFormat("template <typename T>\n"
8833                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
8834                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
8835   verifyFormat(
8836       "template <typename T>\n"
8837       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
8838       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
8839   verifyFormat(
8840       "template <typename T>\n"
8841       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
8842       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
8843       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8844   verifyFormat("template <typename T>\n"
8845                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8846                "    int aaaaaaaaaaaaaaaaaaaaaa);");
8847   verifyFormat(
8848       "template <typename T1, typename T2 = char, typename T3 = char,\n"
8849       "          typename T4 = char>\n"
8850       "void f();");
8851   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
8852                "          template <typename> class cccccccccccccccccccccc,\n"
8853                "          typename ddddddddddddd>\n"
8854                "class C {};");
8855   verifyFormat(
8856       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
8857       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8858 
8859   verifyFormat("void f() {\n"
8860                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
8861                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
8862                "}");
8863 
8864   verifyFormat("template <typename T> class C {};");
8865   verifyFormat("template <typename T> void f();");
8866   verifyFormat("template <typename T> void f() {}");
8867   verifyFormat(
8868       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8869       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8870       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
8871       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8872       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8873       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
8874       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
8875       getLLVMStyleWithColumns(72));
8876   EXPECT_EQ("static_cast<A< //\n"
8877             "    B> *>(\n"
8878             "\n"
8879             ");",
8880             format("static_cast<A<//\n"
8881                    "    B>*>(\n"
8882                    "\n"
8883                    "    );"));
8884   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8885                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
8886 
8887   FormatStyle AlwaysBreak = getLLVMStyle();
8888   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
8889   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
8890   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
8891   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
8892   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8893                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8894                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
8895   verifyFormat("template <template <typename> class Fooooooo,\n"
8896                "          template <typename> class Baaaaaaar>\n"
8897                "struct C {};",
8898                AlwaysBreak);
8899   verifyFormat("template <typename T> // T can be A, B or C.\n"
8900                "struct C {};",
8901                AlwaysBreak);
8902   verifyFormat("template <enum E> class A {\n"
8903                "public:\n"
8904                "  E *f();\n"
8905                "};");
8906 
8907   FormatStyle NeverBreak = getLLVMStyle();
8908   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
8909   verifyFormat("template <typename T> class C {};", NeverBreak);
8910   verifyFormat("template <typename T> void f();", NeverBreak);
8911   verifyFormat("template <typename T> void f() {}", NeverBreak);
8912   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
8913                "bbbbbbbbbbbbbbbbbbbb) {}",
8914                NeverBreak);
8915   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8916                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8917                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
8918                NeverBreak);
8919   verifyFormat("template <template <typename> class Fooooooo,\n"
8920                "          template <typename> class Baaaaaaar>\n"
8921                "struct C {};",
8922                NeverBreak);
8923   verifyFormat("template <typename T> // T can be A, B or C.\n"
8924                "struct C {};",
8925                NeverBreak);
8926   verifyFormat("template <enum E> class A {\n"
8927                "public:\n"
8928                "  E *f();\n"
8929                "};",
8930                NeverBreak);
8931   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
8932   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
8933                "bbbbbbbbbbbbbbbbbbbb) {}",
8934                NeverBreak);
8935 }
8936 
8937 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
8938   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
8939   Style.ColumnLimit = 60;
8940   EXPECT_EQ("// Baseline - no comments.\n"
8941             "template <\n"
8942             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
8943             "void f() {}",
8944             format("// Baseline - no comments.\n"
8945                    "template <\n"
8946                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
8947                    "void f() {}",
8948                    Style));
8949 
8950   EXPECT_EQ("template <\n"
8951             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
8952             "void f() {}",
8953             format("template <\n"
8954                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8955                    "void f() {}",
8956                    Style));
8957 
8958   EXPECT_EQ(
8959       "template <\n"
8960       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
8961       "void f() {}",
8962       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
8963              "void f() {}",
8964              Style));
8965 
8966   EXPECT_EQ(
8967       "template <\n"
8968       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
8969       "                                               // multiline\n"
8970       "void f() {}",
8971       format("template <\n"
8972              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8973              "                                              // multiline\n"
8974              "void f() {}",
8975              Style));
8976 
8977   EXPECT_EQ(
8978       "template <typename aaaaaaaaaa<\n"
8979       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
8980       "void f() {}",
8981       format(
8982           "template <\n"
8983           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
8984           "void f() {}",
8985           Style));
8986 }
8987 
8988 TEST_F(FormatTest, WrapsTemplateParameters) {
8989   FormatStyle Style = getLLVMStyle();
8990   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8991   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
8992   verifyFormat(
8993       "template <typename... a> struct q {};\n"
8994       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
8995       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
8996       "    y;",
8997       Style);
8998   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8999   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9000   verifyFormat(
9001       "template <typename... a> struct r {};\n"
9002       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9003       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9004       "    y;",
9005       Style);
9006   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9007   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9008   verifyFormat("template <typename... a> struct s {};\n"
9009                "extern s<\n"
9010                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9011                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9012                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9013                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9014                "    y;",
9015                Style);
9016   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9017   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9018   verifyFormat("template <typename... a> struct t {};\n"
9019                "extern t<\n"
9020                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9021                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9022                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9023                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9024                "    y;",
9025                Style);
9026 }
9027 
9028 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9029   verifyFormat(
9030       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9031       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9032   verifyFormat(
9033       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9034       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9035       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9036 
9037   // FIXME: Should we have the extra indent after the second break?
9038   verifyFormat(
9039       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9040       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9041       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9042 
9043   verifyFormat(
9044       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9045       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9046 
9047   // Breaking at nested name specifiers is generally not desirable.
9048   verifyFormat(
9049       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9050       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9051 
9052   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9053                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9054                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9055                "                   aaaaaaaaaaaaaaaaaaaaa);",
9056                getLLVMStyleWithColumns(74));
9057 
9058   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9059                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9060                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9061 }
9062 
9063 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9064   verifyFormat("A<int> a;");
9065   verifyFormat("A<A<A<int>>> a;");
9066   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9067   verifyFormat("bool x = a < 1 || 2 > a;");
9068   verifyFormat("bool x = 5 < f<int>();");
9069   verifyFormat("bool x = f<int>() > 5;");
9070   verifyFormat("bool x = 5 < a<int>::x;");
9071   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9072   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9073 
9074   verifyGoogleFormat("A<A<int>> a;");
9075   verifyGoogleFormat("A<A<A<int>>> a;");
9076   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9077   verifyGoogleFormat("A<A<int> > a;");
9078   verifyGoogleFormat("A<A<A<int> > > a;");
9079   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9080   verifyGoogleFormat("A<::A<int>> a;");
9081   verifyGoogleFormat("A<::A> a;");
9082   verifyGoogleFormat("A< ::A> a;");
9083   verifyGoogleFormat("A< ::A<int> > a;");
9084   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9085   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9086   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9087   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9088   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9089             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9090 
9091   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9092 
9093   // template closer followed by a token that starts with > or =
9094   verifyFormat("bool b = a<1> > 1;");
9095   verifyFormat("bool b = a<1> >= 1;");
9096   verifyFormat("int i = a<1> >> 1;");
9097   FormatStyle Style = getLLVMStyle();
9098   Style.SpaceBeforeAssignmentOperators = false;
9099   verifyFormat("bool b= a<1> == 1;", Style);
9100   verifyFormat("a<int> = 1;", Style);
9101   verifyFormat("a<int> >>= 1;", Style);
9102 
9103   verifyFormat("test < a | b >> c;");
9104   verifyFormat("test<test<a | b>> c;");
9105   verifyFormat("test >> a >> b;");
9106   verifyFormat("test << a >> b;");
9107 
9108   verifyFormat("f<int>();");
9109   verifyFormat("template <typename T> void f() {}");
9110   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9111   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9112                "sizeof(char)>::type>;");
9113   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9114   verifyFormat("f(a.operator()<A>());");
9115   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9116                "      .template operator()<A>());",
9117                getLLVMStyleWithColumns(35));
9118 
9119   // Not template parameters.
9120   verifyFormat("return a < b && c > d;");
9121   verifyFormat("void f() {\n"
9122                "  while (a < b && c > d) {\n"
9123                "  }\n"
9124                "}");
9125   verifyFormat("template <typename... Types>\n"
9126                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9127 
9128   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9129                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9130                getLLVMStyleWithColumns(60));
9131   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9132   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9133   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9134   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9135 }
9136 
9137 TEST_F(FormatTest, UnderstandsShiftOperators) {
9138   verifyFormat("if (i < x >> 1)");
9139   verifyFormat("while (i < x >> 1)");
9140   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9141   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9142   verifyFormat(
9143       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9144   verifyFormat("Foo.call<Bar<Function>>()");
9145   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9146   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9147                "++i, v = v >> 1)");
9148   verifyFormat("if (w<u<v<x>>, 1>::t)");
9149 }
9150 
9151 TEST_F(FormatTest, BitshiftOperatorWidth) {
9152   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9153             "                   bar */",
9154             format("int    a=1<<2;  /* foo\n"
9155                    "                   bar */"));
9156 
9157   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9158             "                     bar */",
9159             format("int  b  =256>>1 ;  /* foo\n"
9160                    "                      bar */"));
9161 }
9162 
9163 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9164   verifyFormat("COMPARE(a, ==, b);");
9165   verifyFormat("auto s = sizeof...(Ts) - 1;");
9166 }
9167 
9168 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9169   verifyFormat("int A::*x;");
9170   verifyFormat("int (S::*func)(void *);");
9171   verifyFormat("void f() { int (S::*func)(void *); }");
9172   verifyFormat("typedef bool *(Class::*Member)() const;");
9173   verifyFormat("void f() {\n"
9174                "  (a->*f)();\n"
9175                "  a->*x;\n"
9176                "  (a.*f)();\n"
9177                "  ((*a).*f)();\n"
9178                "  a.*x;\n"
9179                "}");
9180   verifyFormat("void f() {\n"
9181                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9182                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9183                "}");
9184   verifyFormat(
9185       "(aaaaaaaaaa->*bbbbbbb)(\n"
9186       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9187   FormatStyle Style = getLLVMStyle();
9188   Style.PointerAlignment = FormatStyle::PAS_Left;
9189   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9190 }
9191 
9192 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9193   verifyFormat("int a = -2;");
9194   verifyFormat("f(-1, -2, -3);");
9195   verifyFormat("a[-1] = 5;");
9196   verifyFormat("int a = 5 + -2;");
9197   verifyFormat("if (i == -1) {\n}");
9198   verifyFormat("if (i != -1) {\n}");
9199   verifyFormat("if (i > -1) {\n}");
9200   verifyFormat("if (i < -1) {\n}");
9201   verifyFormat("++(a->f());");
9202   verifyFormat("--(a->f());");
9203   verifyFormat("(a->f())++;");
9204   verifyFormat("a[42]++;");
9205   verifyFormat("if (!(a->f())) {\n}");
9206   verifyFormat("if (!+i) {\n}");
9207   verifyFormat("~&a;");
9208 
9209   verifyFormat("a-- > b;");
9210   verifyFormat("b ? -a : c;");
9211   verifyFormat("n * sizeof char16;");
9212   verifyFormat("n * alignof char16;", getGoogleStyle());
9213   verifyFormat("sizeof(char);");
9214   verifyFormat("alignof(char);", getGoogleStyle());
9215 
9216   verifyFormat("return -1;");
9217   verifyFormat("throw -1;");
9218   verifyFormat("switch (a) {\n"
9219                "case -1:\n"
9220                "  break;\n"
9221                "}");
9222   verifyFormat("#define X -1");
9223   verifyFormat("#define X -kConstant");
9224 
9225   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9226   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9227 
9228   verifyFormat("int a = /* confusing comment */ -1;");
9229   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9230   verifyFormat("int a = i /* confusing comment */++;");
9231 
9232   verifyFormat("co_yield -1;");
9233   verifyFormat("co_return -1;");
9234 
9235   // Check that * is not treated as a binary operator when we set
9236   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9237   FormatStyle PASLeftStyle = getLLVMStyle();
9238   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9239   verifyFormat("co_return *a;", PASLeftStyle);
9240   verifyFormat("co_await *a;", PASLeftStyle);
9241   verifyFormat("co_yield *a", PASLeftStyle);
9242   verifyFormat("return *a;", PASLeftStyle);
9243 }
9244 
9245 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9246   verifyFormat("if (!aaaaaaaaaa( // break\n"
9247                "        aaaaa)) {\n"
9248                "}");
9249   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9250                "    aaaaa));");
9251   verifyFormat("*aaa = aaaaaaa( // break\n"
9252                "    bbbbbb);");
9253 }
9254 
9255 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9256   verifyFormat("bool operator<();");
9257   verifyFormat("bool operator>();");
9258   verifyFormat("bool operator=();");
9259   verifyFormat("bool operator==();");
9260   verifyFormat("bool operator!=();");
9261   verifyFormat("int operator+();");
9262   verifyFormat("int operator++();");
9263   verifyFormat("int operator++(int) volatile noexcept;");
9264   verifyFormat("bool operator,();");
9265   verifyFormat("bool operator();");
9266   verifyFormat("bool operator()();");
9267   verifyFormat("bool operator[]();");
9268   verifyFormat("operator bool();");
9269   verifyFormat("operator int();");
9270   verifyFormat("operator void *();");
9271   verifyFormat("operator SomeType<int>();");
9272   verifyFormat("operator SomeType<int, int>();");
9273   verifyFormat("operator SomeType<SomeType<int>>();");
9274   verifyFormat("void *operator new(std::size_t size);");
9275   verifyFormat("void *operator new[](std::size_t size);");
9276   verifyFormat("void operator delete(void *ptr);");
9277   verifyFormat("void operator delete[](void *ptr);");
9278   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9279                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9280   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9281                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9282 
9283   verifyFormat(
9284       "ostream &operator<<(ostream &OutputStream,\n"
9285       "                    SomeReallyLongType WithSomeReallyLongValue);");
9286   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9287                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9288                "  return left.group < right.group;\n"
9289                "}");
9290   verifyFormat("SomeType &operator=(const SomeType &S);");
9291   verifyFormat("f.template operator()<int>();");
9292 
9293   verifyGoogleFormat("operator void*();");
9294   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9295   verifyGoogleFormat("operator ::A();");
9296 
9297   verifyFormat("using A::operator+;");
9298   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9299                "int i;");
9300 
9301   // Calling an operator as a member function.
9302   verifyFormat("void f() { a.operator*(); }");
9303   verifyFormat("void f() { a.operator*(b & b); }");
9304   verifyFormat("void f() { a->operator&(a * b); }");
9305   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9306   // TODO: Calling an operator as a non-member function is hard to distinguish.
9307   // https://llvm.org/PR50629
9308   // verifyFormat("void f() { operator*(a & a); }");
9309   // verifyFormat("void f() { operator&(a, b * b); }");
9310 
9311   verifyFormat("::operator delete(foo);");
9312   verifyFormat("::operator new(n * sizeof(foo));");
9313   verifyFormat("foo() { ::operator delete(foo); }");
9314   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9315 }
9316 
9317 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9318   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9319   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9320   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9321   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9322   verifyFormat("Deleted &operator=(const Deleted &) &;");
9323   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9324   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9325   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9326   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9327   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9328   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9329   verifyFormat("void Fn(T const &) const &;");
9330   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9331   verifyFormat("template <typename T>\n"
9332                "void F(T) && = delete;",
9333                getGoogleStyle());
9334 
9335   FormatStyle AlignLeft = getLLVMStyle();
9336   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9337   verifyFormat("void A::b() && {}", AlignLeft);
9338   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9339   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9340                AlignLeft);
9341   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9342   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9343   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9344   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9345   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9346   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9347   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9348   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9349 
9350   FormatStyle Spaces = getLLVMStyle();
9351   Spaces.SpacesInCStyleCastParentheses = true;
9352   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9353   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9354   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9355   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9356 
9357   Spaces.SpacesInCStyleCastParentheses = false;
9358   Spaces.SpacesInParentheses = true;
9359   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9360   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9361                Spaces);
9362   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9363   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9364 
9365   FormatStyle BreakTemplate = getLLVMStyle();
9366   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9367 
9368   verifyFormat("struct f {\n"
9369                "  template <class T>\n"
9370                "  int &foo(const std::string &str) &noexcept {}\n"
9371                "};",
9372                BreakTemplate);
9373 
9374   verifyFormat("struct f {\n"
9375                "  template <class T>\n"
9376                "  int &foo(const std::string &str) &&noexcept {}\n"
9377                "};",
9378                BreakTemplate);
9379 
9380   verifyFormat("struct f {\n"
9381                "  template <class T>\n"
9382                "  int &foo(const std::string &str) const &noexcept {}\n"
9383                "};",
9384                BreakTemplate);
9385 
9386   verifyFormat("struct f {\n"
9387                "  template <class T>\n"
9388                "  int &foo(const std::string &str) const &noexcept {}\n"
9389                "};",
9390                BreakTemplate);
9391 
9392   verifyFormat("struct f {\n"
9393                "  template <class T>\n"
9394                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
9395                "};",
9396                BreakTemplate);
9397 
9398   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
9399   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
9400       FormatStyle::BTDS_Yes;
9401   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
9402 
9403   verifyFormat("struct f {\n"
9404                "  template <class T>\n"
9405                "  int& foo(const std::string& str) & noexcept {}\n"
9406                "};",
9407                AlignLeftBreakTemplate);
9408 
9409   verifyFormat("struct f {\n"
9410                "  template <class T>\n"
9411                "  int& foo(const std::string& str) && noexcept {}\n"
9412                "};",
9413                AlignLeftBreakTemplate);
9414 
9415   verifyFormat("struct f {\n"
9416                "  template <class T>\n"
9417                "  int& foo(const std::string& str) const& noexcept {}\n"
9418                "};",
9419                AlignLeftBreakTemplate);
9420 
9421   verifyFormat("struct f {\n"
9422                "  template <class T>\n"
9423                "  int& foo(const std::string& str) const&& noexcept {}\n"
9424                "};",
9425                AlignLeftBreakTemplate);
9426 
9427   verifyFormat("struct f {\n"
9428                "  template <class T>\n"
9429                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
9430                "};",
9431                AlignLeftBreakTemplate);
9432 
9433   // The `&` in `Type&` should not be confused with a trailing `&` of
9434   // DEPRECATED(reason) member function.
9435   verifyFormat("struct f {\n"
9436                "  template <class T>\n"
9437                "  DEPRECATED(reason)\n"
9438                "  Type &foo(arguments) {}\n"
9439                "};",
9440                BreakTemplate);
9441 
9442   verifyFormat("struct f {\n"
9443                "  template <class T>\n"
9444                "  DEPRECATED(reason)\n"
9445                "  Type& foo(arguments) {}\n"
9446                "};",
9447                AlignLeftBreakTemplate);
9448 
9449   verifyFormat("void (*foopt)(int) = &func;");
9450 }
9451 
9452 TEST_F(FormatTest, UnderstandsNewAndDelete) {
9453   verifyFormat("void f() {\n"
9454                "  A *a = new A;\n"
9455                "  A *a = new (placement) A;\n"
9456                "  delete a;\n"
9457                "  delete (A *)a;\n"
9458                "}");
9459   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9460                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9461   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9462                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9463                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9464   verifyFormat("delete[] h->p;");
9465 }
9466 
9467 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
9468   verifyFormat("int *f(int *a) {}");
9469   verifyFormat("int main(int argc, char **argv) {}");
9470   verifyFormat("Test::Test(int b) : a(b * b) {}");
9471   verifyIndependentOfContext("f(a, *a);");
9472   verifyFormat("void g() { f(*a); }");
9473   verifyIndependentOfContext("int a = b * 10;");
9474   verifyIndependentOfContext("int a = 10 * b;");
9475   verifyIndependentOfContext("int a = b * c;");
9476   verifyIndependentOfContext("int a += b * c;");
9477   verifyIndependentOfContext("int a -= b * c;");
9478   verifyIndependentOfContext("int a *= b * c;");
9479   verifyIndependentOfContext("int a /= b * c;");
9480   verifyIndependentOfContext("int a = *b;");
9481   verifyIndependentOfContext("int a = *b * c;");
9482   verifyIndependentOfContext("int a = b * *c;");
9483   verifyIndependentOfContext("int a = b * (10);");
9484   verifyIndependentOfContext("S << b * (10);");
9485   verifyIndependentOfContext("return 10 * b;");
9486   verifyIndependentOfContext("return *b * *c;");
9487   verifyIndependentOfContext("return a & ~b;");
9488   verifyIndependentOfContext("f(b ? *c : *d);");
9489   verifyIndependentOfContext("int a = b ? *c : *d;");
9490   verifyIndependentOfContext("*b = a;");
9491   verifyIndependentOfContext("a * ~b;");
9492   verifyIndependentOfContext("a * !b;");
9493   verifyIndependentOfContext("a * +b;");
9494   verifyIndependentOfContext("a * -b;");
9495   verifyIndependentOfContext("a * ++b;");
9496   verifyIndependentOfContext("a * --b;");
9497   verifyIndependentOfContext("a[4] * b;");
9498   verifyIndependentOfContext("a[a * a] = 1;");
9499   verifyIndependentOfContext("f() * b;");
9500   verifyIndependentOfContext("a * [self dostuff];");
9501   verifyIndependentOfContext("int x = a * (a + b);");
9502   verifyIndependentOfContext("(a *)(a + b);");
9503   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
9504   verifyIndependentOfContext("int *pa = (int *)&a;");
9505   verifyIndependentOfContext("return sizeof(int **);");
9506   verifyIndependentOfContext("return sizeof(int ******);");
9507   verifyIndependentOfContext("return (int **&)a;");
9508   verifyIndependentOfContext("f((*PointerToArray)[10]);");
9509   verifyFormat("void f(Type (*parameter)[10]) {}");
9510   verifyFormat("void f(Type (&parameter)[10]) {}");
9511   verifyGoogleFormat("return sizeof(int**);");
9512   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
9513   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
9514   verifyFormat("auto a = [](int **&, int ***) {};");
9515   verifyFormat("auto PointerBinding = [](const char *S) {};");
9516   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
9517   verifyFormat("[](const decltype(*a) &value) {}");
9518   verifyFormat("[](const typeof(*a) &value) {}");
9519   verifyFormat("[](const _Atomic(a *) &value) {}");
9520   verifyFormat("[](const __underlying_type(a) &value) {}");
9521   verifyFormat("decltype(a * b) F();");
9522   verifyFormat("typeof(a * b) F();");
9523   verifyFormat("#define MACRO() [](A *a) { return 1; }");
9524   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
9525   verifyIndependentOfContext("typedef void (*f)(int *a);");
9526   verifyIndependentOfContext("int i{a * b};");
9527   verifyIndependentOfContext("aaa && aaa->f();");
9528   verifyIndependentOfContext("int x = ~*p;");
9529   verifyFormat("Constructor() : a(a), area(width * height) {}");
9530   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
9531   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
9532   verifyFormat("void f() { f(a, c * d); }");
9533   verifyFormat("void f() { f(new a(), c * d); }");
9534   verifyFormat("void f(const MyOverride &override);");
9535   verifyFormat("void f(const MyFinal &final);");
9536   verifyIndependentOfContext("bool a = f() && override.f();");
9537   verifyIndependentOfContext("bool a = f() && final.f();");
9538 
9539   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
9540 
9541   verifyIndependentOfContext("A<int *> a;");
9542   verifyIndependentOfContext("A<int **> a;");
9543   verifyIndependentOfContext("A<int *, int *> a;");
9544   verifyIndependentOfContext("A<int *[]> a;");
9545   verifyIndependentOfContext(
9546       "const char *const p = reinterpret_cast<const char *const>(q);");
9547   verifyIndependentOfContext("A<int **, int **> a;");
9548   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
9549   verifyFormat("for (char **a = b; *a; ++a) {\n}");
9550   verifyFormat("for (; a && b;) {\n}");
9551   verifyFormat("bool foo = true && [] { return false; }();");
9552 
9553   verifyFormat(
9554       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9555       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9556 
9557   verifyGoogleFormat("int const* a = &b;");
9558   verifyGoogleFormat("**outparam = 1;");
9559   verifyGoogleFormat("*outparam = a * b;");
9560   verifyGoogleFormat("int main(int argc, char** argv) {}");
9561   verifyGoogleFormat("A<int*> a;");
9562   verifyGoogleFormat("A<int**> a;");
9563   verifyGoogleFormat("A<int*, int*> a;");
9564   verifyGoogleFormat("A<int**, int**> a;");
9565   verifyGoogleFormat("f(b ? *c : *d);");
9566   verifyGoogleFormat("int a = b ? *c : *d;");
9567   verifyGoogleFormat("Type* t = **x;");
9568   verifyGoogleFormat("Type* t = *++*x;");
9569   verifyGoogleFormat("*++*x;");
9570   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
9571   verifyGoogleFormat("Type* t = x++ * y;");
9572   verifyGoogleFormat(
9573       "const char* const p = reinterpret_cast<const char* const>(q);");
9574   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
9575   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
9576   verifyGoogleFormat("template <typename T>\n"
9577                      "void f(int i = 0, SomeType** temps = NULL);");
9578 
9579   FormatStyle Left = getLLVMStyle();
9580   Left.PointerAlignment = FormatStyle::PAS_Left;
9581   verifyFormat("x = *a(x) = *a(y);", Left);
9582   verifyFormat("for (;; *a = b) {\n}", Left);
9583   verifyFormat("return *this += 1;", Left);
9584   verifyFormat("throw *x;", Left);
9585   verifyFormat("delete *x;", Left);
9586   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
9587   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
9588   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
9589   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
9590   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
9591   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
9592   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
9593   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
9594   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
9595 
9596   verifyIndependentOfContext("a = *(x + y);");
9597   verifyIndependentOfContext("a = &(x + y);");
9598   verifyIndependentOfContext("*(x + y).call();");
9599   verifyIndependentOfContext("&(x + y)->call();");
9600   verifyFormat("void f() { &(*I).first; }");
9601 
9602   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
9603   verifyFormat("f(* /* confusing comment */ foo);");
9604   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
9605   verifyFormat("void foo(int * // this is the first paramters\n"
9606                "         ,\n"
9607                "         int second);");
9608   verifyFormat("double term = a * // first\n"
9609                "              b;");
9610   verifyFormat(
9611       "int *MyValues = {\n"
9612       "    *A, // Operator detection might be confused by the '{'\n"
9613       "    *BB // Operator detection might be confused by previous comment\n"
9614       "};");
9615 
9616   verifyIndependentOfContext("if (int *a = &b)");
9617   verifyIndependentOfContext("if (int &a = *b)");
9618   verifyIndependentOfContext("if (a & b[i])");
9619   verifyIndependentOfContext("if constexpr (a & b[i])");
9620   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
9621   verifyIndependentOfContext("if (a * (b * c))");
9622   verifyIndependentOfContext("if constexpr (a * (b * c))");
9623   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
9624   verifyIndependentOfContext("if (a::b::c::d & b[i])");
9625   verifyIndependentOfContext("if (*b[i])");
9626   verifyIndependentOfContext("if (int *a = (&b))");
9627   verifyIndependentOfContext("while (int *a = &b)");
9628   verifyIndependentOfContext("while (a * (b * c))");
9629   verifyIndependentOfContext("size = sizeof *a;");
9630   verifyIndependentOfContext("if (a && (b = c))");
9631   verifyFormat("void f() {\n"
9632                "  for (const int &v : Values) {\n"
9633                "  }\n"
9634                "}");
9635   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
9636   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
9637   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
9638 
9639   verifyFormat("#define A (!a * b)");
9640   verifyFormat("#define MACRO     \\\n"
9641                "  int *i = a * b; \\\n"
9642                "  void f(a *b);",
9643                getLLVMStyleWithColumns(19));
9644 
9645   verifyIndependentOfContext("A = new SomeType *[Length];");
9646   verifyIndependentOfContext("A = new SomeType *[Length]();");
9647   verifyIndependentOfContext("T **t = new T *;");
9648   verifyIndependentOfContext("T **t = new T *();");
9649   verifyGoogleFormat("A = new SomeType*[Length]();");
9650   verifyGoogleFormat("A = new SomeType*[Length];");
9651   verifyGoogleFormat("T** t = new T*;");
9652   verifyGoogleFormat("T** t = new T*();");
9653 
9654   verifyFormat("STATIC_ASSERT((a & b) == 0);");
9655   verifyFormat("STATIC_ASSERT(0 == (a & b));");
9656   verifyFormat("template <bool a, bool b> "
9657                "typename t::if<x && y>::type f() {}");
9658   verifyFormat("template <int *y> f() {}");
9659   verifyFormat("vector<int *> v;");
9660   verifyFormat("vector<int *const> v;");
9661   verifyFormat("vector<int *const **const *> v;");
9662   verifyFormat("vector<int *volatile> v;");
9663   verifyFormat("vector<a *_Nonnull> v;");
9664   verifyFormat("vector<a *_Nullable> v;");
9665   verifyFormat("vector<a *_Null_unspecified> v;");
9666   verifyFormat("vector<a *__ptr32> v;");
9667   verifyFormat("vector<a *__ptr64> v;");
9668   verifyFormat("vector<a *__capability> v;");
9669   FormatStyle TypeMacros = getLLVMStyle();
9670   TypeMacros.TypenameMacros = {"LIST"};
9671   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
9672   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
9673   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
9674   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
9675   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
9676 
9677   FormatStyle CustomQualifier = getLLVMStyle();
9678   // Add identifiers that should not be parsed as a qualifier by default.
9679   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9680   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
9681   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
9682   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
9683   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
9684   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
9685   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
9686   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
9687   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
9688   verifyFormat("vector<a * _NotAQualifier> v;");
9689   verifyFormat("vector<a * __not_a_qualifier> v;");
9690   verifyFormat("vector<a * b> v;");
9691   verifyFormat("foo<b && false>();");
9692   verifyFormat("foo<b & 1>();");
9693   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
9694   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
9695   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
9696   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
9697   verifyFormat(
9698       "template <class T, class = typename std::enable_if<\n"
9699       "                       std::is_integral<T>::value &&\n"
9700       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
9701       "void F();",
9702       getLLVMStyleWithColumns(70));
9703   verifyFormat("template <class T,\n"
9704                "          class = typename std::enable_if<\n"
9705                "              std::is_integral<T>::value &&\n"
9706                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
9707                "          class U>\n"
9708                "void F();",
9709                getLLVMStyleWithColumns(70));
9710   verifyFormat(
9711       "template <class T,\n"
9712       "          class = typename ::std::enable_if<\n"
9713       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
9714       "void F();",
9715       getGoogleStyleWithColumns(68));
9716 
9717   verifyIndependentOfContext("MACRO(int *i);");
9718   verifyIndependentOfContext("MACRO(auto *a);");
9719   verifyIndependentOfContext("MACRO(const A *a);");
9720   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
9721   verifyIndependentOfContext("MACRO(decltype(A) *a);");
9722   verifyIndependentOfContext("MACRO(typeof(A) *a);");
9723   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
9724   verifyIndependentOfContext("MACRO(A *const a);");
9725   verifyIndependentOfContext("MACRO(A *restrict a);");
9726   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
9727   verifyIndependentOfContext("MACRO(A *__restrict a);");
9728   verifyIndependentOfContext("MACRO(A *volatile a);");
9729   verifyIndependentOfContext("MACRO(A *__volatile a);");
9730   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
9731   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
9732   verifyIndependentOfContext("MACRO(A *_Nullable a);");
9733   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
9734   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
9735   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
9736   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
9737   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
9738   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
9739   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
9740   verifyIndependentOfContext("MACRO(A *__capability);");
9741   verifyIndependentOfContext("MACRO(A &__capability);");
9742   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
9743   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
9744   // If we add __my_qualifier to AttributeMacros it should always be parsed as
9745   // a type declaration:
9746   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
9747   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
9748   // Also check that TypenameMacros prevents parsing it as multiplication:
9749   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
9750   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
9751 
9752   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
9753   verifyFormat("void f() { f(float{1}, a * a); }");
9754   verifyFormat("void f() { f(float(1), a * a); }");
9755 
9756   verifyFormat("f((void (*)(int))g);");
9757   verifyFormat("f((void (&)(int))g);");
9758   verifyFormat("f((void (^)(int))g);");
9759 
9760   // FIXME: Is there a way to make this work?
9761   // verifyIndependentOfContext("MACRO(A *a);");
9762   verifyFormat("MACRO(A &B);");
9763   verifyFormat("MACRO(A *B);");
9764   verifyFormat("void f() { MACRO(A * B); }");
9765   verifyFormat("void f() { MACRO(A & B); }");
9766 
9767   // This lambda was mis-formatted after D88956 (treating it as a binop):
9768   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
9769   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
9770   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
9771   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
9772 
9773   verifyFormat("DatumHandle const *operator->() const { return input_; }");
9774   verifyFormat("return options != nullptr && operator==(*options);");
9775 
9776   EXPECT_EQ("#define OP(x)                                    \\\n"
9777             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
9778             "    return s << a.DebugString();                 \\\n"
9779             "  }",
9780             format("#define OP(x) \\\n"
9781                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
9782                    "    return s << a.DebugString(); \\\n"
9783                    "  }",
9784                    getLLVMStyleWithColumns(50)));
9785 
9786   // FIXME: We cannot handle this case yet; we might be able to figure out that
9787   // foo<x> d > v; doesn't make sense.
9788   verifyFormat("foo<a<b && c> d> v;");
9789 
9790   FormatStyle PointerMiddle = getLLVMStyle();
9791   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9792   verifyFormat("delete *x;", PointerMiddle);
9793   verifyFormat("int * x;", PointerMiddle);
9794   verifyFormat("int *[] x;", PointerMiddle);
9795   verifyFormat("template <int * y> f() {}", PointerMiddle);
9796   verifyFormat("int * f(int * a) {}", PointerMiddle);
9797   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
9798   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
9799   verifyFormat("A<int *> a;", PointerMiddle);
9800   verifyFormat("A<int **> a;", PointerMiddle);
9801   verifyFormat("A<int *, int *> a;", PointerMiddle);
9802   verifyFormat("A<int *[]> a;", PointerMiddle);
9803   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
9804   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
9805   verifyFormat("T ** t = new T *;", PointerMiddle);
9806 
9807   // Member function reference qualifiers aren't binary operators.
9808   verifyFormat("string // break\n"
9809                "operator()() & {}");
9810   verifyFormat("string // break\n"
9811                "operator()() && {}");
9812   verifyGoogleFormat("template <typename T>\n"
9813                      "auto x() & -> int {}");
9814 
9815   // Should be binary operators when used as an argument expression (overloaded
9816   // operator invoked as a member function).
9817   verifyFormat("void f() { a.operator()(a * a); }");
9818   verifyFormat("void f() { a->operator()(a & a); }");
9819   verifyFormat("void f() { a.operator()(*a & *a); }");
9820   verifyFormat("void f() { a->operator()(*a * *a); }");
9821 
9822   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
9823   verifyFormat("int operator()(T (&)[N]) { return 0; }");
9824 }
9825 
9826 TEST_F(FormatTest, UnderstandsAttributes) {
9827   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
9828   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
9829                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9830   FormatStyle AfterType = getLLVMStyle();
9831   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
9832   verifyFormat("__attribute__((nodebug)) void\n"
9833                "foo() {}\n",
9834                AfterType);
9835   verifyFormat("__unused void\n"
9836                "foo() {}",
9837                AfterType);
9838 
9839   FormatStyle CustomAttrs = getLLVMStyle();
9840   CustomAttrs.AttributeMacros.push_back("__unused");
9841   CustomAttrs.AttributeMacros.push_back("__attr1");
9842   CustomAttrs.AttributeMacros.push_back("__attr2");
9843   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
9844   verifyFormat("vector<SomeType *__attribute((foo))> v;");
9845   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
9846   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
9847   // Check that it is parsed as a multiplication without AttributeMacros and
9848   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
9849   verifyFormat("vector<SomeType * __attr1> v;");
9850   verifyFormat("vector<SomeType __attr1 *> v;");
9851   verifyFormat("vector<SomeType __attr1 *const> v;");
9852   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
9853   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
9854   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
9855   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
9856   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
9857   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
9858   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
9859   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
9860 
9861   // Check that these are not parsed as function declarations:
9862   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9863   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
9864   verifyFormat("SomeType s(InitValue);", CustomAttrs);
9865   verifyFormat("SomeType s{InitValue};", CustomAttrs);
9866   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
9867   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
9868   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
9869   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
9870   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
9871   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
9872 }
9873 
9874 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
9875   // Check that qualifiers on pointers don't break parsing of casts.
9876   verifyFormat("x = (foo *const)*v;");
9877   verifyFormat("x = (foo *volatile)*v;");
9878   verifyFormat("x = (foo *restrict)*v;");
9879   verifyFormat("x = (foo *__attribute__((foo)))*v;");
9880   verifyFormat("x = (foo *_Nonnull)*v;");
9881   verifyFormat("x = (foo *_Nullable)*v;");
9882   verifyFormat("x = (foo *_Null_unspecified)*v;");
9883   verifyFormat("x = (foo *_Nonnull)*v;");
9884   verifyFormat("x = (foo *[[clang::attr]])*v;");
9885   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
9886   verifyFormat("x = (foo *__ptr32)*v;");
9887   verifyFormat("x = (foo *__ptr64)*v;");
9888   verifyFormat("x = (foo *__capability)*v;");
9889 
9890   // Check that we handle multiple trailing qualifiers and skip them all to
9891   // determine that the expression is a cast to a pointer type.
9892   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
9893   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
9894   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
9895   StringRef AllQualifiers =
9896       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
9897       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
9898   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
9899   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
9900 
9901   // Also check that address-of is not parsed as a binary bitwise-and:
9902   verifyFormat("x = (foo *const)&v;");
9903   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
9904   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
9905 
9906   // Check custom qualifiers:
9907   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
9908   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9909   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
9910   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
9911   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
9912                CustomQualifier);
9913   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
9914                CustomQualifier);
9915 
9916   // Check that unknown identifiers result in binary operator parsing:
9917   verifyFormat("x = (foo * __unknown_qualifier) * v;");
9918   verifyFormat("x = (foo * __unknown_qualifier) & v;");
9919 }
9920 
9921 TEST_F(FormatTest, UnderstandsSquareAttributes) {
9922   verifyFormat("SomeType s [[unused]] (InitValue);");
9923   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
9924   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
9925   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
9926   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
9927   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9928                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9929   verifyFormat("[[nodiscard]] bool f() { return false; }");
9930   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
9931   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
9932   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
9933 
9934   // Make sure we do not mistake attributes for array subscripts.
9935   verifyFormat("int a() {}\n"
9936                "[[unused]] int b() {}\n");
9937   verifyFormat("NSArray *arr;\n"
9938                "arr[[Foo() bar]];");
9939 
9940   // On the other hand, we still need to correctly find array subscripts.
9941   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
9942 
9943   // Make sure that we do not mistake Objective-C method inside array literals
9944   // as attributes, even if those method names are also keywords.
9945   verifyFormat("@[ [foo bar] ];");
9946   verifyFormat("@[ [NSArray class] ];");
9947   verifyFormat("@[ [foo enum] ];");
9948 
9949   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
9950 
9951   // Make sure we do not parse attributes as lambda introducers.
9952   FormatStyle MultiLineFunctions = getLLVMStyle();
9953   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9954   verifyFormat("[[unused]] int b() {\n"
9955                "  return 42;\n"
9956                "}\n",
9957                MultiLineFunctions);
9958 }
9959 
9960 TEST_F(FormatTest, AttributeClass) {
9961   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
9962   verifyFormat("class S {\n"
9963                "  S(S&&) = default;\n"
9964                "};",
9965                Style);
9966   verifyFormat("class [[nodiscard]] S {\n"
9967                "  S(S&&) = default;\n"
9968                "};",
9969                Style);
9970   verifyFormat("class __attribute((maybeunused)) S {\n"
9971                "  S(S&&) = default;\n"
9972                "};",
9973                Style);
9974   verifyFormat("struct S {\n"
9975                "  S(S&&) = default;\n"
9976                "};",
9977                Style);
9978   verifyFormat("struct [[nodiscard]] S {\n"
9979                "  S(S&&) = default;\n"
9980                "};",
9981                Style);
9982 }
9983 
9984 TEST_F(FormatTest, AttributesAfterMacro) {
9985   FormatStyle Style = getLLVMStyle();
9986   verifyFormat("MACRO;\n"
9987                "__attribute__((maybe_unused)) int foo() {\n"
9988                "  //...\n"
9989                "}");
9990 
9991   verifyFormat("MACRO;\n"
9992                "[[nodiscard]] int foo() {\n"
9993                "  //...\n"
9994                "}");
9995 
9996   EXPECT_EQ("MACRO\n\n"
9997             "__attribute__((maybe_unused)) int foo() {\n"
9998             "  //...\n"
9999             "}",
10000             format("MACRO\n\n"
10001                    "__attribute__((maybe_unused)) int foo() {\n"
10002                    "  //...\n"
10003                    "}"));
10004 
10005   EXPECT_EQ("MACRO\n\n"
10006             "[[nodiscard]] int foo() {\n"
10007             "  //...\n"
10008             "}",
10009             format("MACRO\n\n"
10010                    "[[nodiscard]] int foo() {\n"
10011                    "  //...\n"
10012                    "}"));
10013 }
10014 
10015 TEST_F(FormatTest, AttributePenaltyBreaking) {
10016   FormatStyle Style = getLLVMStyle();
10017   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10018                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10019                Style);
10020   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10021                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10022                Style);
10023   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10024                "shared_ptr<ALongTypeName> &C d) {\n}",
10025                Style);
10026 }
10027 
10028 TEST_F(FormatTest, UnderstandsEllipsis) {
10029   FormatStyle Style = getLLVMStyle();
10030   verifyFormat("int printf(const char *fmt, ...);");
10031   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10032   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10033 
10034   verifyFormat("template <int *...PP> a;", Style);
10035 
10036   Style.PointerAlignment = FormatStyle::PAS_Left;
10037   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10038 
10039   verifyFormat("template <int*... PP> a;", Style);
10040 
10041   Style.PointerAlignment = FormatStyle::PAS_Middle;
10042   verifyFormat("template <int *... PP> a;", Style);
10043 }
10044 
10045 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10046   EXPECT_EQ("int *a;\n"
10047             "int *a;\n"
10048             "int *a;",
10049             format("int *a;\n"
10050                    "int* a;\n"
10051                    "int *a;",
10052                    getGoogleStyle()));
10053   EXPECT_EQ("int* a;\n"
10054             "int* a;\n"
10055             "int* a;",
10056             format("int* a;\n"
10057                    "int* a;\n"
10058                    "int *a;",
10059                    getGoogleStyle()));
10060   EXPECT_EQ("int *a;\n"
10061             "int *a;\n"
10062             "int *a;",
10063             format("int *a;\n"
10064                    "int * a;\n"
10065                    "int *  a;",
10066                    getGoogleStyle()));
10067   EXPECT_EQ("auto x = [] {\n"
10068             "  int *a;\n"
10069             "  int *a;\n"
10070             "  int *a;\n"
10071             "};",
10072             format("auto x=[]{int *a;\n"
10073                    "int * a;\n"
10074                    "int *  a;};",
10075                    getGoogleStyle()));
10076 }
10077 
10078 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10079   verifyFormat("int f(int &&a) {}");
10080   verifyFormat("int f(int a, char &&b) {}");
10081   verifyFormat("void f() { int &&a = b; }");
10082   verifyGoogleFormat("int f(int a, char&& b) {}");
10083   verifyGoogleFormat("void f() { int&& a = b; }");
10084 
10085   verifyIndependentOfContext("A<int &&> a;");
10086   verifyIndependentOfContext("A<int &&, int &&> a;");
10087   verifyGoogleFormat("A<int&&> a;");
10088   verifyGoogleFormat("A<int&&, int&&> a;");
10089 
10090   // Not rvalue references:
10091   verifyFormat("template <bool B, bool C> class A {\n"
10092                "  static_assert(B && C, \"Something is wrong\");\n"
10093                "};");
10094   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10095   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10096   verifyFormat("#define A(a, b) (a && b)");
10097 }
10098 
10099 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10100   verifyFormat("void f() {\n"
10101                "  x[aaaaaaaaa -\n"
10102                "    b] = 23;\n"
10103                "}",
10104                getLLVMStyleWithColumns(15));
10105 }
10106 
10107 TEST_F(FormatTest, FormatsCasts) {
10108   verifyFormat("Type *A = static_cast<Type *>(P);");
10109   verifyFormat("Type *A = (Type *)P;");
10110   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10111   verifyFormat("int a = (int)(2.0f);");
10112   verifyFormat("int a = (int)2.0f;");
10113   verifyFormat("x[(int32)y];");
10114   verifyFormat("x = (int32)y;");
10115   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10116   verifyFormat("int a = (int)*b;");
10117   verifyFormat("int a = (int)2.0f;");
10118   verifyFormat("int a = (int)~0;");
10119   verifyFormat("int a = (int)++a;");
10120   verifyFormat("int a = (int)sizeof(int);");
10121   verifyFormat("int a = (int)+2;");
10122   verifyFormat("my_int a = (my_int)2.0f;");
10123   verifyFormat("my_int a = (my_int)sizeof(int);");
10124   verifyFormat("return (my_int)aaa;");
10125   verifyFormat("#define x ((int)-1)");
10126   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10127   verifyFormat("#define p(q) ((int *)&q)");
10128   verifyFormat("fn(a)(b) + 1;");
10129 
10130   verifyFormat("void f() { my_int a = (my_int)*b; }");
10131   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10132   verifyFormat("my_int a = (my_int)~0;");
10133   verifyFormat("my_int a = (my_int)++a;");
10134   verifyFormat("my_int a = (my_int)-2;");
10135   verifyFormat("my_int a = (my_int)1;");
10136   verifyFormat("my_int a = (my_int *)1;");
10137   verifyFormat("my_int a = (const my_int)-1;");
10138   verifyFormat("my_int a = (const my_int *)-1;");
10139   verifyFormat("my_int a = (my_int)(my_int)-1;");
10140   verifyFormat("my_int a = (ns::my_int)-2;");
10141   verifyFormat("case (my_int)ONE:");
10142   verifyFormat("auto x = (X)this;");
10143   // Casts in Obj-C style calls used to not be recognized as such.
10144   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10145 
10146   // FIXME: single value wrapped with paren will be treated as cast.
10147   verifyFormat("void f(int i = (kValue)*kMask) {}");
10148 
10149   verifyFormat("{ (void)F; }");
10150 
10151   // Don't break after a cast's
10152   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10153                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10154                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10155 
10156   // These are not casts.
10157   verifyFormat("void f(int *) {}");
10158   verifyFormat("f(foo)->b;");
10159   verifyFormat("f(foo).b;");
10160   verifyFormat("f(foo)(b);");
10161   verifyFormat("f(foo)[b];");
10162   verifyFormat("[](foo) { return 4; }(bar);");
10163   verifyFormat("(*funptr)(foo)[4];");
10164   verifyFormat("funptrs[4](foo)[4];");
10165   verifyFormat("void f(int *);");
10166   verifyFormat("void f(int *) = 0;");
10167   verifyFormat("void f(SmallVector<int>) {}");
10168   verifyFormat("void f(SmallVector<int>);");
10169   verifyFormat("void f(SmallVector<int>) = 0;");
10170   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10171   verifyFormat("int a = sizeof(int) * b;");
10172   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10173   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10174   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10175   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10176 
10177   // These are not casts, but at some point were confused with casts.
10178   verifyFormat("virtual void foo(int *) override;");
10179   verifyFormat("virtual void foo(char &) const;");
10180   verifyFormat("virtual void foo(int *a, char *) const;");
10181   verifyFormat("int a = sizeof(int *) + b;");
10182   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10183   verifyFormat("bool b = f(g<int>) && c;");
10184   verifyFormat("typedef void (*f)(int i) func;");
10185   verifyFormat("void operator++(int) noexcept;");
10186   verifyFormat("void operator++(int &) noexcept;");
10187   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10188                "&) noexcept;");
10189   verifyFormat(
10190       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10191   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10192   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10193   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10194   verifyFormat("void operator delete(foo &) noexcept;");
10195   verifyFormat("void operator delete(foo) noexcept;");
10196   verifyFormat("void operator delete(int) noexcept;");
10197   verifyFormat("void operator delete(int &) noexcept;");
10198   verifyFormat("void operator delete(int &) volatile noexcept;");
10199   verifyFormat("void operator delete(int &) const");
10200   verifyFormat("void operator delete(int &) = default");
10201   verifyFormat("void operator delete(int &) = delete");
10202   verifyFormat("void operator delete(int &) [[noreturn]]");
10203   verifyFormat("void operator delete(int &) throw();");
10204   verifyFormat("void operator delete(int &) throw(int);");
10205   verifyFormat("auto operator delete(int &) -> int;");
10206   verifyFormat("auto operator delete(int &) override");
10207   verifyFormat("auto operator delete(int &) final");
10208 
10209   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10210                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10211   // FIXME: The indentation here is not ideal.
10212   verifyFormat(
10213       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10214       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10215       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10216 }
10217 
10218 TEST_F(FormatTest, FormatsFunctionTypes) {
10219   verifyFormat("A<bool()> a;");
10220   verifyFormat("A<SomeType()> a;");
10221   verifyFormat("A<void (*)(int, std::string)> a;");
10222   verifyFormat("A<void *(int)>;");
10223   verifyFormat("void *(*a)(int *, SomeType *);");
10224   verifyFormat("int (*func)(void *);");
10225   verifyFormat("void f() { int (*func)(void *); }");
10226   verifyFormat("template <class CallbackClass>\n"
10227                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10228 
10229   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10230   verifyGoogleFormat("void* (*a)(int);");
10231   verifyGoogleFormat(
10232       "template <class CallbackClass>\n"
10233       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10234 
10235   // Other constructs can look somewhat like function types:
10236   verifyFormat("A<sizeof(*x)> a;");
10237   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10238   verifyFormat("some_var = function(*some_pointer_var)[0];");
10239   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10240   verifyFormat("int x = f(&h)();");
10241   verifyFormat("returnsFunction(&param1, &param2)(param);");
10242   verifyFormat("std::function<\n"
10243                "    LooooooooooongTemplatedType<\n"
10244                "        SomeType>*(\n"
10245                "        LooooooooooooooooongType type)>\n"
10246                "    function;",
10247                getGoogleStyleWithColumns(40));
10248 }
10249 
10250 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10251   verifyFormat("A (*foo_)[6];");
10252   verifyFormat("vector<int> (*foo_)[6];");
10253 }
10254 
10255 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10256   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10257                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10258   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10259                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10260   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10261                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10262 
10263   // Different ways of ()-initializiation.
10264   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10265                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10266   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10267                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10268   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10269                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10270   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10271                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10272 
10273   // Lambdas should not confuse the variable declaration heuristic.
10274   verifyFormat("LooooooooooooooooongType\n"
10275                "    variable(nullptr, [](A *a) {});",
10276                getLLVMStyleWithColumns(40));
10277 }
10278 
10279 TEST_F(FormatTest, BreaksLongDeclarations) {
10280   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10281                "    AnotherNameForTheLongType;");
10282   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10283                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10284   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10285                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10286   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10287                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10288   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10289                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10290   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10291                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10292   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10293                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10294   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10295                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10296   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10297                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10298   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10299                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10300   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10301                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10302   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10303                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10304   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10305                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10306   FormatStyle Indented = getLLVMStyle();
10307   Indented.IndentWrappedFunctionNames = true;
10308   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10309                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10310                Indented);
10311   verifyFormat(
10312       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10313       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10314       Indented);
10315   verifyFormat(
10316       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10317       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10318       Indented);
10319   verifyFormat(
10320       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10321       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10322       Indented);
10323 
10324   // FIXME: Without the comment, this breaks after "(".
10325   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10326                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10327                getGoogleStyle());
10328 
10329   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10330                "                  int LoooooooooooooooooooongParam2) {}");
10331   verifyFormat(
10332       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
10333       "                                   SourceLocation L, IdentifierIn *II,\n"
10334       "                                   Type *T) {}");
10335   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
10336                "ReallyReaaallyLongFunctionName(\n"
10337                "    const std::string &SomeParameter,\n"
10338                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10339                "        &ReallyReallyLongParameterName,\n"
10340                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10341                "        &AnotherLongParameterName) {}");
10342   verifyFormat("template <typename A>\n"
10343                "SomeLoooooooooooooooooooooongType<\n"
10344                "    typename some_namespace::SomeOtherType<A>::Type>\n"
10345                "Function() {}");
10346 
10347   verifyGoogleFormat(
10348       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
10349       "    aaaaaaaaaaaaaaaaaaaaaaa;");
10350   verifyGoogleFormat(
10351       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
10352       "                                   SourceLocation L) {}");
10353   verifyGoogleFormat(
10354       "some_namespace::LongReturnType\n"
10355       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
10356       "    int first_long_parameter, int second_parameter) {}");
10357 
10358   verifyGoogleFormat("template <typename T>\n"
10359                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10360                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
10361   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10362                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
10363 
10364   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
10365                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10366                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10367   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10368                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10369                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
10370   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10371                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
10372                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
10373                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10374 
10375   verifyFormat("template <typename T> // Templates on own line.\n"
10376                "static int            // Some comment.\n"
10377                "MyFunction(int a);",
10378                getLLVMStyle());
10379 }
10380 
10381 TEST_F(FormatTest, FormatsAccessModifiers) {
10382   FormatStyle Style = getLLVMStyle();
10383   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
10384             FormatStyle::ELBAMS_LogicalBlock);
10385   verifyFormat("struct foo {\n"
10386                "private:\n"
10387                "  void f() {}\n"
10388                "\n"
10389                "private:\n"
10390                "  int i;\n"
10391                "\n"
10392                "protected:\n"
10393                "  int j;\n"
10394                "};\n",
10395                Style);
10396   verifyFormat("struct foo {\n"
10397                "private:\n"
10398                "  void f() {}\n"
10399                "\n"
10400                "private:\n"
10401                "  int i;\n"
10402                "\n"
10403                "protected:\n"
10404                "  int j;\n"
10405                "};\n",
10406                "struct foo {\n"
10407                "private:\n"
10408                "  void f() {}\n"
10409                "private:\n"
10410                "  int i;\n"
10411                "protected:\n"
10412                "  int j;\n"
10413                "};\n",
10414                Style);
10415   verifyFormat("struct foo { /* comment */\n"
10416                "private:\n"
10417                "  int i;\n"
10418                "  // comment\n"
10419                "private:\n"
10420                "  int j;\n"
10421                "};\n",
10422                Style);
10423   verifyFormat("struct foo {\n"
10424                "#ifdef FOO\n"
10425                "#endif\n"
10426                "private:\n"
10427                "  int i;\n"
10428                "#ifdef FOO\n"
10429                "private:\n"
10430                "#endif\n"
10431                "  int j;\n"
10432                "};\n",
10433                Style);
10434   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10435   verifyFormat("struct foo {\n"
10436                "private:\n"
10437                "  void f() {}\n"
10438                "private:\n"
10439                "  int i;\n"
10440                "protected:\n"
10441                "  int j;\n"
10442                "};\n",
10443                Style);
10444   verifyFormat("struct foo {\n"
10445                "private:\n"
10446                "  void f() {}\n"
10447                "private:\n"
10448                "  int i;\n"
10449                "protected:\n"
10450                "  int j;\n"
10451                "};\n",
10452                "struct foo {\n"
10453                "\n"
10454                "private:\n"
10455                "  void f() {}\n"
10456                "\n"
10457                "private:\n"
10458                "  int i;\n"
10459                "\n"
10460                "protected:\n"
10461                "  int j;\n"
10462                "};\n",
10463                Style);
10464   verifyFormat("struct foo { /* comment */\n"
10465                "private:\n"
10466                "  int i;\n"
10467                "  // comment\n"
10468                "private:\n"
10469                "  int j;\n"
10470                "};\n",
10471                "struct foo { /* comment */\n"
10472                "\n"
10473                "private:\n"
10474                "  int i;\n"
10475                "  // comment\n"
10476                "\n"
10477                "private:\n"
10478                "  int j;\n"
10479                "};\n",
10480                Style);
10481   verifyFormat("struct foo {\n"
10482                "#ifdef FOO\n"
10483                "#endif\n"
10484                "private:\n"
10485                "  int i;\n"
10486                "#ifdef FOO\n"
10487                "private:\n"
10488                "#endif\n"
10489                "  int j;\n"
10490                "};\n",
10491                "struct foo {\n"
10492                "#ifdef FOO\n"
10493                "#endif\n"
10494                "\n"
10495                "private:\n"
10496                "  int i;\n"
10497                "#ifdef FOO\n"
10498                "\n"
10499                "private:\n"
10500                "#endif\n"
10501                "  int j;\n"
10502                "};\n",
10503                Style);
10504   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10505   verifyFormat("struct foo {\n"
10506                "private:\n"
10507                "  void f() {}\n"
10508                "\n"
10509                "private:\n"
10510                "  int i;\n"
10511                "\n"
10512                "protected:\n"
10513                "  int j;\n"
10514                "};\n",
10515                Style);
10516   verifyFormat("struct foo {\n"
10517                "private:\n"
10518                "  void f() {}\n"
10519                "\n"
10520                "private:\n"
10521                "  int i;\n"
10522                "\n"
10523                "protected:\n"
10524                "  int j;\n"
10525                "};\n",
10526                "struct foo {\n"
10527                "private:\n"
10528                "  void f() {}\n"
10529                "private:\n"
10530                "  int i;\n"
10531                "protected:\n"
10532                "  int j;\n"
10533                "};\n",
10534                Style);
10535   verifyFormat("struct foo { /* comment */\n"
10536                "private:\n"
10537                "  int i;\n"
10538                "  // comment\n"
10539                "\n"
10540                "private:\n"
10541                "  int j;\n"
10542                "};\n",
10543                "struct foo { /* comment */\n"
10544                "private:\n"
10545                "  int i;\n"
10546                "  // comment\n"
10547                "\n"
10548                "private:\n"
10549                "  int j;\n"
10550                "};\n",
10551                Style);
10552   verifyFormat("struct foo {\n"
10553                "#ifdef FOO\n"
10554                "#endif\n"
10555                "\n"
10556                "private:\n"
10557                "  int i;\n"
10558                "#ifdef FOO\n"
10559                "\n"
10560                "private:\n"
10561                "#endif\n"
10562                "  int j;\n"
10563                "};\n",
10564                "struct foo {\n"
10565                "#ifdef FOO\n"
10566                "#endif\n"
10567                "private:\n"
10568                "  int i;\n"
10569                "#ifdef FOO\n"
10570                "private:\n"
10571                "#endif\n"
10572                "  int j;\n"
10573                "};\n",
10574                Style);
10575   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10576   EXPECT_EQ("struct foo {\n"
10577             "\n"
10578             "private:\n"
10579             "  void f() {}\n"
10580             "\n"
10581             "private:\n"
10582             "  int i;\n"
10583             "\n"
10584             "protected:\n"
10585             "  int j;\n"
10586             "};\n",
10587             format("struct foo {\n"
10588                    "\n"
10589                    "private:\n"
10590                    "  void f() {}\n"
10591                    "\n"
10592                    "private:\n"
10593                    "  int i;\n"
10594                    "\n"
10595                    "protected:\n"
10596                    "  int j;\n"
10597                    "};\n",
10598                    Style));
10599   verifyFormat("struct foo {\n"
10600                "private:\n"
10601                "  void f() {}\n"
10602                "private:\n"
10603                "  int i;\n"
10604                "protected:\n"
10605                "  int j;\n"
10606                "};\n",
10607                Style);
10608   EXPECT_EQ("struct foo { /* comment */\n"
10609             "\n"
10610             "private:\n"
10611             "  int i;\n"
10612             "  // comment\n"
10613             "\n"
10614             "private:\n"
10615             "  int j;\n"
10616             "};\n",
10617             format("struct foo { /* comment */\n"
10618                    "\n"
10619                    "private:\n"
10620                    "  int i;\n"
10621                    "  // comment\n"
10622                    "\n"
10623                    "private:\n"
10624                    "  int j;\n"
10625                    "};\n",
10626                    Style));
10627   verifyFormat("struct foo { /* comment */\n"
10628                "private:\n"
10629                "  int i;\n"
10630                "  // comment\n"
10631                "private:\n"
10632                "  int j;\n"
10633                "};\n",
10634                Style);
10635   EXPECT_EQ("struct foo {\n"
10636             "#ifdef FOO\n"
10637             "#endif\n"
10638             "\n"
10639             "private:\n"
10640             "  int i;\n"
10641             "#ifdef FOO\n"
10642             "\n"
10643             "private:\n"
10644             "#endif\n"
10645             "  int j;\n"
10646             "};\n",
10647             format("struct foo {\n"
10648                    "#ifdef FOO\n"
10649                    "#endif\n"
10650                    "\n"
10651                    "private:\n"
10652                    "  int i;\n"
10653                    "#ifdef FOO\n"
10654                    "\n"
10655                    "private:\n"
10656                    "#endif\n"
10657                    "  int j;\n"
10658                    "};\n",
10659                    Style));
10660   verifyFormat("struct foo {\n"
10661                "#ifdef FOO\n"
10662                "#endif\n"
10663                "private:\n"
10664                "  int i;\n"
10665                "#ifdef FOO\n"
10666                "private:\n"
10667                "#endif\n"
10668                "  int j;\n"
10669                "};\n",
10670                Style);
10671 
10672   FormatStyle NoEmptyLines = getLLVMStyle();
10673   NoEmptyLines.MaxEmptyLinesToKeep = 0;
10674   verifyFormat("struct foo {\n"
10675                "private:\n"
10676                "  void f() {}\n"
10677                "\n"
10678                "private:\n"
10679                "  int i;\n"
10680                "\n"
10681                "public:\n"
10682                "protected:\n"
10683                "  int j;\n"
10684                "};\n",
10685                NoEmptyLines);
10686 
10687   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10688   verifyFormat("struct foo {\n"
10689                "private:\n"
10690                "  void f() {}\n"
10691                "private:\n"
10692                "  int i;\n"
10693                "public:\n"
10694                "protected:\n"
10695                "  int j;\n"
10696                "};\n",
10697                NoEmptyLines);
10698 
10699   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10700   verifyFormat("struct foo {\n"
10701                "private:\n"
10702                "  void f() {}\n"
10703                "\n"
10704                "private:\n"
10705                "  int i;\n"
10706                "\n"
10707                "public:\n"
10708                "\n"
10709                "protected:\n"
10710                "  int j;\n"
10711                "};\n",
10712                NoEmptyLines);
10713 }
10714 
10715 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
10716 
10717   FormatStyle Style = getLLVMStyle();
10718   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
10719   verifyFormat("struct foo {\n"
10720                "private:\n"
10721                "  void f() {}\n"
10722                "\n"
10723                "private:\n"
10724                "  int i;\n"
10725                "\n"
10726                "protected:\n"
10727                "  int j;\n"
10728                "};\n",
10729                Style);
10730 
10731   // Check if lines are removed.
10732   verifyFormat("struct foo {\n"
10733                "private:\n"
10734                "  void f() {}\n"
10735                "\n"
10736                "private:\n"
10737                "  int i;\n"
10738                "\n"
10739                "protected:\n"
10740                "  int j;\n"
10741                "};\n",
10742                "struct foo {\n"
10743                "private:\n"
10744                "\n"
10745                "  void f() {}\n"
10746                "\n"
10747                "private:\n"
10748                "\n"
10749                "  int i;\n"
10750                "\n"
10751                "protected:\n"
10752                "\n"
10753                "  int j;\n"
10754                "};\n",
10755                Style);
10756 
10757   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10758   verifyFormat("struct foo {\n"
10759                "private:\n"
10760                "\n"
10761                "  void f() {}\n"
10762                "\n"
10763                "private:\n"
10764                "\n"
10765                "  int i;\n"
10766                "\n"
10767                "protected:\n"
10768                "\n"
10769                "  int j;\n"
10770                "};\n",
10771                Style);
10772 
10773   // Check if lines are added.
10774   verifyFormat("struct foo {\n"
10775                "private:\n"
10776                "\n"
10777                "  void f() {}\n"
10778                "\n"
10779                "private:\n"
10780                "\n"
10781                "  int i;\n"
10782                "\n"
10783                "protected:\n"
10784                "\n"
10785                "  int j;\n"
10786                "};\n",
10787                "struct foo {\n"
10788                "private:\n"
10789                "  void f() {}\n"
10790                "\n"
10791                "private:\n"
10792                "  int i;\n"
10793                "\n"
10794                "protected:\n"
10795                "  int j;\n"
10796                "};\n",
10797                Style);
10798 
10799   // Leave tests rely on the code layout, test::messUp can not be used.
10800   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10801   Style.MaxEmptyLinesToKeep = 0u;
10802   verifyFormat("struct foo {\n"
10803                "private:\n"
10804                "  void f() {}\n"
10805                "\n"
10806                "private:\n"
10807                "  int i;\n"
10808                "\n"
10809                "protected:\n"
10810                "  int j;\n"
10811                "};\n",
10812                Style);
10813 
10814   // Check if MaxEmptyLinesToKeep is respected.
10815   EXPECT_EQ("struct foo {\n"
10816             "private:\n"
10817             "  void f() {}\n"
10818             "\n"
10819             "private:\n"
10820             "  int i;\n"
10821             "\n"
10822             "protected:\n"
10823             "  int j;\n"
10824             "};\n",
10825             format("struct foo {\n"
10826                    "private:\n"
10827                    "\n\n\n"
10828                    "  void f() {}\n"
10829                    "\n"
10830                    "private:\n"
10831                    "\n\n\n"
10832                    "  int i;\n"
10833                    "\n"
10834                    "protected:\n"
10835                    "\n\n\n"
10836                    "  int j;\n"
10837                    "};\n",
10838                    Style));
10839 
10840   Style.MaxEmptyLinesToKeep = 1u;
10841   EXPECT_EQ("struct foo {\n"
10842             "private:\n"
10843             "\n"
10844             "  void f() {}\n"
10845             "\n"
10846             "private:\n"
10847             "\n"
10848             "  int i;\n"
10849             "\n"
10850             "protected:\n"
10851             "\n"
10852             "  int j;\n"
10853             "};\n",
10854             format("struct foo {\n"
10855                    "private:\n"
10856                    "\n"
10857                    "  void f() {}\n"
10858                    "\n"
10859                    "private:\n"
10860                    "\n"
10861                    "  int i;\n"
10862                    "\n"
10863                    "protected:\n"
10864                    "\n"
10865                    "  int j;\n"
10866                    "};\n",
10867                    Style));
10868   // Check if no lines are kept.
10869   EXPECT_EQ("struct foo {\n"
10870             "private:\n"
10871             "  void f() {}\n"
10872             "\n"
10873             "private:\n"
10874             "  int i;\n"
10875             "\n"
10876             "protected:\n"
10877             "  int j;\n"
10878             "};\n",
10879             format("struct foo {\n"
10880                    "private:\n"
10881                    "  void f() {}\n"
10882                    "\n"
10883                    "private:\n"
10884                    "  int i;\n"
10885                    "\n"
10886                    "protected:\n"
10887                    "  int j;\n"
10888                    "};\n",
10889                    Style));
10890   // Check if MaxEmptyLinesToKeep is respected.
10891   EXPECT_EQ("struct foo {\n"
10892             "private:\n"
10893             "\n"
10894             "  void f() {}\n"
10895             "\n"
10896             "private:\n"
10897             "\n"
10898             "  int i;\n"
10899             "\n"
10900             "protected:\n"
10901             "\n"
10902             "  int j;\n"
10903             "};\n",
10904             format("struct foo {\n"
10905                    "private:\n"
10906                    "\n\n\n"
10907                    "  void f() {}\n"
10908                    "\n"
10909                    "private:\n"
10910                    "\n\n\n"
10911                    "  int i;\n"
10912                    "\n"
10913                    "protected:\n"
10914                    "\n\n\n"
10915                    "  int j;\n"
10916                    "};\n",
10917                    Style));
10918 
10919   Style.MaxEmptyLinesToKeep = 10u;
10920   EXPECT_EQ("struct foo {\n"
10921             "private:\n"
10922             "\n\n\n"
10923             "  void f() {}\n"
10924             "\n"
10925             "private:\n"
10926             "\n\n\n"
10927             "  int i;\n"
10928             "\n"
10929             "protected:\n"
10930             "\n\n\n"
10931             "  int j;\n"
10932             "};\n",
10933             format("struct foo {\n"
10934                    "private:\n"
10935                    "\n\n\n"
10936                    "  void f() {}\n"
10937                    "\n"
10938                    "private:\n"
10939                    "\n\n\n"
10940                    "  int i;\n"
10941                    "\n"
10942                    "protected:\n"
10943                    "\n\n\n"
10944                    "  int j;\n"
10945                    "};\n",
10946                    Style));
10947 
10948   // Test with comments.
10949   Style = getLLVMStyle();
10950   verifyFormat("struct foo {\n"
10951                "private:\n"
10952                "  // comment\n"
10953                "  void f() {}\n"
10954                "\n"
10955                "private: /* comment */\n"
10956                "  int i;\n"
10957                "};\n",
10958                Style);
10959   verifyFormat("struct foo {\n"
10960                "private:\n"
10961                "  // comment\n"
10962                "  void f() {}\n"
10963                "\n"
10964                "private: /* comment */\n"
10965                "  int i;\n"
10966                "};\n",
10967                "struct foo {\n"
10968                "private:\n"
10969                "\n"
10970                "  // comment\n"
10971                "  void f() {}\n"
10972                "\n"
10973                "private: /* comment */\n"
10974                "\n"
10975                "  int i;\n"
10976                "};\n",
10977                Style);
10978 
10979   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10980   verifyFormat("struct foo {\n"
10981                "private:\n"
10982                "\n"
10983                "  // comment\n"
10984                "  void f() {}\n"
10985                "\n"
10986                "private: /* comment */\n"
10987                "\n"
10988                "  int i;\n"
10989                "};\n",
10990                "struct foo {\n"
10991                "private:\n"
10992                "  // comment\n"
10993                "  void f() {}\n"
10994                "\n"
10995                "private: /* comment */\n"
10996                "  int i;\n"
10997                "};\n",
10998                Style);
10999   verifyFormat("struct foo {\n"
11000                "private:\n"
11001                "\n"
11002                "  // comment\n"
11003                "  void f() {}\n"
11004                "\n"
11005                "private: /* comment */\n"
11006                "\n"
11007                "  int i;\n"
11008                "};\n",
11009                Style);
11010 
11011   // Test with preprocessor defines.
11012   Style = getLLVMStyle();
11013   verifyFormat("struct foo {\n"
11014                "private:\n"
11015                "#ifdef FOO\n"
11016                "#endif\n"
11017                "  void f() {}\n"
11018                "};\n",
11019                Style);
11020   verifyFormat("struct foo {\n"
11021                "private:\n"
11022                "#ifdef FOO\n"
11023                "#endif\n"
11024                "  void f() {}\n"
11025                "};\n",
11026                "struct foo {\n"
11027                "private:\n"
11028                "\n"
11029                "#ifdef FOO\n"
11030                "#endif\n"
11031                "  void f() {}\n"
11032                "};\n",
11033                Style);
11034 
11035   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11036   verifyFormat("struct foo {\n"
11037                "private:\n"
11038                "\n"
11039                "#ifdef FOO\n"
11040                "#endif\n"
11041                "  void f() {}\n"
11042                "};\n",
11043                "struct foo {\n"
11044                "private:\n"
11045                "#ifdef FOO\n"
11046                "#endif\n"
11047                "  void f() {}\n"
11048                "};\n",
11049                Style);
11050   verifyFormat("struct foo {\n"
11051                "private:\n"
11052                "\n"
11053                "#ifdef FOO\n"
11054                "#endif\n"
11055                "  void f() {}\n"
11056                "};\n",
11057                Style);
11058 }
11059 
11060 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11061   // Combined tests of EmptyLineAfterAccessModifier and
11062   // EmptyLineBeforeAccessModifier.
11063   FormatStyle Style = getLLVMStyle();
11064   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11065   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11066   verifyFormat("struct foo {\n"
11067                "private:\n"
11068                "\n"
11069                "protected:\n"
11070                "};\n",
11071                Style);
11072 
11073   Style.MaxEmptyLinesToKeep = 10u;
11074   // Both remove all new lines.
11075   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11076   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11077   verifyFormat("struct foo {\n"
11078                "private:\n"
11079                "protected:\n"
11080                "};\n",
11081                "struct foo {\n"
11082                "private:\n"
11083                "\n\n\n"
11084                "protected:\n"
11085                "};\n",
11086                Style);
11087 
11088   // Leave tests rely on the code layout, test::messUp can not be used.
11089   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11090   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11091   Style.MaxEmptyLinesToKeep = 10u;
11092   EXPECT_EQ("struct foo {\n"
11093             "private:\n"
11094             "\n\n\n"
11095             "protected:\n"
11096             "};\n",
11097             format("struct foo {\n"
11098                    "private:\n"
11099                    "\n\n\n"
11100                    "protected:\n"
11101                    "};\n",
11102                    Style));
11103   Style.MaxEmptyLinesToKeep = 3u;
11104   EXPECT_EQ("struct foo {\n"
11105             "private:\n"
11106             "\n\n\n"
11107             "protected:\n"
11108             "};\n",
11109             format("struct foo {\n"
11110                    "private:\n"
11111                    "\n\n\n"
11112                    "protected:\n"
11113                    "};\n",
11114                    Style));
11115   Style.MaxEmptyLinesToKeep = 1u;
11116   EXPECT_EQ("struct foo {\n"
11117             "private:\n"
11118             "\n\n\n"
11119             "protected:\n"
11120             "};\n",
11121             format("struct foo {\n"
11122                    "private:\n"
11123                    "\n\n\n"
11124                    "protected:\n"
11125                    "};\n",
11126                    Style)); // Based on new lines in original document and not
11127                             // on the setting.
11128 
11129   Style.MaxEmptyLinesToKeep = 10u;
11130   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11131   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11132   // Newlines are kept if they are greater than zero,
11133   // test::messUp removes all new lines which changes the logic
11134   EXPECT_EQ("struct foo {\n"
11135             "private:\n"
11136             "\n\n\n"
11137             "protected:\n"
11138             "};\n",
11139             format("struct foo {\n"
11140                    "private:\n"
11141                    "\n\n\n"
11142                    "protected:\n"
11143                    "};\n",
11144                    Style));
11145 
11146   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11147   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11148   // test::messUp removes all new lines which changes the logic
11149   EXPECT_EQ("struct foo {\n"
11150             "private:\n"
11151             "\n\n\n"
11152             "protected:\n"
11153             "};\n",
11154             format("struct foo {\n"
11155                    "private:\n"
11156                    "\n\n\n"
11157                    "protected:\n"
11158                    "};\n",
11159                    Style));
11160 
11161   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11162   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11163   EXPECT_EQ("struct foo {\n"
11164             "private:\n"
11165             "\n\n\n"
11166             "protected:\n"
11167             "};\n",
11168             format("struct foo {\n"
11169                    "private:\n"
11170                    "\n\n\n"
11171                    "protected:\n"
11172                    "};\n",
11173                    Style)); // test::messUp removes all new lines which changes
11174                             // the logic.
11175 
11176   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11177   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11178   verifyFormat("struct foo {\n"
11179                "private:\n"
11180                "protected:\n"
11181                "};\n",
11182                "struct foo {\n"
11183                "private:\n"
11184                "\n\n\n"
11185                "protected:\n"
11186                "};\n",
11187                Style);
11188 
11189   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11190   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11191   EXPECT_EQ("struct foo {\n"
11192             "private:\n"
11193             "\n\n\n"
11194             "protected:\n"
11195             "};\n",
11196             format("struct foo {\n"
11197                    "private:\n"
11198                    "\n\n\n"
11199                    "protected:\n"
11200                    "};\n",
11201                    Style)); // test::messUp removes all new lines which changes
11202                             // the logic.
11203 
11204   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11205   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11206   verifyFormat("struct foo {\n"
11207                "private:\n"
11208                "protected:\n"
11209                "};\n",
11210                "struct foo {\n"
11211                "private:\n"
11212                "\n\n\n"
11213                "protected:\n"
11214                "};\n",
11215                Style);
11216 
11217   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11218   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11219   verifyFormat("struct foo {\n"
11220                "private:\n"
11221                "protected:\n"
11222                "};\n",
11223                "struct foo {\n"
11224                "private:\n"
11225                "\n\n\n"
11226                "protected:\n"
11227                "};\n",
11228                Style);
11229 
11230   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11231   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11232   verifyFormat("struct foo {\n"
11233                "private:\n"
11234                "protected:\n"
11235                "};\n",
11236                "struct foo {\n"
11237                "private:\n"
11238                "\n\n\n"
11239                "protected:\n"
11240                "};\n",
11241                Style);
11242 
11243   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11244   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11245   verifyFormat("struct foo {\n"
11246                "private:\n"
11247                "protected:\n"
11248                "};\n",
11249                "struct foo {\n"
11250                "private:\n"
11251                "\n\n\n"
11252                "protected:\n"
11253                "};\n",
11254                Style);
11255 }
11256 
11257 TEST_F(FormatTest, FormatsArrays) {
11258   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11259                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11260   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11261                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11262   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11263                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11264   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11265                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11266   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11267                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11268   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11269                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11270                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11271   verifyFormat(
11272       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11273       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11274       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11275   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11276                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11277 
11278   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11279                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11280   verifyFormat(
11281       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11282       "                                  .aaaaaaa[0]\n"
11283       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11284   verifyFormat("a[::b::c];");
11285 
11286   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11287 
11288   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11289   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11290 }
11291 
11292 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11293   verifyFormat("(a)->b();");
11294   verifyFormat("--a;");
11295 }
11296 
11297 TEST_F(FormatTest, HandlesIncludeDirectives) {
11298   verifyFormat("#include <string>\n"
11299                "#include <a/b/c.h>\n"
11300                "#include \"a/b/string\"\n"
11301                "#include \"string.h\"\n"
11302                "#include \"string.h\"\n"
11303                "#include <a-a>\n"
11304                "#include < path with space >\n"
11305                "#include_next <test.h>"
11306                "#include \"abc.h\" // this is included for ABC\n"
11307                "#include \"some long include\" // with a comment\n"
11308                "#include \"some very long include path\"\n"
11309                "#include <some/very/long/include/path>\n",
11310                getLLVMStyleWithColumns(35));
11311   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11312   EXPECT_EQ("#include <a>", format("#include<a>"));
11313 
11314   verifyFormat("#import <string>");
11315   verifyFormat("#import <a/b/c.h>");
11316   verifyFormat("#import \"a/b/string\"");
11317   verifyFormat("#import \"string.h\"");
11318   verifyFormat("#import \"string.h\"");
11319   verifyFormat("#if __has_include(<strstream>)\n"
11320                "#include <strstream>\n"
11321                "#endif");
11322 
11323   verifyFormat("#define MY_IMPORT <a/b>");
11324 
11325   verifyFormat("#if __has_include(<a/b>)");
11326   verifyFormat("#if __has_include_next(<a/b>)");
11327   verifyFormat("#define F __has_include(<a/b>)");
11328   verifyFormat("#define F __has_include_next(<a/b>)");
11329 
11330   // Protocol buffer definition or missing "#".
11331   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
11332                getLLVMStyleWithColumns(30));
11333 
11334   FormatStyle Style = getLLVMStyle();
11335   Style.AlwaysBreakBeforeMultilineStrings = true;
11336   Style.ColumnLimit = 0;
11337   verifyFormat("#import \"abc.h\"", Style);
11338 
11339   // But 'import' might also be a regular C++ namespace.
11340   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11341                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11342 }
11343 
11344 //===----------------------------------------------------------------------===//
11345 // Error recovery tests.
11346 //===----------------------------------------------------------------------===//
11347 
11348 TEST_F(FormatTest, IncompleteParameterLists) {
11349   FormatStyle NoBinPacking = getLLVMStyle();
11350   NoBinPacking.BinPackParameters = false;
11351   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
11352                "                        double *min_x,\n"
11353                "                        double *max_x,\n"
11354                "                        double *min_y,\n"
11355                "                        double *max_y,\n"
11356                "                        double *min_z,\n"
11357                "                        double *max_z, ) {}",
11358                NoBinPacking);
11359 }
11360 
11361 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
11362   verifyFormat("void f() { return; }\n42");
11363   verifyFormat("void f() {\n"
11364                "  if (0)\n"
11365                "    return;\n"
11366                "}\n"
11367                "42");
11368   verifyFormat("void f() { return }\n42");
11369   verifyFormat("void f() {\n"
11370                "  if (0)\n"
11371                "    return\n"
11372                "}\n"
11373                "42");
11374 }
11375 
11376 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
11377   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
11378   EXPECT_EQ("void f() {\n"
11379             "  if (a)\n"
11380             "    return\n"
11381             "}",
11382             format("void  f  (  )  {  if  ( a )  return  }"));
11383   EXPECT_EQ("namespace N {\n"
11384             "void f()\n"
11385             "}",
11386             format("namespace  N  {  void f()  }"));
11387   EXPECT_EQ("namespace N {\n"
11388             "void f() {}\n"
11389             "void g()\n"
11390             "} // namespace N",
11391             format("namespace N  { void f( ) { } void g( ) }"));
11392 }
11393 
11394 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
11395   verifyFormat("int aaaaaaaa =\n"
11396                "    // Overlylongcomment\n"
11397                "    b;",
11398                getLLVMStyleWithColumns(20));
11399   verifyFormat("function(\n"
11400                "    ShortArgument,\n"
11401                "    LoooooooooooongArgument);\n",
11402                getLLVMStyleWithColumns(20));
11403 }
11404 
11405 TEST_F(FormatTest, IncorrectAccessSpecifier) {
11406   verifyFormat("public:");
11407   verifyFormat("class A {\n"
11408                "public\n"
11409                "  void f() {}\n"
11410                "};");
11411   verifyFormat("public\n"
11412                "int qwerty;");
11413   verifyFormat("public\n"
11414                "B {}");
11415   verifyFormat("public\n"
11416                "{}");
11417   verifyFormat("public\n"
11418                "B { int x; }");
11419 }
11420 
11421 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
11422   verifyFormat("{");
11423   verifyFormat("#})");
11424   verifyNoCrash("(/**/[:!] ?[).");
11425 }
11426 
11427 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
11428   // Found by oss-fuzz:
11429   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
11430   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
11431   Style.ColumnLimit = 60;
11432   verifyNoCrash(
11433       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
11434       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
11435       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
11436       Style);
11437 }
11438 
11439 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
11440   verifyFormat("do {\n}");
11441   verifyFormat("do {\n}\n"
11442                "f();");
11443   verifyFormat("do {\n}\n"
11444                "wheeee(fun);");
11445   verifyFormat("do {\n"
11446                "  f();\n"
11447                "}");
11448 }
11449 
11450 TEST_F(FormatTest, IncorrectCodeMissingParens) {
11451   verifyFormat("if {\n  foo;\n  foo();\n}");
11452   verifyFormat("switch {\n  foo;\n  foo();\n}");
11453   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
11454   verifyFormat("while {\n  foo;\n  foo();\n}");
11455   verifyFormat("do {\n  foo;\n  foo();\n} while;");
11456 }
11457 
11458 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
11459   verifyIncompleteFormat("namespace {\n"
11460                          "class Foo { Foo (\n"
11461                          "};\n"
11462                          "} // namespace");
11463 }
11464 
11465 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
11466   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
11467   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
11468   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
11469   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
11470 
11471   EXPECT_EQ("{\n"
11472             "  {\n"
11473             "    breakme(\n"
11474             "        qwe);\n"
11475             "  }\n",
11476             format("{\n"
11477                    "    {\n"
11478                    " breakme(qwe);\n"
11479                    "}\n",
11480                    getLLVMStyleWithColumns(10)));
11481 }
11482 
11483 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
11484   verifyFormat("int x = {\n"
11485                "    avariable,\n"
11486                "    b(alongervariable)};",
11487                getLLVMStyleWithColumns(25));
11488 }
11489 
11490 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
11491   verifyFormat("return (a)(b){1, 2, 3};");
11492 }
11493 
11494 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
11495   verifyFormat("vector<int> x{1, 2, 3, 4};");
11496   verifyFormat("vector<int> x{\n"
11497                "    1,\n"
11498                "    2,\n"
11499                "    3,\n"
11500                "    4,\n"
11501                "};");
11502   verifyFormat("vector<T> x{{}, {}, {}, {}};");
11503   verifyFormat("f({1, 2});");
11504   verifyFormat("auto v = Foo{-1};");
11505   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
11506   verifyFormat("Class::Class : member{1, 2, 3} {}");
11507   verifyFormat("new vector<int>{1, 2, 3};");
11508   verifyFormat("new int[3]{1, 2, 3};");
11509   verifyFormat("new int{1};");
11510   verifyFormat("return {arg1, arg2};");
11511   verifyFormat("return {arg1, SomeType{parameter}};");
11512   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
11513   verifyFormat("new T{arg1, arg2};");
11514   verifyFormat("f(MyMap[{composite, key}]);");
11515   verifyFormat("class Class {\n"
11516                "  T member = {arg1, arg2};\n"
11517                "};");
11518   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
11519   verifyFormat("const struct A a = {.a = 1, .b = 2};");
11520   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
11521   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
11522   verifyFormat("int a = std::is_integral<int>{} + 0;");
11523 
11524   verifyFormat("int foo(int i) { return fo1{}(i); }");
11525   verifyFormat("int foo(int i) { return fo1{}(i); }");
11526   verifyFormat("auto i = decltype(x){};");
11527   verifyFormat("auto i = typeof(x){};");
11528   verifyFormat("auto i = _Atomic(x){};");
11529   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
11530   verifyFormat("Node n{1, Node{1000}, //\n"
11531                "       2};");
11532   verifyFormat("Aaaa aaaaaaa{\n"
11533                "    {\n"
11534                "        aaaa,\n"
11535                "    },\n"
11536                "};");
11537   verifyFormat("class C : public D {\n"
11538                "  SomeClass SC{2};\n"
11539                "};");
11540   verifyFormat("class C : public A {\n"
11541                "  class D : public B {\n"
11542                "    void f() { int i{2}; }\n"
11543                "  };\n"
11544                "};");
11545   verifyFormat("#define A {a, a},");
11546   // Don't confuse braced list initializers with compound statements.
11547   verifyFormat(
11548       "class A {\n"
11549       "  A() : a{} {}\n"
11550       "  A(int b) : b(b) {}\n"
11551       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
11552       "  int a, b;\n"
11553       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
11554       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
11555       "{}\n"
11556       "};");
11557 
11558   // Avoid breaking between equal sign and opening brace
11559   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
11560   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
11561   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
11562                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
11563                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
11564                "     {\"ccccccccccccccccccccc\", 2}};",
11565                AvoidBreakingFirstArgument);
11566 
11567   // Binpacking only if there is no trailing comma
11568   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
11569                "                      cccccccccc, dddddddddd};",
11570                getLLVMStyleWithColumns(50));
11571   verifyFormat("const Aaaaaa aaaaa = {\n"
11572                "    aaaaaaaaaaa,\n"
11573                "    bbbbbbbbbbb,\n"
11574                "    ccccccccccc,\n"
11575                "    ddddddddddd,\n"
11576                "};",
11577                getLLVMStyleWithColumns(50));
11578 
11579   // Cases where distinguising braced lists and blocks is hard.
11580   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
11581   verifyFormat("void f() {\n"
11582                "  return; // comment\n"
11583                "}\n"
11584                "SomeType t;");
11585   verifyFormat("void f() {\n"
11586                "  if (a) {\n"
11587                "    f();\n"
11588                "  }\n"
11589                "}\n"
11590                "SomeType t;");
11591 
11592   // In combination with BinPackArguments = false.
11593   FormatStyle NoBinPacking = getLLVMStyle();
11594   NoBinPacking.BinPackArguments = false;
11595   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
11596                "                      bbbbb,\n"
11597                "                      ccccc,\n"
11598                "                      ddddd,\n"
11599                "                      eeeee,\n"
11600                "                      ffffff,\n"
11601                "                      ggggg,\n"
11602                "                      hhhhhh,\n"
11603                "                      iiiiii,\n"
11604                "                      jjjjjj,\n"
11605                "                      kkkkkk};",
11606                NoBinPacking);
11607   verifyFormat("const Aaaaaa aaaaa = {\n"
11608                "    aaaaa,\n"
11609                "    bbbbb,\n"
11610                "    ccccc,\n"
11611                "    ddddd,\n"
11612                "    eeeee,\n"
11613                "    ffffff,\n"
11614                "    ggggg,\n"
11615                "    hhhhhh,\n"
11616                "    iiiiii,\n"
11617                "    jjjjjj,\n"
11618                "    kkkkkk,\n"
11619                "};",
11620                NoBinPacking);
11621   verifyFormat(
11622       "const Aaaaaa aaaaa = {\n"
11623       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
11624       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
11625       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
11626       "};",
11627       NoBinPacking);
11628 
11629   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11630   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
11631             "    CDDDP83848_BMCR_REGISTER,\n"
11632             "    CDDDP83848_BMSR_REGISTER,\n"
11633             "    CDDDP83848_RBR_REGISTER};",
11634             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
11635                    "                                CDDDP83848_BMSR_REGISTER,\n"
11636                    "                                CDDDP83848_RBR_REGISTER};",
11637                    NoBinPacking));
11638 
11639   // FIXME: The alignment of these trailing comments might be bad. Then again,
11640   // this might be utterly useless in real code.
11641   verifyFormat("Constructor::Constructor()\n"
11642                "    : some_value{         //\n"
11643                "                 aaaaaaa, //\n"
11644                "                 bbbbbbb} {}");
11645 
11646   // In braced lists, the first comment is always assumed to belong to the
11647   // first element. Thus, it can be moved to the next or previous line as
11648   // appropriate.
11649   EXPECT_EQ("function({// First element:\n"
11650             "          1,\n"
11651             "          // Second element:\n"
11652             "          2});",
11653             format("function({\n"
11654                    "    // First element:\n"
11655                    "    1,\n"
11656                    "    // Second element:\n"
11657                    "    2});"));
11658   EXPECT_EQ("std::vector<int> MyNumbers{\n"
11659             "    // First element:\n"
11660             "    1,\n"
11661             "    // Second element:\n"
11662             "    2};",
11663             format("std::vector<int> MyNumbers{// First element:\n"
11664                    "                           1,\n"
11665                    "                           // Second element:\n"
11666                    "                           2};",
11667                    getLLVMStyleWithColumns(30)));
11668   // A trailing comma should still lead to an enforced line break and no
11669   // binpacking.
11670   EXPECT_EQ("vector<int> SomeVector = {\n"
11671             "    // aaa\n"
11672             "    1,\n"
11673             "    2,\n"
11674             "};",
11675             format("vector<int> SomeVector = { // aaa\n"
11676                    "    1, 2, };"));
11677 
11678   // C++11 brace initializer list l-braces should not be treated any differently
11679   // when breaking before lambda bodies is enabled
11680   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
11681   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
11682   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
11683   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
11684   verifyFormat(
11685       "std::runtime_error{\n"
11686       "    \"Long string which will force a break onto the next line...\"};",
11687       BreakBeforeLambdaBody);
11688 
11689   FormatStyle ExtraSpaces = getLLVMStyle();
11690   ExtraSpaces.Cpp11BracedListStyle = false;
11691   ExtraSpaces.ColumnLimit = 75;
11692   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
11693   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
11694   verifyFormat("f({ 1, 2 });", ExtraSpaces);
11695   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
11696   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
11697   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
11698   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
11699   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
11700   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
11701   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
11702   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
11703   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
11704   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
11705   verifyFormat("class Class {\n"
11706                "  T member = { arg1, arg2 };\n"
11707                "};",
11708                ExtraSpaces);
11709   verifyFormat(
11710       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11711       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
11712       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
11713       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
11714       ExtraSpaces);
11715   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
11716   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
11717                ExtraSpaces);
11718   verifyFormat(
11719       "someFunction(OtherParam,\n"
11720       "             BracedList{ // comment 1 (Forcing interesting break)\n"
11721       "                         param1, param2,\n"
11722       "                         // comment 2\n"
11723       "                         param3, param4 });",
11724       ExtraSpaces);
11725   verifyFormat(
11726       "std::this_thread::sleep_for(\n"
11727       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
11728       ExtraSpaces);
11729   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
11730                "    aaaaaaa,\n"
11731                "    aaaaaaaaaa,\n"
11732                "    aaaaa,\n"
11733                "    aaaaaaaaaaaaaaa,\n"
11734                "    aaa,\n"
11735                "    aaaaaaaaaa,\n"
11736                "    a,\n"
11737                "    aaaaaaaaaaaaaaaaaaaaa,\n"
11738                "    aaaaaaaaaaaa,\n"
11739                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
11740                "    aaaaaaa,\n"
11741                "    a};");
11742   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
11743   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
11744   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
11745 
11746   // Avoid breaking between initializer/equal sign and opening brace
11747   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
11748   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
11749                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11750                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11751                "  { \"ccccccccccccccccccccc\", 2 }\n"
11752                "};",
11753                ExtraSpaces);
11754   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
11755                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11756                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11757                "  { \"ccccccccccccccccccccc\", 2 }\n"
11758                "};",
11759                ExtraSpaces);
11760 
11761   FormatStyle SpaceBeforeBrace = getLLVMStyle();
11762   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
11763   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
11764   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
11765 
11766   FormatStyle SpaceBetweenBraces = getLLVMStyle();
11767   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
11768   SpaceBetweenBraces.SpacesInParentheses = true;
11769   SpaceBetweenBraces.SpacesInSquareBrackets = true;
11770   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
11771   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
11772   verifyFormat("vector< int > x{ // comment 1\n"
11773                "                 1, 2, 3, 4 };",
11774                SpaceBetweenBraces);
11775   SpaceBetweenBraces.ColumnLimit = 20;
11776   EXPECT_EQ("vector< int > x{\n"
11777             "    1, 2, 3, 4 };",
11778             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11779   SpaceBetweenBraces.ColumnLimit = 24;
11780   EXPECT_EQ("vector< int > x{ 1, 2,\n"
11781             "                 3, 4 };",
11782             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11783   EXPECT_EQ("vector< int > x{\n"
11784             "    1,\n"
11785             "    2,\n"
11786             "    3,\n"
11787             "    4,\n"
11788             "};",
11789             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
11790   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
11791   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
11792   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
11793 }
11794 
11795 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
11796   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11797                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11798                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11799                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11800                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11801                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
11802   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
11803                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11804                "                 1, 22, 333, 4444, 55555, //\n"
11805                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11806                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
11807   verifyFormat(
11808       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
11809       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
11810       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
11811       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11812       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11813       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11814       "                 7777777};");
11815   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11816                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11817                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
11818   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11819                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11820                "    // Separating comment.\n"
11821                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
11822   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11823                "    // Leading comment\n"
11824                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11825                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
11826   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11827                "                 1, 1, 1, 1};",
11828                getLLVMStyleWithColumns(39));
11829   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11830                "                 1, 1, 1, 1};",
11831                getLLVMStyleWithColumns(38));
11832   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
11833                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
11834                getLLVMStyleWithColumns(43));
11835   verifyFormat(
11836       "static unsigned SomeValues[10][3] = {\n"
11837       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
11838       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
11839   verifyFormat("static auto fields = new vector<string>{\n"
11840                "    \"aaaaaaaaaaaaa\",\n"
11841                "    \"aaaaaaaaaaaaa\",\n"
11842                "    \"aaaaaaaaaaaa\",\n"
11843                "    \"aaaaaaaaaaaaaa\",\n"
11844                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11845                "    \"aaaaaaaaaaaa\",\n"
11846                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11847                "};");
11848   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
11849   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
11850                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
11851                "                 3, cccccccccccccccccccccc};",
11852                getLLVMStyleWithColumns(60));
11853 
11854   // Trailing commas.
11855   verifyFormat("vector<int> x = {\n"
11856                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
11857                "};",
11858                getLLVMStyleWithColumns(39));
11859   verifyFormat("vector<int> x = {\n"
11860                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
11861                "};",
11862                getLLVMStyleWithColumns(39));
11863   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11864                "                 1, 1, 1, 1,\n"
11865                "                 /**/ /**/};",
11866                getLLVMStyleWithColumns(39));
11867 
11868   // Trailing comment in the first line.
11869   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
11870                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
11871                "    111111111,  222222222,  3333333333,  444444444,  //\n"
11872                "    11111111,   22222222,   333333333,   44444444};");
11873   // Trailing comment in the last line.
11874   verifyFormat("int aaaaa[] = {\n"
11875                "    1, 2, 3, // comment\n"
11876                "    4, 5, 6  // comment\n"
11877                "};");
11878 
11879   // With nested lists, we should either format one item per line or all nested
11880   // lists one on line.
11881   // FIXME: For some nested lists, we can do better.
11882   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
11883                "        {aaaaaaaaaaaaaaaaaaa},\n"
11884                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
11885                "        {aaaaaaaaaaaaaaaaa}};",
11886                getLLVMStyleWithColumns(60));
11887   verifyFormat(
11888       "SomeStruct my_struct_array = {\n"
11889       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
11890       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
11891       "    {aaa, aaa},\n"
11892       "    {aaa, aaa},\n"
11893       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
11894       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
11895       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
11896 
11897   // No column layout should be used here.
11898   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
11899                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
11900 
11901   verifyNoCrash("a<,");
11902 
11903   // No braced initializer here.
11904   verifyFormat("void f() {\n"
11905                "  struct Dummy {};\n"
11906                "  f(v);\n"
11907                "}");
11908 
11909   // Long lists should be formatted in columns even if they are nested.
11910   verifyFormat(
11911       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11912       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11913       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11914       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11915       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11916       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
11917 
11918   // Allow "single-column" layout even if that violates the column limit. There
11919   // isn't going to be a better way.
11920   verifyFormat("std::vector<int> a = {\n"
11921                "    aaaaaaaa,\n"
11922                "    aaaaaaaa,\n"
11923                "    aaaaaaaa,\n"
11924                "    aaaaaaaa,\n"
11925                "    aaaaaaaaaa,\n"
11926                "    aaaaaaaa,\n"
11927                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
11928                getLLVMStyleWithColumns(30));
11929   verifyFormat("vector<int> aaaa = {\n"
11930                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11931                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11932                "    aaaaaa.aaaaaaa,\n"
11933                "    aaaaaa.aaaaaaa,\n"
11934                "    aaaaaa.aaaaaaa,\n"
11935                "    aaaaaa.aaaaaaa,\n"
11936                "};");
11937 
11938   // Don't create hanging lists.
11939   verifyFormat("someFunction(Param, {List1, List2,\n"
11940                "                     List3});",
11941                getLLVMStyleWithColumns(35));
11942   verifyFormat("someFunction(Param, Param,\n"
11943                "             {List1, List2,\n"
11944                "              List3});",
11945                getLLVMStyleWithColumns(35));
11946   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
11947                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
11948 }
11949 
11950 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
11951   FormatStyle DoNotMerge = getLLVMStyle();
11952   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
11953 
11954   verifyFormat("void f() { return 42; }");
11955   verifyFormat("void f() {\n"
11956                "  return 42;\n"
11957                "}",
11958                DoNotMerge);
11959   verifyFormat("void f() {\n"
11960                "  // Comment\n"
11961                "}");
11962   verifyFormat("{\n"
11963                "#error {\n"
11964                "  int a;\n"
11965                "}");
11966   verifyFormat("{\n"
11967                "  int a;\n"
11968                "#error {\n"
11969                "}");
11970   verifyFormat("void f() {} // comment");
11971   verifyFormat("void f() { int a; } // comment");
11972   verifyFormat("void f() {\n"
11973                "} // comment",
11974                DoNotMerge);
11975   verifyFormat("void f() {\n"
11976                "  int a;\n"
11977                "} // comment",
11978                DoNotMerge);
11979   verifyFormat("void f() {\n"
11980                "} // comment",
11981                getLLVMStyleWithColumns(15));
11982 
11983   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
11984   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
11985 
11986   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
11987   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
11988   verifyFormat("class C {\n"
11989                "  C()\n"
11990                "      : iiiiiiii(nullptr),\n"
11991                "        kkkkkkk(nullptr),\n"
11992                "        mmmmmmm(nullptr),\n"
11993                "        nnnnnnn(nullptr) {}\n"
11994                "};",
11995                getGoogleStyle());
11996 
11997   FormatStyle NoColumnLimit = getLLVMStyle();
11998   NoColumnLimit.ColumnLimit = 0;
11999   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12000   EXPECT_EQ("class C {\n"
12001             "  A() : b(0) {}\n"
12002             "};",
12003             format("class C{A():b(0){}};", NoColumnLimit));
12004   EXPECT_EQ("A()\n"
12005             "    : b(0) {\n"
12006             "}",
12007             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12008 
12009   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12010   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12011       FormatStyle::SFS_None;
12012   EXPECT_EQ("A()\n"
12013             "    : b(0) {\n"
12014             "}",
12015             format("A():b(0){}", DoNotMergeNoColumnLimit));
12016   EXPECT_EQ("A()\n"
12017             "    : b(0) {\n"
12018             "}",
12019             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12020 
12021   verifyFormat("#define A          \\\n"
12022                "  void f() {       \\\n"
12023                "    int i;         \\\n"
12024                "  }",
12025                getLLVMStyleWithColumns(20));
12026   verifyFormat("#define A           \\\n"
12027                "  void f() { int i; }",
12028                getLLVMStyleWithColumns(21));
12029   verifyFormat("#define A            \\\n"
12030                "  void f() {         \\\n"
12031                "    int i;           \\\n"
12032                "  }                  \\\n"
12033                "  int j;",
12034                getLLVMStyleWithColumns(22));
12035   verifyFormat("#define A             \\\n"
12036                "  void f() { int i; } \\\n"
12037                "  int j;",
12038                getLLVMStyleWithColumns(23));
12039 }
12040 
12041 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12042   FormatStyle MergeEmptyOnly = getLLVMStyle();
12043   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12044   verifyFormat("class C {\n"
12045                "  int f() {}\n"
12046                "};",
12047                MergeEmptyOnly);
12048   verifyFormat("class C {\n"
12049                "  int f() {\n"
12050                "    return 42;\n"
12051                "  }\n"
12052                "};",
12053                MergeEmptyOnly);
12054   verifyFormat("int f() {}", MergeEmptyOnly);
12055   verifyFormat("int f() {\n"
12056                "  return 42;\n"
12057                "}",
12058                MergeEmptyOnly);
12059 
12060   // Also verify behavior when BraceWrapping.AfterFunction = true
12061   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12062   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12063   verifyFormat("int f() {}", MergeEmptyOnly);
12064   verifyFormat("class C {\n"
12065                "  int f() {}\n"
12066                "};",
12067                MergeEmptyOnly);
12068 }
12069 
12070 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12071   FormatStyle MergeInlineOnly = getLLVMStyle();
12072   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12073   verifyFormat("class C {\n"
12074                "  int f() { return 42; }\n"
12075                "};",
12076                MergeInlineOnly);
12077   verifyFormat("int f() {\n"
12078                "  return 42;\n"
12079                "}",
12080                MergeInlineOnly);
12081 
12082   // SFS_Inline implies SFS_Empty
12083   verifyFormat("class C {\n"
12084                "  int f() {}\n"
12085                "};",
12086                MergeInlineOnly);
12087   verifyFormat("int f() {}", MergeInlineOnly);
12088 
12089   // Also verify behavior when BraceWrapping.AfterFunction = true
12090   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12091   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12092   verifyFormat("class C {\n"
12093                "  int f() { return 42; }\n"
12094                "};",
12095                MergeInlineOnly);
12096   verifyFormat("int f()\n"
12097                "{\n"
12098                "  return 42;\n"
12099                "}",
12100                MergeInlineOnly);
12101 
12102   // SFS_Inline implies SFS_Empty
12103   verifyFormat("int f() {}", MergeInlineOnly);
12104   verifyFormat("class C {\n"
12105                "  int f() {}\n"
12106                "};",
12107                MergeInlineOnly);
12108 }
12109 
12110 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12111   FormatStyle MergeInlineOnly = getLLVMStyle();
12112   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12113       FormatStyle::SFS_InlineOnly;
12114   verifyFormat("class C {\n"
12115                "  int f() { return 42; }\n"
12116                "};",
12117                MergeInlineOnly);
12118   verifyFormat("int f() {\n"
12119                "  return 42;\n"
12120                "}",
12121                MergeInlineOnly);
12122 
12123   // SFS_InlineOnly does not imply SFS_Empty
12124   verifyFormat("class C {\n"
12125                "  int f() {}\n"
12126                "};",
12127                MergeInlineOnly);
12128   verifyFormat("int f() {\n"
12129                "}",
12130                MergeInlineOnly);
12131 
12132   // Also verify behavior when BraceWrapping.AfterFunction = true
12133   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12134   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12135   verifyFormat("class C {\n"
12136                "  int f() { return 42; }\n"
12137                "};",
12138                MergeInlineOnly);
12139   verifyFormat("int f()\n"
12140                "{\n"
12141                "  return 42;\n"
12142                "}",
12143                MergeInlineOnly);
12144 
12145   // SFS_InlineOnly does not imply SFS_Empty
12146   verifyFormat("int f()\n"
12147                "{\n"
12148                "}",
12149                MergeInlineOnly);
12150   verifyFormat("class C {\n"
12151                "  int f() {}\n"
12152                "};",
12153                MergeInlineOnly);
12154 }
12155 
12156 TEST_F(FormatTest, SplitEmptyFunction) {
12157   FormatStyle Style = getLLVMStyle();
12158   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12159   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12160   Style.BraceWrapping.AfterFunction = true;
12161   Style.BraceWrapping.SplitEmptyFunction = false;
12162   Style.ColumnLimit = 40;
12163 
12164   verifyFormat("int f()\n"
12165                "{}",
12166                Style);
12167   verifyFormat("int f()\n"
12168                "{\n"
12169                "  return 42;\n"
12170                "}",
12171                Style);
12172   verifyFormat("int f()\n"
12173                "{\n"
12174                "  // some comment\n"
12175                "}",
12176                Style);
12177 
12178   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12179   verifyFormat("int f() {}", Style);
12180   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12181                "{}",
12182                Style);
12183   verifyFormat("int f()\n"
12184                "{\n"
12185                "  return 0;\n"
12186                "}",
12187                Style);
12188 
12189   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12190   verifyFormat("class Foo {\n"
12191                "  int f() {}\n"
12192                "};\n",
12193                Style);
12194   verifyFormat("class Foo {\n"
12195                "  int f() { return 0; }\n"
12196                "};\n",
12197                Style);
12198   verifyFormat("class Foo {\n"
12199                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12200                "  {}\n"
12201                "};\n",
12202                Style);
12203   verifyFormat("class Foo {\n"
12204                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12205                "  {\n"
12206                "    return 0;\n"
12207                "  }\n"
12208                "};\n",
12209                Style);
12210 
12211   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12212   verifyFormat("int f() {}", Style);
12213   verifyFormat("int f() { return 0; }", Style);
12214   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12215                "{}",
12216                Style);
12217   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12218                "{\n"
12219                "  return 0;\n"
12220                "}",
12221                Style);
12222 }
12223 
12224 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12225   FormatStyle Style = getLLVMStyle();
12226   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12227   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12228   Style.BraceWrapping.AfterFunction = true;
12229   Style.BraceWrapping.SplitEmptyFunction = true;
12230   Style.BraceWrapping.SplitEmptyRecord = false;
12231   Style.ColumnLimit = 40;
12232 
12233   verifyFormat("class C {};", Style);
12234   verifyFormat("struct C {};", Style);
12235   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12236                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12237                "{\n"
12238                "}",
12239                Style);
12240   verifyFormat("class C {\n"
12241                "  C()\n"
12242                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12243                "        bbbbbbbbbbbbbbbbbbb()\n"
12244                "  {\n"
12245                "  }\n"
12246                "  void\n"
12247                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12248                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12249                "  {\n"
12250                "  }\n"
12251                "};",
12252                Style);
12253 }
12254 
12255 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12256   FormatStyle Style = getLLVMStyle();
12257   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12258   verifyFormat("#ifdef A\n"
12259                "int f() {}\n"
12260                "#else\n"
12261                "int g() {}\n"
12262                "#endif",
12263                Style);
12264 }
12265 
12266 TEST_F(FormatTest, SplitEmptyClass) {
12267   FormatStyle Style = getLLVMStyle();
12268   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12269   Style.BraceWrapping.AfterClass = true;
12270   Style.BraceWrapping.SplitEmptyRecord = false;
12271 
12272   verifyFormat("class Foo\n"
12273                "{};",
12274                Style);
12275   verifyFormat("/* something */ class Foo\n"
12276                "{};",
12277                Style);
12278   verifyFormat("template <typename X> class Foo\n"
12279                "{};",
12280                Style);
12281   verifyFormat("class Foo\n"
12282                "{\n"
12283                "  Foo();\n"
12284                "};",
12285                Style);
12286   verifyFormat("typedef class Foo\n"
12287                "{\n"
12288                "} Foo_t;",
12289                Style);
12290 
12291   Style.BraceWrapping.SplitEmptyRecord = true;
12292   Style.BraceWrapping.AfterStruct = true;
12293   verifyFormat("class rep\n"
12294                "{\n"
12295                "};",
12296                Style);
12297   verifyFormat("struct rep\n"
12298                "{\n"
12299                "};",
12300                Style);
12301   verifyFormat("template <typename T> class rep\n"
12302                "{\n"
12303                "};",
12304                Style);
12305   verifyFormat("template <typename T> struct rep\n"
12306                "{\n"
12307                "};",
12308                Style);
12309   verifyFormat("class rep\n"
12310                "{\n"
12311                "  int x;\n"
12312                "};",
12313                Style);
12314   verifyFormat("struct rep\n"
12315                "{\n"
12316                "  int x;\n"
12317                "};",
12318                Style);
12319   verifyFormat("template <typename T> class rep\n"
12320                "{\n"
12321                "  int x;\n"
12322                "};",
12323                Style);
12324   verifyFormat("template <typename T> struct rep\n"
12325                "{\n"
12326                "  int x;\n"
12327                "};",
12328                Style);
12329   verifyFormat("template <typename T> class rep // Foo\n"
12330                "{\n"
12331                "  int x;\n"
12332                "};",
12333                Style);
12334   verifyFormat("template <typename T> struct rep // Bar\n"
12335                "{\n"
12336                "  int x;\n"
12337                "};",
12338                Style);
12339 
12340   verifyFormat("template <typename T> class rep<T>\n"
12341                "{\n"
12342                "  int x;\n"
12343                "};",
12344                Style);
12345 
12346   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12347                "{\n"
12348                "  int x;\n"
12349                "};",
12350                Style);
12351   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12352                "{\n"
12353                "};",
12354                Style);
12355 
12356   verifyFormat("#include \"stdint.h\"\n"
12357                "namespace rep {}",
12358                Style);
12359   verifyFormat("#include <stdint.h>\n"
12360                "namespace rep {}",
12361                Style);
12362   verifyFormat("#include <stdint.h>\n"
12363                "namespace rep {}",
12364                "#include <stdint.h>\n"
12365                "namespace rep {\n"
12366                "\n"
12367                "\n"
12368                "}",
12369                Style);
12370 }
12371 
12372 TEST_F(FormatTest, SplitEmptyStruct) {
12373   FormatStyle Style = getLLVMStyle();
12374   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12375   Style.BraceWrapping.AfterStruct = true;
12376   Style.BraceWrapping.SplitEmptyRecord = false;
12377 
12378   verifyFormat("struct Foo\n"
12379                "{};",
12380                Style);
12381   verifyFormat("/* something */ struct Foo\n"
12382                "{};",
12383                Style);
12384   verifyFormat("template <typename X> struct Foo\n"
12385                "{};",
12386                Style);
12387   verifyFormat("struct Foo\n"
12388                "{\n"
12389                "  Foo();\n"
12390                "};",
12391                Style);
12392   verifyFormat("typedef struct Foo\n"
12393                "{\n"
12394                "} Foo_t;",
12395                Style);
12396   // typedef struct Bar {} Bar_t;
12397 }
12398 
12399 TEST_F(FormatTest, SplitEmptyUnion) {
12400   FormatStyle Style = getLLVMStyle();
12401   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12402   Style.BraceWrapping.AfterUnion = true;
12403   Style.BraceWrapping.SplitEmptyRecord = false;
12404 
12405   verifyFormat("union Foo\n"
12406                "{};",
12407                Style);
12408   verifyFormat("/* something */ union Foo\n"
12409                "{};",
12410                Style);
12411   verifyFormat("union Foo\n"
12412                "{\n"
12413                "  A,\n"
12414                "};",
12415                Style);
12416   verifyFormat("typedef union Foo\n"
12417                "{\n"
12418                "} Foo_t;",
12419                Style);
12420 }
12421 
12422 TEST_F(FormatTest, SplitEmptyNamespace) {
12423   FormatStyle Style = getLLVMStyle();
12424   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12425   Style.BraceWrapping.AfterNamespace = true;
12426   Style.BraceWrapping.SplitEmptyNamespace = false;
12427 
12428   verifyFormat("namespace Foo\n"
12429                "{};",
12430                Style);
12431   verifyFormat("/* something */ namespace Foo\n"
12432                "{};",
12433                Style);
12434   verifyFormat("inline namespace Foo\n"
12435                "{};",
12436                Style);
12437   verifyFormat("/* something */ inline namespace Foo\n"
12438                "{};",
12439                Style);
12440   verifyFormat("export namespace Foo\n"
12441                "{};",
12442                Style);
12443   verifyFormat("namespace Foo\n"
12444                "{\n"
12445                "void Bar();\n"
12446                "};",
12447                Style);
12448 }
12449 
12450 TEST_F(FormatTest, NeverMergeShortRecords) {
12451   FormatStyle Style = getLLVMStyle();
12452 
12453   verifyFormat("class Foo {\n"
12454                "  Foo();\n"
12455                "};",
12456                Style);
12457   verifyFormat("typedef class Foo {\n"
12458                "  Foo();\n"
12459                "} Foo_t;",
12460                Style);
12461   verifyFormat("struct Foo {\n"
12462                "  Foo();\n"
12463                "};",
12464                Style);
12465   verifyFormat("typedef struct Foo {\n"
12466                "  Foo();\n"
12467                "} Foo_t;",
12468                Style);
12469   verifyFormat("union Foo {\n"
12470                "  A,\n"
12471                "};",
12472                Style);
12473   verifyFormat("typedef union Foo {\n"
12474                "  A,\n"
12475                "} Foo_t;",
12476                Style);
12477   verifyFormat("namespace Foo {\n"
12478                "void Bar();\n"
12479                "};",
12480                Style);
12481 
12482   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12483   Style.BraceWrapping.AfterClass = true;
12484   Style.BraceWrapping.AfterStruct = true;
12485   Style.BraceWrapping.AfterUnion = true;
12486   Style.BraceWrapping.AfterNamespace = true;
12487   verifyFormat("class Foo\n"
12488                "{\n"
12489                "  Foo();\n"
12490                "};",
12491                Style);
12492   verifyFormat("typedef class Foo\n"
12493                "{\n"
12494                "  Foo();\n"
12495                "} Foo_t;",
12496                Style);
12497   verifyFormat("struct Foo\n"
12498                "{\n"
12499                "  Foo();\n"
12500                "};",
12501                Style);
12502   verifyFormat("typedef struct Foo\n"
12503                "{\n"
12504                "  Foo();\n"
12505                "} Foo_t;",
12506                Style);
12507   verifyFormat("union Foo\n"
12508                "{\n"
12509                "  A,\n"
12510                "};",
12511                Style);
12512   verifyFormat("typedef union Foo\n"
12513                "{\n"
12514                "  A,\n"
12515                "} Foo_t;",
12516                Style);
12517   verifyFormat("namespace Foo\n"
12518                "{\n"
12519                "void Bar();\n"
12520                "};",
12521                Style);
12522 }
12523 
12524 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
12525   // Elaborate type variable declarations.
12526   verifyFormat("struct foo a = {bar};\nint n;");
12527   verifyFormat("class foo a = {bar};\nint n;");
12528   verifyFormat("union foo a = {bar};\nint n;");
12529 
12530   // Elaborate types inside function definitions.
12531   verifyFormat("struct foo f() {}\nint n;");
12532   verifyFormat("class foo f() {}\nint n;");
12533   verifyFormat("union foo f() {}\nint n;");
12534 
12535   // Templates.
12536   verifyFormat("template <class X> void f() {}\nint n;");
12537   verifyFormat("template <struct X> void f() {}\nint n;");
12538   verifyFormat("template <union X> void f() {}\nint n;");
12539 
12540   // Actual definitions...
12541   verifyFormat("struct {\n} n;");
12542   verifyFormat(
12543       "template <template <class T, class Y>, class Z> class X {\n} n;");
12544   verifyFormat("union Z {\n  int n;\n} x;");
12545   verifyFormat("class MACRO Z {\n} n;");
12546   verifyFormat("class MACRO(X) Z {\n} n;");
12547   verifyFormat("class __attribute__(X) Z {\n} n;");
12548   verifyFormat("class __declspec(X) Z {\n} n;");
12549   verifyFormat("class A##B##C {\n} n;");
12550   verifyFormat("class alignas(16) Z {\n} n;");
12551   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
12552   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
12553 
12554   // Redefinition from nested context:
12555   verifyFormat("class A::B::C {\n} n;");
12556 
12557   // Template definitions.
12558   verifyFormat(
12559       "template <typename F>\n"
12560       "Matcher(const Matcher<F> &Other,\n"
12561       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
12562       "                             !is_same<F, T>::value>::type * = 0)\n"
12563       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
12564 
12565   // FIXME: This is still incorrectly handled at the formatter side.
12566   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
12567   verifyFormat("int i = SomeFunction(a<b, a> b);");
12568 
12569   // FIXME:
12570   // This now gets parsed incorrectly as class definition.
12571   // verifyFormat("class A<int> f() {\n}\nint n;");
12572 
12573   // Elaborate types where incorrectly parsing the structural element would
12574   // break the indent.
12575   verifyFormat("if (true)\n"
12576                "  class X x;\n"
12577                "else\n"
12578                "  f();\n");
12579 
12580   // This is simply incomplete. Formatting is not important, but must not crash.
12581   verifyFormat("class A:");
12582 }
12583 
12584 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
12585   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
12586             format("#error Leave     all         white!!!!! space* alone!\n"));
12587   EXPECT_EQ(
12588       "#warning Leave     all         white!!!!! space* alone!\n",
12589       format("#warning Leave     all         white!!!!! space* alone!\n"));
12590   EXPECT_EQ("#error 1", format("  #  error   1"));
12591   EXPECT_EQ("#warning 1", format("  #  warning 1"));
12592 }
12593 
12594 TEST_F(FormatTest, FormatHashIfExpressions) {
12595   verifyFormat("#if AAAA && BBBB");
12596   verifyFormat("#if (AAAA && BBBB)");
12597   verifyFormat("#elif (AAAA && BBBB)");
12598   // FIXME: Come up with a better indentation for #elif.
12599   verifyFormat(
12600       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
12601       "    defined(BBBBBBBB)\n"
12602       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
12603       "    defined(BBBBBBBB)\n"
12604       "#endif",
12605       getLLVMStyleWithColumns(65));
12606 }
12607 
12608 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
12609   FormatStyle AllowsMergedIf = getGoogleStyle();
12610   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
12611       FormatStyle::SIS_WithoutElse;
12612   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
12613   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
12614   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
12615   EXPECT_EQ("if (true) return 42;",
12616             format("if (true)\nreturn 42;", AllowsMergedIf));
12617   FormatStyle ShortMergedIf = AllowsMergedIf;
12618   ShortMergedIf.ColumnLimit = 25;
12619   verifyFormat("#define A \\\n"
12620                "  if (true) return 42;",
12621                ShortMergedIf);
12622   verifyFormat("#define A \\\n"
12623                "  f();    \\\n"
12624                "  if (true)\n"
12625                "#define B",
12626                ShortMergedIf);
12627   verifyFormat("#define A \\\n"
12628                "  f();    \\\n"
12629                "  if (true)\n"
12630                "g();",
12631                ShortMergedIf);
12632   verifyFormat("{\n"
12633                "#ifdef A\n"
12634                "  // Comment\n"
12635                "  if (true) continue;\n"
12636                "#endif\n"
12637                "  // Comment\n"
12638                "  if (true) continue;\n"
12639                "}",
12640                ShortMergedIf);
12641   ShortMergedIf.ColumnLimit = 33;
12642   verifyFormat("#define A \\\n"
12643                "  if constexpr (true) return 42;",
12644                ShortMergedIf);
12645   verifyFormat("#define A \\\n"
12646                "  if CONSTEXPR (true) return 42;",
12647                ShortMergedIf);
12648   ShortMergedIf.ColumnLimit = 29;
12649   verifyFormat("#define A                   \\\n"
12650                "  if (aaaaaaaaaa) return 1; \\\n"
12651                "  return 2;",
12652                ShortMergedIf);
12653   ShortMergedIf.ColumnLimit = 28;
12654   verifyFormat("#define A         \\\n"
12655                "  if (aaaaaaaaaa) \\\n"
12656                "    return 1;     \\\n"
12657                "  return 2;",
12658                ShortMergedIf);
12659   verifyFormat("#define A                \\\n"
12660                "  if constexpr (aaaaaaa) \\\n"
12661                "    return 1;            \\\n"
12662                "  return 2;",
12663                ShortMergedIf);
12664   verifyFormat("#define A                \\\n"
12665                "  if CONSTEXPR (aaaaaaa) \\\n"
12666                "    return 1;            \\\n"
12667                "  return 2;",
12668                ShortMergedIf);
12669 }
12670 
12671 TEST_F(FormatTest, FormatStarDependingOnContext) {
12672   verifyFormat("void f(int *a);");
12673   verifyFormat("void f() { f(fint * b); }");
12674   verifyFormat("class A {\n  void f(int *a);\n};");
12675   verifyFormat("class A {\n  int *a;\n};");
12676   verifyFormat("namespace a {\n"
12677                "namespace b {\n"
12678                "class A {\n"
12679                "  void f() {}\n"
12680                "  int *a;\n"
12681                "};\n"
12682                "} // namespace b\n"
12683                "} // namespace a");
12684 }
12685 
12686 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
12687   verifyFormat("while");
12688   verifyFormat("operator");
12689 }
12690 
12691 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
12692   // This code would be painfully slow to format if we didn't skip it.
12693   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
12694                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12695                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12696                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12697                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12698                    "A(1, 1)\n"
12699                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
12700                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12701                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12702                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12703                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12704                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12705                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12706                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12707                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12708                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
12709   // Deeply nested part is untouched, rest is formatted.
12710   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
12711             format(std::string("int    i;\n") + Code + "int    j;\n",
12712                    getLLVMStyle(), SC_ExpectIncomplete));
12713 }
12714 
12715 //===----------------------------------------------------------------------===//
12716 // Objective-C tests.
12717 //===----------------------------------------------------------------------===//
12718 
12719 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
12720   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
12721   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
12722             format("-(NSUInteger)indexOfObject:(id)anObject;"));
12723   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
12724   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
12725   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
12726             format("-(NSInteger)Method3:(id)anObject;"));
12727   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
12728             format("-(NSInteger)Method4:(id)anObject;"));
12729   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
12730             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
12731   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
12732             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
12733   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12734             "forAllCells:(BOOL)flag;",
12735             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12736                    "forAllCells:(BOOL)flag;"));
12737 
12738   // Very long objectiveC method declaration.
12739   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
12740                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
12741   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
12742                "                    inRange:(NSRange)range\n"
12743                "                   outRange:(NSRange)out_range\n"
12744                "                  outRange1:(NSRange)out_range1\n"
12745                "                  outRange2:(NSRange)out_range2\n"
12746                "                  outRange3:(NSRange)out_range3\n"
12747                "                  outRange4:(NSRange)out_range4\n"
12748                "                  outRange5:(NSRange)out_range5\n"
12749                "                  outRange6:(NSRange)out_range6\n"
12750                "                  outRange7:(NSRange)out_range7\n"
12751                "                  outRange8:(NSRange)out_range8\n"
12752                "                  outRange9:(NSRange)out_range9;");
12753 
12754   // When the function name has to be wrapped.
12755   FormatStyle Style = getLLVMStyle();
12756   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
12757   // and always indents instead.
12758   Style.IndentWrappedFunctionNames = false;
12759   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12760                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
12761                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
12762                "}",
12763                Style);
12764   Style.IndentWrappedFunctionNames = true;
12765   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12766                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
12767                "               anotherName:(NSString)dddddddddddddd {\n"
12768                "}",
12769                Style);
12770 
12771   verifyFormat("- (int)sum:(vector<int>)numbers;");
12772   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
12773   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
12774   // protocol lists (but not for template classes):
12775   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
12776 
12777   verifyFormat("- (int (*)())foo:(int (*)())f;");
12778   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
12779 
12780   // If there's no return type (very rare in practice!), LLVM and Google style
12781   // agree.
12782   verifyFormat("- foo;");
12783   verifyFormat("- foo:(int)f;");
12784   verifyGoogleFormat("- foo:(int)foo;");
12785 }
12786 
12787 TEST_F(FormatTest, BreaksStringLiterals) {
12788   EXPECT_EQ("\"some text \"\n"
12789             "\"other\";",
12790             format("\"some text other\";", getLLVMStyleWithColumns(12)));
12791   EXPECT_EQ("\"some text \"\n"
12792             "\"other\";",
12793             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
12794   EXPECT_EQ(
12795       "#define A  \\\n"
12796       "  \"some \"  \\\n"
12797       "  \"text \"  \\\n"
12798       "  \"other\";",
12799       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
12800   EXPECT_EQ(
12801       "#define A  \\\n"
12802       "  \"so \"    \\\n"
12803       "  \"text \"  \\\n"
12804       "  \"other\";",
12805       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
12806 
12807   EXPECT_EQ("\"some text\"",
12808             format("\"some text\"", getLLVMStyleWithColumns(1)));
12809   EXPECT_EQ("\"some text\"",
12810             format("\"some text\"", getLLVMStyleWithColumns(11)));
12811   EXPECT_EQ("\"some \"\n"
12812             "\"text\"",
12813             format("\"some text\"", getLLVMStyleWithColumns(10)));
12814   EXPECT_EQ("\"some \"\n"
12815             "\"text\"",
12816             format("\"some text\"", getLLVMStyleWithColumns(7)));
12817   EXPECT_EQ("\"some\"\n"
12818             "\" tex\"\n"
12819             "\"t\"",
12820             format("\"some text\"", getLLVMStyleWithColumns(6)));
12821   EXPECT_EQ("\"some\"\n"
12822             "\" tex\"\n"
12823             "\" and\"",
12824             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
12825   EXPECT_EQ("\"some\"\n"
12826             "\"/tex\"\n"
12827             "\"/and\"",
12828             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
12829 
12830   EXPECT_EQ("variable =\n"
12831             "    \"long string \"\n"
12832             "    \"literal\";",
12833             format("variable = \"long string literal\";",
12834                    getLLVMStyleWithColumns(20)));
12835 
12836   EXPECT_EQ("variable = f(\n"
12837             "    \"long string \"\n"
12838             "    \"literal\",\n"
12839             "    short,\n"
12840             "    loooooooooooooooooooong);",
12841             format("variable = f(\"long string literal\", short, "
12842                    "loooooooooooooooooooong);",
12843                    getLLVMStyleWithColumns(20)));
12844 
12845   EXPECT_EQ(
12846       "f(g(\"long string \"\n"
12847       "    \"literal\"),\n"
12848       "  b);",
12849       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
12850   EXPECT_EQ("f(g(\"long string \"\n"
12851             "    \"literal\",\n"
12852             "    a),\n"
12853             "  b);",
12854             format("f(g(\"long string literal\", a), b);",
12855                    getLLVMStyleWithColumns(20)));
12856   EXPECT_EQ(
12857       "f(\"one two\".split(\n"
12858       "    variable));",
12859       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
12860   EXPECT_EQ("f(\"one two three four five six \"\n"
12861             "  \"seven\".split(\n"
12862             "      really_looooong_variable));",
12863             format("f(\"one two three four five six seven\"."
12864                    "split(really_looooong_variable));",
12865                    getLLVMStyleWithColumns(33)));
12866 
12867   EXPECT_EQ("f(\"some \"\n"
12868             "  \"text\",\n"
12869             "  other);",
12870             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
12871 
12872   // Only break as a last resort.
12873   verifyFormat(
12874       "aaaaaaaaaaaaaaaaaaaa(\n"
12875       "    aaaaaaaaaaaaaaaaaaaa,\n"
12876       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
12877 
12878   EXPECT_EQ("\"splitmea\"\n"
12879             "\"trandomp\"\n"
12880             "\"oint\"",
12881             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
12882 
12883   EXPECT_EQ("\"split/\"\n"
12884             "\"pathat/\"\n"
12885             "\"slashes\"",
12886             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
12887 
12888   EXPECT_EQ("\"split/\"\n"
12889             "\"pathat/\"\n"
12890             "\"slashes\"",
12891             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
12892   EXPECT_EQ("\"split at \"\n"
12893             "\"spaces/at/\"\n"
12894             "\"slashes.at.any$\"\n"
12895             "\"non-alphanumeric%\"\n"
12896             "\"1111111111characte\"\n"
12897             "\"rs\"",
12898             format("\"split at "
12899                    "spaces/at/"
12900                    "slashes.at."
12901                    "any$non-"
12902                    "alphanumeric%"
12903                    "1111111111characte"
12904                    "rs\"",
12905                    getLLVMStyleWithColumns(20)));
12906 
12907   // Verify that splitting the strings understands
12908   // Style::AlwaysBreakBeforeMultilineStrings.
12909   EXPECT_EQ("aaaaaaaaaaaa(\n"
12910             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
12911             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
12912             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
12913                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
12914                    "aaaaaaaaaaaaaaaaaaaaaa\");",
12915                    getGoogleStyle()));
12916   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12917             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
12918             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
12919                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
12920                    "aaaaaaaaaaaaaaaaaaaaaa\";",
12921                    getGoogleStyle()));
12922   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12923             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
12924             format("llvm::outs() << "
12925                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
12926                    "aaaaaaaaaaaaaaaaaaa\";"));
12927   EXPECT_EQ("ffff(\n"
12928             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12929             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
12930             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
12931                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
12932                    getGoogleStyle()));
12933 
12934   FormatStyle Style = getLLVMStyleWithColumns(12);
12935   Style.BreakStringLiterals = false;
12936   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
12937 
12938   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
12939   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
12940   EXPECT_EQ("#define A \\\n"
12941             "  \"some \" \\\n"
12942             "  \"text \" \\\n"
12943             "  \"other\";",
12944             format("#define A \"some text other\";", AlignLeft));
12945 }
12946 
12947 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
12948   EXPECT_EQ("C a = \"some more \"\n"
12949             "      \"text\";",
12950             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
12951 }
12952 
12953 TEST_F(FormatTest, FullyRemoveEmptyLines) {
12954   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
12955   NoEmptyLines.MaxEmptyLinesToKeep = 0;
12956   EXPECT_EQ("int i = a(b());",
12957             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
12958 }
12959 
12960 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
12961   EXPECT_EQ(
12962       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12963       "(\n"
12964       "    \"x\t\");",
12965       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12966              "aaaaaaa("
12967              "\"x\t\");"));
12968 }
12969 
12970 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
12971   EXPECT_EQ(
12972       "u8\"utf8 string \"\n"
12973       "u8\"literal\";",
12974       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
12975   EXPECT_EQ(
12976       "u\"utf16 string \"\n"
12977       "u\"literal\";",
12978       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
12979   EXPECT_EQ(
12980       "U\"utf32 string \"\n"
12981       "U\"literal\";",
12982       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
12983   EXPECT_EQ("L\"wide string \"\n"
12984             "L\"literal\";",
12985             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
12986   EXPECT_EQ("@\"NSString \"\n"
12987             "@\"literal\";",
12988             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
12989   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
12990 
12991   // This input makes clang-format try to split the incomplete unicode escape
12992   // sequence, which used to lead to a crasher.
12993   verifyNoCrash(
12994       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
12995       getLLVMStyleWithColumns(60));
12996 }
12997 
12998 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
12999   FormatStyle Style = getGoogleStyleWithColumns(15);
13000   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13001   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13002   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13003   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13004   EXPECT_EQ("u8R\"x(raw literal)x\";",
13005             format("u8R\"x(raw literal)x\";", Style));
13006 }
13007 
13008 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13009   FormatStyle Style = getLLVMStyleWithColumns(20);
13010   EXPECT_EQ(
13011       "_T(\"aaaaaaaaaaaaaa\")\n"
13012       "_T(\"aaaaaaaaaaaaaa\")\n"
13013       "_T(\"aaaaaaaaaaaa\")",
13014       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13015   EXPECT_EQ("f(x,\n"
13016             "  _T(\"aaaaaaaaaaaa\")\n"
13017             "  _T(\"aaa\"),\n"
13018             "  z);",
13019             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13020 
13021   // FIXME: Handle embedded spaces in one iteration.
13022   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13023   //            "_T(\"aaaaaaaaaaaaa\")\n"
13024   //            "_T(\"aaaaaaaaaaaaa\")\n"
13025   //            "_T(\"a\")",
13026   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13027   //                   getLLVMStyleWithColumns(20)));
13028   EXPECT_EQ(
13029       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13030       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13031   EXPECT_EQ("f(\n"
13032             "#if !TEST\n"
13033             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13034             "#endif\n"
13035             ");",
13036             format("f(\n"
13037                    "#if !TEST\n"
13038                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13039                    "#endif\n"
13040                    ");"));
13041   EXPECT_EQ("f(\n"
13042             "\n"
13043             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13044             format("f(\n"
13045                    "\n"
13046                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13047   // Regression test for accessing tokens past the end of a vector in the
13048   // TokenLexer.
13049   verifyNoCrash(R"(_T(
13050 "
13051 )
13052 )");
13053 }
13054 
13055 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13056   // In a function call with two operands, the second can be broken with no line
13057   // break before it.
13058   EXPECT_EQ(
13059       "func(a, \"long long \"\n"
13060       "        \"long long\");",
13061       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13062   // In a function call with three operands, the second must be broken with a
13063   // line break before it.
13064   EXPECT_EQ("func(a,\n"
13065             "     \"long long long \"\n"
13066             "     \"long\",\n"
13067             "     c);",
13068             format("func(a, \"long long long long\", c);",
13069                    getLLVMStyleWithColumns(24)));
13070   // In a function call with three operands, the third must be broken with a
13071   // line break before it.
13072   EXPECT_EQ("func(a, b,\n"
13073             "     \"long long long \"\n"
13074             "     \"long\");",
13075             format("func(a, b, \"long long long long\");",
13076                    getLLVMStyleWithColumns(24)));
13077   // In a function call with three operands, both the second and the third must
13078   // be broken with a line break before them.
13079   EXPECT_EQ("func(a,\n"
13080             "     \"long long long \"\n"
13081             "     \"long\",\n"
13082             "     \"long long long \"\n"
13083             "     \"long\");",
13084             format("func(a, \"long long long long\", \"long long long long\");",
13085                    getLLVMStyleWithColumns(24)));
13086   // In a chain of << with two operands, the second can be broken with no line
13087   // break before it.
13088   EXPECT_EQ("a << \"line line \"\n"
13089             "     \"line\";",
13090             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13091   // In a chain of << with three operands, the second can be broken with no line
13092   // break before it.
13093   EXPECT_EQ(
13094       "abcde << \"line \"\n"
13095       "         \"line line\"\n"
13096       "      << c;",
13097       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13098   // In a chain of << with three operands, the third must be broken with a line
13099   // break before it.
13100   EXPECT_EQ(
13101       "a << b\n"
13102       "  << \"line line \"\n"
13103       "     \"line\";",
13104       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13105   // In a chain of << with three operands, the second can be broken with no line
13106   // break before it and the third must be broken with a line break before it.
13107   EXPECT_EQ("abcd << \"line line \"\n"
13108             "        \"line\"\n"
13109             "     << \"line line \"\n"
13110             "        \"line\";",
13111             format("abcd << \"line line line\" << \"line line line\";",
13112                    getLLVMStyleWithColumns(20)));
13113   // In a chain of binary operators with two operands, the second can be broken
13114   // with no line break before it.
13115   EXPECT_EQ(
13116       "abcd + \"line line \"\n"
13117       "       \"line line\";",
13118       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13119   // In a chain of binary operators with three operands, the second must be
13120   // broken with a line break before it.
13121   EXPECT_EQ("abcd +\n"
13122             "    \"line line \"\n"
13123             "    \"line line\" +\n"
13124             "    e;",
13125             format("abcd + \"line line line line\" + e;",
13126                    getLLVMStyleWithColumns(20)));
13127   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13128   // the first must be broken with a line break before it.
13129   FormatStyle Style = getLLVMStyleWithColumns(25);
13130   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13131   EXPECT_EQ("someFunction(\n"
13132             "    \"long long long \"\n"
13133             "    \"long\",\n"
13134             "    a);",
13135             format("someFunction(\"long long long long\", a);", Style));
13136 }
13137 
13138 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13139   EXPECT_EQ(
13140       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13141       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13142       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13143       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13144              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13145              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13146 }
13147 
13148 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13149   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13150             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13151   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13152             "multiline raw string literal xxxxxxxxxxxxxx\n"
13153             ")x\",\n"
13154             "              a),\n"
13155             "            b);",
13156             format("fffffffffff(g(R\"x(\n"
13157                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13158                    ")x\", a), b);",
13159                    getGoogleStyleWithColumns(20)));
13160   EXPECT_EQ("fffffffffff(\n"
13161             "    g(R\"x(qqq\n"
13162             "multiline raw string literal xxxxxxxxxxxxxx\n"
13163             ")x\",\n"
13164             "      a),\n"
13165             "    b);",
13166             format("fffffffffff(g(R\"x(qqq\n"
13167                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13168                    ")x\", a), b);",
13169                    getGoogleStyleWithColumns(20)));
13170 
13171   EXPECT_EQ("fffffffffff(R\"x(\n"
13172             "multiline raw string literal xxxxxxxxxxxxxx\n"
13173             ")x\");",
13174             format("fffffffffff(R\"x(\n"
13175                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13176                    ")x\");",
13177                    getGoogleStyleWithColumns(20)));
13178   EXPECT_EQ("fffffffffff(R\"x(\n"
13179             "multiline raw string literal xxxxxxxxxxxxxx\n"
13180             ")x\" + bbbbbb);",
13181             format("fffffffffff(R\"x(\n"
13182                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13183                    ")x\" +   bbbbbb);",
13184                    getGoogleStyleWithColumns(20)));
13185   EXPECT_EQ("fffffffffff(\n"
13186             "    R\"x(\n"
13187             "multiline raw string literal xxxxxxxxxxxxxx\n"
13188             ")x\" +\n"
13189             "    bbbbbb);",
13190             format("fffffffffff(\n"
13191                    " R\"x(\n"
13192                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13193                    ")x\" + bbbbbb);",
13194                    getGoogleStyleWithColumns(20)));
13195   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13196             format("fffffffffff(\n"
13197                    " R\"(single line raw string)\" + bbbbbb);"));
13198 }
13199 
13200 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13201   verifyFormat("string a = \"unterminated;");
13202   EXPECT_EQ("function(\"unterminated,\n"
13203             "         OtherParameter);",
13204             format("function(  \"unterminated,\n"
13205                    "    OtherParameter);"));
13206 }
13207 
13208 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13209   FormatStyle Style = getLLVMStyle();
13210   Style.Standard = FormatStyle::LS_Cpp03;
13211   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13212             format("#define x(_a) printf(\"foo\"_a);", Style));
13213 }
13214 
13215 TEST_F(FormatTest, CppLexVersion) {
13216   FormatStyle Style = getLLVMStyle();
13217   // Formatting of x * y differs if x is a type.
13218   verifyFormat("void foo() { MACRO(a * b); }", Style);
13219   verifyFormat("void foo() { MACRO(int *b); }", Style);
13220 
13221   // LLVM style uses latest lexer.
13222   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13223   Style.Standard = FormatStyle::LS_Cpp17;
13224   // But in c++17, char8_t isn't a keyword.
13225   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13226 }
13227 
13228 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13229 
13230 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13231   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13232             "             \"ddeeefff\");",
13233             format("someFunction(\"aaabbbcccdddeeefff\");",
13234                    getLLVMStyleWithColumns(25)));
13235   EXPECT_EQ("someFunction1234567890(\n"
13236             "    \"aaabbbcccdddeeefff\");",
13237             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13238                    getLLVMStyleWithColumns(26)));
13239   EXPECT_EQ("someFunction1234567890(\n"
13240             "    \"aaabbbcccdddeeeff\"\n"
13241             "    \"f\");",
13242             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13243                    getLLVMStyleWithColumns(25)));
13244   EXPECT_EQ("someFunction1234567890(\n"
13245             "    \"aaabbbcccdddeeeff\"\n"
13246             "    \"f\");",
13247             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13248                    getLLVMStyleWithColumns(24)));
13249   EXPECT_EQ("someFunction(\n"
13250             "    \"aaabbbcc ddde \"\n"
13251             "    \"efff\");",
13252             format("someFunction(\"aaabbbcc ddde efff\");",
13253                    getLLVMStyleWithColumns(25)));
13254   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13255             "             \"ddeeefff\");",
13256             format("someFunction(\"aaabbbccc ddeeefff\");",
13257                    getLLVMStyleWithColumns(25)));
13258   EXPECT_EQ("someFunction1234567890(\n"
13259             "    \"aaabb \"\n"
13260             "    \"cccdddeeefff\");",
13261             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13262                    getLLVMStyleWithColumns(25)));
13263   EXPECT_EQ("#define A          \\\n"
13264             "  string s =       \\\n"
13265             "      \"123456789\"  \\\n"
13266             "      \"0\";         \\\n"
13267             "  int i;",
13268             format("#define A string s = \"1234567890\"; int i;",
13269                    getLLVMStyleWithColumns(20)));
13270   EXPECT_EQ("someFunction(\n"
13271             "    \"aaabbbcc \"\n"
13272             "    \"dddeeefff\");",
13273             format("someFunction(\"aaabbbcc dddeeefff\");",
13274                    getLLVMStyleWithColumns(25)));
13275 }
13276 
13277 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13278   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13279   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13280   EXPECT_EQ("\"test\"\n"
13281             "\"\\n\"",
13282             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13283   EXPECT_EQ("\"tes\\\\\"\n"
13284             "\"n\"",
13285             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
13286   EXPECT_EQ("\"\\\\\\\\\"\n"
13287             "\"\\n\"",
13288             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
13289   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
13290   EXPECT_EQ("\"\\uff01\"\n"
13291             "\"test\"",
13292             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
13293   EXPECT_EQ("\"\\Uff01ff02\"",
13294             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
13295   EXPECT_EQ("\"\\x000000000001\"\n"
13296             "\"next\"",
13297             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
13298   EXPECT_EQ("\"\\x000000000001next\"",
13299             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
13300   EXPECT_EQ("\"\\x000000000001\"",
13301             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
13302   EXPECT_EQ("\"test\"\n"
13303             "\"\\000000\"\n"
13304             "\"000001\"",
13305             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
13306   EXPECT_EQ("\"test\\000\"\n"
13307             "\"00000000\"\n"
13308             "\"1\"",
13309             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
13310 }
13311 
13312 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
13313   verifyFormat("void f() {\n"
13314                "  return g() {}\n"
13315                "  void h() {}");
13316   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
13317                "g();\n"
13318                "}");
13319 }
13320 
13321 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
13322   verifyFormat(
13323       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
13324 }
13325 
13326 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
13327   verifyFormat("class X {\n"
13328                "  void f() {\n"
13329                "  }\n"
13330                "};",
13331                getLLVMStyleWithColumns(12));
13332 }
13333 
13334 TEST_F(FormatTest, ConfigurableIndentWidth) {
13335   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
13336   EightIndent.IndentWidth = 8;
13337   EightIndent.ContinuationIndentWidth = 8;
13338   verifyFormat("void f() {\n"
13339                "        someFunction();\n"
13340                "        if (true) {\n"
13341                "                f();\n"
13342                "        }\n"
13343                "}",
13344                EightIndent);
13345   verifyFormat("class X {\n"
13346                "        void f() {\n"
13347                "        }\n"
13348                "};",
13349                EightIndent);
13350   verifyFormat("int x[] = {\n"
13351                "        call(),\n"
13352                "        call()};",
13353                EightIndent);
13354 }
13355 
13356 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
13357   verifyFormat("double\n"
13358                "f();",
13359                getLLVMStyleWithColumns(8));
13360 }
13361 
13362 TEST_F(FormatTest, ConfigurableUseOfTab) {
13363   FormatStyle Tab = getLLVMStyleWithColumns(42);
13364   Tab.IndentWidth = 8;
13365   Tab.UseTab = FormatStyle::UT_Always;
13366   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13367 
13368   EXPECT_EQ("if (aaaaaaaa && // q\n"
13369             "    bb)\t\t// w\n"
13370             "\t;",
13371             format("if (aaaaaaaa &&// q\n"
13372                    "bb)// w\n"
13373                    ";",
13374                    Tab));
13375   EXPECT_EQ("if (aaa && bbb) // w\n"
13376             "\t;",
13377             format("if(aaa&&bbb)// w\n"
13378                    ";",
13379                    Tab));
13380 
13381   verifyFormat("class X {\n"
13382                "\tvoid f() {\n"
13383                "\t\tsomeFunction(parameter1,\n"
13384                "\t\t\t     parameter2);\n"
13385                "\t}\n"
13386                "};",
13387                Tab);
13388   verifyFormat("#define A                        \\\n"
13389                "\tvoid f() {               \\\n"
13390                "\t\tsomeFunction(    \\\n"
13391                "\t\t    parameter1,  \\\n"
13392                "\t\t    parameter2); \\\n"
13393                "\t}",
13394                Tab);
13395   verifyFormat("int a;\t      // x\n"
13396                "int bbbbbbbb; // x\n",
13397                Tab);
13398 
13399   Tab.TabWidth = 4;
13400   Tab.IndentWidth = 8;
13401   verifyFormat("class TabWidth4Indent8 {\n"
13402                "\t\tvoid f() {\n"
13403                "\t\t\t\tsomeFunction(parameter1,\n"
13404                "\t\t\t\t\t\t\t parameter2);\n"
13405                "\t\t}\n"
13406                "};",
13407                Tab);
13408 
13409   Tab.TabWidth = 4;
13410   Tab.IndentWidth = 4;
13411   verifyFormat("class TabWidth4Indent4 {\n"
13412                "\tvoid f() {\n"
13413                "\t\tsomeFunction(parameter1,\n"
13414                "\t\t\t\t\t parameter2);\n"
13415                "\t}\n"
13416                "};",
13417                Tab);
13418 
13419   Tab.TabWidth = 8;
13420   Tab.IndentWidth = 4;
13421   verifyFormat("class TabWidth8Indent4 {\n"
13422                "    void f() {\n"
13423                "\tsomeFunction(parameter1,\n"
13424                "\t\t     parameter2);\n"
13425                "    }\n"
13426                "};",
13427                Tab);
13428 
13429   Tab.TabWidth = 8;
13430   Tab.IndentWidth = 8;
13431   EXPECT_EQ("/*\n"
13432             "\t      a\t\tcomment\n"
13433             "\t      in multiple lines\n"
13434             "       */",
13435             format("   /*\t \t \n"
13436                    " \t \t a\t\tcomment\t \t\n"
13437                    " \t \t in multiple lines\t\n"
13438                    " \t  */",
13439                    Tab));
13440 
13441   Tab.UseTab = FormatStyle::UT_ForIndentation;
13442   verifyFormat("{\n"
13443                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13444                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13445                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13446                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13447                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13448                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13449                "};",
13450                Tab);
13451   verifyFormat("enum AA {\n"
13452                "\ta1, // Force multiple lines\n"
13453                "\ta2,\n"
13454                "\ta3\n"
13455                "};",
13456                Tab);
13457   EXPECT_EQ("if (aaaaaaaa && // q\n"
13458             "    bb)         // w\n"
13459             "\t;",
13460             format("if (aaaaaaaa &&// q\n"
13461                    "bb)// w\n"
13462                    ";",
13463                    Tab));
13464   verifyFormat("class X {\n"
13465                "\tvoid f() {\n"
13466                "\t\tsomeFunction(parameter1,\n"
13467                "\t\t             parameter2);\n"
13468                "\t}\n"
13469                "};",
13470                Tab);
13471   verifyFormat("{\n"
13472                "\tQ(\n"
13473                "\t    {\n"
13474                "\t\t    int a;\n"
13475                "\t\t    someFunction(aaaaaaaa,\n"
13476                "\t\t                 bbbbbbb);\n"
13477                "\t    },\n"
13478                "\t    p);\n"
13479                "}",
13480                Tab);
13481   EXPECT_EQ("{\n"
13482             "\t/* aaaa\n"
13483             "\t   bbbb */\n"
13484             "}",
13485             format("{\n"
13486                    "/* aaaa\n"
13487                    "   bbbb */\n"
13488                    "}",
13489                    Tab));
13490   EXPECT_EQ("{\n"
13491             "\t/*\n"
13492             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13493             "\t  bbbbbbbbbbbbb\n"
13494             "\t*/\n"
13495             "}",
13496             format("{\n"
13497                    "/*\n"
13498                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13499                    "*/\n"
13500                    "}",
13501                    Tab));
13502   EXPECT_EQ("{\n"
13503             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13504             "\t// bbbbbbbbbbbbb\n"
13505             "}",
13506             format("{\n"
13507                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13508                    "}",
13509                    Tab));
13510   EXPECT_EQ("{\n"
13511             "\t/*\n"
13512             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13513             "\t  bbbbbbbbbbbbb\n"
13514             "\t*/\n"
13515             "}",
13516             format("{\n"
13517                    "\t/*\n"
13518                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13519                    "\t*/\n"
13520                    "}",
13521                    Tab));
13522   EXPECT_EQ("{\n"
13523             "\t/*\n"
13524             "\n"
13525             "\t*/\n"
13526             "}",
13527             format("{\n"
13528                    "\t/*\n"
13529                    "\n"
13530                    "\t*/\n"
13531                    "}",
13532                    Tab));
13533   EXPECT_EQ("{\n"
13534             "\t/*\n"
13535             " asdf\n"
13536             "\t*/\n"
13537             "}",
13538             format("{\n"
13539                    "\t/*\n"
13540                    " asdf\n"
13541                    "\t*/\n"
13542                    "}",
13543                    Tab));
13544 
13545   verifyFormat("void f() {\n"
13546                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
13547                "\t            : bbbbbbbbbbbbbbbbbb\n"
13548                "}",
13549                Tab);
13550   FormatStyle TabNoBreak = Tab;
13551   TabNoBreak.BreakBeforeTernaryOperators = false;
13552   verifyFormat("void f() {\n"
13553                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
13554                "\t              bbbbbbbbbbbbbbbbbb\n"
13555                "}",
13556                TabNoBreak);
13557   verifyFormat("void f() {\n"
13558                "\treturn true ?\n"
13559                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
13560                "\t           bbbbbbbbbbbbbbbbbbbb\n"
13561                "}",
13562                TabNoBreak);
13563 
13564   Tab.UseTab = FormatStyle::UT_Never;
13565   EXPECT_EQ("/*\n"
13566             "              a\t\tcomment\n"
13567             "              in multiple lines\n"
13568             "       */",
13569             format("   /*\t \t \n"
13570                    " \t \t a\t\tcomment\t \t\n"
13571                    " \t \t in multiple lines\t\n"
13572                    " \t  */",
13573                    Tab));
13574   EXPECT_EQ("/* some\n"
13575             "   comment */",
13576             format(" \t \t /* some\n"
13577                    " \t \t    comment */",
13578                    Tab));
13579   EXPECT_EQ("int a; /* some\n"
13580             "   comment */",
13581             format(" \t \t int a; /* some\n"
13582                    " \t \t    comment */",
13583                    Tab));
13584 
13585   EXPECT_EQ("int a; /* some\n"
13586             "comment */",
13587             format(" \t \t int\ta; /* some\n"
13588                    " \t \t    comment */",
13589                    Tab));
13590   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13591             "    comment */",
13592             format(" \t \t f(\"\t\t\"); /* some\n"
13593                    " \t \t    comment */",
13594                    Tab));
13595   EXPECT_EQ("{\n"
13596             "        /*\n"
13597             "         * Comment\n"
13598             "         */\n"
13599             "        int i;\n"
13600             "}",
13601             format("{\n"
13602                    "\t/*\n"
13603                    "\t * Comment\n"
13604                    "\t */\n"
13605                    "\t int i;\n"
13606                    "}",
13607                    Tab));
13608 
13609   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13610   Tab.TabWidth = 8;
13611   Tab.IndentWidth = 8;
13612   EXPECT_EQ("if (aaaaaaaa && // q\n"
13613             "    bb)         // w\n"
13614             "\t;",
13615             format("if (aaaaaaaa &&// q\n"
13616                    "bb)// w\n"
13617                    ";",
13618                    Tab));
13619   EXPECT_EQ("if (aaa && bbb) // w\n"
13620             "\t;",
13621             format("if(aaa&&bbb)// w\n"
13622                    ";",
13623                    Tab));
13624   verifyFormat("class X {\n"
13625                "\tvoid f() {\n"
13626                "\t\tsomeFunction(parameter1,\n"
13627                "\t\t\t     parameter2);\n"
13628                "\t}\n"
13629                "};",
13630                Tab);
13631   verifyFormat("#define A                        \\\n"
13632                "\tvoid f() {               \\\n"
13633                "\t\tsomeFunction(    \\\n"
13634                "\t\t    parameter1,  \\\n"
13635                "\t\t    parameter2); \\\n"
13636                "\t}",
13637                Tab);
13638   Tab.TabWidth = 4;
13639   Tab.IndentWidth = 8;
13640   verifyFormat("class TabWidth4Indent8 {\n"
13641                "\t\tvoid f() {\n"
13642                "\t\t\t\tsomeFunction(parameter1,\n"
13643                "\t\t\t\t\t\t\t parameter2);\n"
13644                "\t\t}\n"
13645                "};",
13646                Tab);
13647   Tab.TabWidth = 4;
13648   Tab.IndentWidth = 4;
13649   verifyFormat("class TabWidth4Indent4 {\n"
13650                "\tvoid f() {\n"
13651                "\t\tsomeFunction(parameter1,\n"
13652                "\t\t\t\t\t parameter2);\n"
13653                "\t}\n"
13654                "};",
13655                Tab);
13656   Tab.TabWidth = 8;
13657   Tab.IndentWidth = 4;
13658   verifyFormat("class TabWidth8Indent4 {\n"
13659                "    void f() {\n"
13660                "\tsomeFunction(parameter1,\n"
13661                "\t\t     parameter2);\n"
13662                "    }\n"
13663                "};",
13664                Tab);
13665   Tab.TabWidth = 8;
13666   Tab.IndentWidth = 8;
13667   EXPECT_EQ("/*\n"
13668             "\t      a\t\tcomment\n"
13669             "\t      in multiple lines\n"
13670             "       */",
13671             format("   /*\t \t \n"
13672                    " \t \t a\t\tcomment\t \t\n"
13673                    " \t \t in multiple lines\t\n"
13674                    " \t  */",
13675                    Tab));
13676   verifyFormat("{\n"
13677                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13678                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13679                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13680                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13681                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13682                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13683                "};",
13684                Tab);
13685   verifyFormat("enum AA {\n"
13686                "\ta1, // Force multiple lines\n"
13687                "\ta2,\n"
13688                "\ta3\n"
13689                "};",
13690                Tab);
13691   EXPECT_EQ("if (aaaaaaaa && // q\n"
13692             "    bb)         // w\n"
13693             "\t;",
13694             format("if (aaaaaaaa &&// q\n"
13695                    "bb)// w\n"
13696                    ";",
13697                    Tab));
13698   verifyFormat("class X {\n"
13699                "\tvoid f() {\n"
13700                "\t\tsomeFunction(parameter1,\n"
13701                "\t\t\t     parameter2);\n"
13702                "\t}\n"
13703                "};",
13704                Tab);
13705   verifyFormat("{\n"
13706                "\tQ(\n"
13707                "\t    {\n"
13708                "\t\t    int a;\n"
13709                "\t\t    someFunction(aaaaaaaa,\n"
13710                "\t\t\t\t bbbbbbb);\n"
13711                "\t    },\n"
13712                "\t    p);\n"
13713                "}",
13714                Tab);
13715   EXPECT_EQ("{\n"
13716             "\t/* aaaa\n"
13717             "\t   bbbb */\n"
13718             "}",
13719             format("{\n"
13720                    "/* aaaa\n"
13721                    "   bbbb */\n"
13722                    "}",
13723                    Tab));
13724   EXPECT_EQ("{\n"
13725             "\t/*\n"
13726             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13727             "\t  bbbbbbbbbbbbb\n"
13728             "\t*/\n"
13729             "}",
13730             format("{\n"
13731                    "/*\n"
13732                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13733                    "*/\n"
13734                    "}",
13735                    Tab));
13736   EXPECT_EQ("{\n"
13737             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13738             "\t// bbbbbbbbbbbbb\n"
13739             "}",
13740             format("{\n"
13741                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13742                    "}",
13743                    Tab));
13744   EXPECT_EQ("{\n"
13745             "\t/*\n"
13746             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13747             "\t  bbbbbbbbbbbbb\n"
13748             "\t*/\n"
13749             "}",
13750             format("{\n"
13751                    "\t/*\n"
13752                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13753                    "\t*/\n"
13754                    "}",
13755                    Tab));
13756   EXPECT_EQ("{\n"
13757             "\t/*\n"
13758             "\n"
13759             "\t*/\n"
13760             "}",
13761             format("{\n"
13762                    "\t/*\n"
13763                    "\n"
13764                    "\t*/\n"
13765                    "}",
13766                    Tab));
13767   EXPECT_EQ("{\n"
13768             "\t/*\n"
13769             " asdf\n"
13770             "\t*/\n"
13771             "}",
13772             format("{\n"
13773                    "\t/*\n"
13774                    " asdf\n"
13775                    "\t*/\n"
13776                    "}",
13777                    Tab));
13778   EXPECT_EQ("/* some\n"
13779             "   comment */",
13780             format(" \t \t /* some\n"
13781                    " \t \t    comment */",
13782                    Tab));
13783   EXPECT_EQ("int a; /* some\n"
13784             "   comment */",
13785             format(" \t \t int a; /* some\n"
13786                    " \t \t    comment */",
13787                    Tab));
13788   EXPECT_EQ("int a; /* some\n"
13789             "comment */",
13790             format(" \t \t int\ta; /* some\n"
13791                    " \t \t    comment */",
13792                    Tab));
13793   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13794             "    comment */",
13795             format(" \t \t f(\"\t\t\"); /* some\n"
13796                    " \t \t    comment */",
13797                    Tab));
13798   EXPECT_EQ("{\n"
13799             "\t/*\n"
13800             "\t * Comment\n"
13801             "\t */\n"
13802             "\tint i;\n"
13803             "}",
13804             format("{\n"
13805                    "\t/*\n"
13806                    "\t * Comment\n"
13807                    "\t */\n"
13808                    "\t int i;\n"
13809                    "}",
13810                    Tab));
13811   Tab.TabWidth = 2;
13812   Tab.IndentWidth = 2;
13813   EXPECT_EQ("{\n"
13814             "\t/* aaaa\n"
13815             "\t\t bbbb */\n"
13816             "}",
13817             format("{\n"
13818                    "/* aaaa\n"
13819                    "\t bbbb */\n"
13820                    "}",
13821                    Tab));
13822   EXPECT_EQ("{\n"
13823             "\t/*\n"
13824             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13825             "\t\tbbbbbbbbbbbbb\n"
13826             "\t*/\n"
13827             "}",
13828             format("{\n"
13829                    "/*\n"
13830                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13831                    "*/\n"
13832                    "}",
13833                    Tab));
13834   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13835   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13836   Tab.TabWidth = 4;
13837   Tab.IndentWidth = 4;
13838   verifyFormat("class Assign {\n"
13839                "\tvoid f() {\n"
13840                "\t\tint         x      = 123;\n"
13841                "\t\tint         random = 4;\n"
13842                "\t\tstd::string alphabet =\n"
13843                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
13844                "\t}\n"
13845                "};",
13846                Tab);
13847 
13848   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
13849   Tab.TabWidth = 8;
13850   Tab.IndentWidth = 8;
13851   EXPECT_EQ("if (aaaaaaaa && // q\n"
13852             "    bb)         // w\n"
13853             "\t;",
13854             format("if (aaaaaaaa &&// q\n"
13855                    "bb)// w\n"
13856                    ";",
13857                    Tab));
13858   EXPECT_EQ("if (aaa && bbb) // w\n"
13859             "\t;",
13860             format("if(aaa&&bbb)// w\n"
13861                    ";",
13862                    Tab));
13863   verifyFormat("class X {\n"
13864                "\tvoid f() {\n"
13865                "\t\tsomeFunction(parameter1,\n"
13866                "\t\t             parameter2);\n"
13867                "\t}\n"
13868                "};",
13869                Tab);
13870   verifyFormat("#define A                        \\\n"
13871                "\tvoid f() {               \\\n"
13872                "\t\tsomeFunction(    \\\n"
13873                "\t\t    parameter1,  \\\n"
13874                "\t\t    parameter2); \\\n"
13875                "\t}",
13876                Tab);
13877   Tab.TabWidth = 4;
13878   Tab.IndentWidth = 8;
13879   verifyFormat("class TabWidth4Indent8 {\n"
13880                "\t\tvoid f() {\n"
13881                "\t\t\t\tsomeFunction(parameter1,\n"
13882                "\t\t\t\t             parameter2);\n"
13883                "\t\t}\n"
13884                "};",
13885                Tab);
13886   Tab.TabWidth = 4;
13887   Tab.IndentWidth = 4;
13888   verifyFormat("class TabWidth4Indent4 {\n"
13889                "\tvoid f() {\n"
13890                "\t\tsomeFunction(parameter1,\n"
13891                "\t\t             parameter2);\n"
13892                "\t}\n"
13893                "};",
13894                Tab);
13895   Tab.TabWidth = 8;
13896   Tab.IndentWidth = 4;
13897   verifyFormat("class TabWidth8Indent4 {\n"
13898                "    void f() {\n"
13899                "\tsomeFunction(parameter1,\n"
13900                "\t             parameter2);\n"
13901                "    }\n"
13902                "};",
13903                Tab);
13904   Tab.TabWidth = 8;
13905   Tab.IndentWidth = 8;
13906   EXPECT_EQ("/*\n"
13907             "              a\t\tcomment\n"
13908             "              in multiple lines\n"
13909             "       */",
13910             format("   /*\t \t \n"
13911                    " \t \t a\t\tcomment\t \t\n"
13912                    " \t \t in multiple lines\t\n"
13913                    " \t  */",
13914                    Tab));
13915   verifyFormat("{\n"
13916                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13917                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13918                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13919                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13920                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13921                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13922                "};",
13923                Tab);
13924   verifyFormat("enum AA {\n"
13925                "\ta1, // Force multiple lines\n"
13926                "\ta2,\n"
13927                "\ta3\n"
13928                "};",
13929                Tab);
13930   EXPECT_EQ("if (aaaaaaaa && // q\n"
13931             "    bb)         // w\n"
13932             "\t;",
13933             format("if (aaaaaaaa &&// q\n"
13934                    "bb)// w\n"
13935                    ";",
13936                    Tab));
13937   verifyFormat("class X {\n"
13938                "\tvoid f() {\n"
13939                "\t\tsomeFunction(parameter1,\n"
13940                "\t\t             parameter2);\n"
13941                "\t}\n"
13942                "};",
13943                Tab);
13944   verifyFormat("{\n"
13945                "\tQ(\n"
13946                "\t    {\n"
13947                "\t\t    int a;\n"
13948                "\t\t    someFunction(aaaaaaaa,\n"
13949                "\t\t                 bbbbbbb);\n"
13950                "\t    },\n"
13951                "\t    p);\n"
13952                "}",
13953                Tab);
13954   EXPECT_EQ("{\n"
13955             "\t/* aaaa\n"
13956             "\t   bbbb */\n"
13957             "}",
13958             format("{\n"
13959                    "/* aaaa\n"
13960                    "   bbbb */\n"
13961                    "}",
13962                    Tab));
13963   EXPECT_EQ("{\n"
13964             "\t/*\n"
13965             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13966             "\t  bbbbbbbbbbbbb\n"
13967             "\t*/\n"
13968             "}",
13969             format("{\n"
13970                    "/*\n"
13971                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13972                    "*/\n"
13973                    "}",
13974                    Tab));
13975   EXPECT_EQ("{\n"
13976             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13977             "\t// bbbbbbbbbbbbb\n"
13978             "}",
13979             format("{\n"
13980                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13981                    "}",
13982                    Tab));
13983   EXPECT_EQ("{\n"
13984             "\t/*\n"
13985             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13986             "\t  bbbbbbbbbbbbb\n"
13987             "\t*/\n"
13988             "}",
13989             format("{\n"
13990                    "\t/*\n"
13991                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13992                    "\t*/\n"
13993                    "}",
13994                    Tab));
13995   EXPECT_EQ("{\n"
13996             "\t/*\n"
13997             "\n"
13998             "\t*/\n"
13999             "}",
14000             format("{\n"
14001                    "\t/*\n"
14002                    "\n"
14003                    "\t*/\n"
14004                    "}",
14005                    Tab));
14006   EXPECT_EQ("{\n"
14007             "\t/*\n"
14008             " asdf\n"
14009             "\t*/\n"
14010             "}",
14011             format("{\n"
14012                    "\t/*\n"
14013                    " asdf\n"
14014                    "\t*/\n"
14015                    "}",
14016                    Tab));
14017   EXPECT_EQ("/* some\n"
14018             "   comment */",
14019             format(" \t \t /* some\n"
14020                    " \t \t    comment */",
14021                    Tab));
14022   EXPECT_EQ("int a; /* some\n"
14023             "   comment */",
14024             format(" \t \t int a; /* some\n"
14025                    " \t \t    comment */",
14026                    Tab));
14027   EXPECT_EQ("int a; /* some\n"
14028             "comment */",
14029             format(" \t \t int\ta; /* some\n"
14030                    " \t \t    comment */",
14031                    Tab));
14032   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14033             "    comment */",
14034             format(" \t \t f(\"\t\t\"); /* some\n"
14035                    " \t \t    comment */",
14036                    Tab));
14037   EXPECT_EQ("{\n"
14038             "\t/*\n"
14039             "\t * Comment\n"
14040             "\t */\n"
14041             "\tint i;\n"
14042             "}",
14043             format("{\n"
14044                    "\t/*\n"
14045                    "\t * Comment\n"
14046                    "\t */\n"
14047                    "\t int i;\n"
14048                    "}",
14049                    Tab));
14050   Tab.TabWidth = 2;
14051   Tab.IndentWidth = 2;
14052   EXPECT_EQ("{\n"
14053             "\t/* aaaa\n"
14054             "\t   bbbb */\n"
14055             "}",
14056             format("{\n"
14057                    "/* aaaa\n"
14058                    "   bbbb */\n"
14059                    "}",
14060                    Tab));
14061   EXPECT_EQ("{\n"
14062             "\t/*\n"
14063             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14064             "\t  bbbbbbbbbbbbb\n"
14065             "\t*/\n"
14066             "}",
14067             format("{\n"
14068                    "/*\n"
14069                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14070                    "*/\n"
14071                    "}",
14072                    Tab));
14073   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14074   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14075   Tab.TabWidth = 4;
14076   Tab.IndentWidth = 4;
14077   verifyFormat("class Assign {\n"
14078                "\tvoid f() {\n"
14079                "\t\tint         x      = 123;\n"
14080                "\t\tint         random = 4;\n"
14081                "\t\tstd::string alphabet =\n"
14082                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14083                "\t}\n"
14084                "};",
14085                Tab);
14086   Tab.AlignOperands = FormatStyle::OAS_Align;
14087   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14088                "                 cccccccccccccccccccc;",
14089                Tab);
14090   // no alignment
14091   verifyFormat("int aaaaaaaaaa =\n"
14092                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14093                Tab);
14094   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14095                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14096                "                        : 333333333333333;",
14097                Tab);
14098   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14099   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14100   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14101                "               + cccccccccccccccccccc;",
14102                Tab);
14103 }
14104 
14105 TEST_F(FormatTest, ZeroTabWidth) {
14106   FormatStyle Tab = getLLVMStyleWithColumns(42);
14107   Tab.IndentWidth = 8;
14108   Tab.UseTab = FormatStyle::UT_Never;
14109   Tab.TabWidth = 0;
14110   EXPECT_EQ("void a(){\n"
14111             "    // line starts with '\t'\n"
14112             "};",
14113             format("void a(){\n"
14114                    "\t// line starts with '\t'\n"
14115                    "};",
14116                    Tab));
14117 
14118   EXPECT_EQ("void a(){\n"
14119             "    // line starts with '\t'\n"
14120             "};",
14121             format("void a(){\n"
14122                    "\t\t// line starts with '\t'\n"
14123                    "};",
14124                    Tab));
14125 
14126   Tab.UseTab = FormatStyle::UT_ForIndentation;
14127   EXPECT_EQ("void a(){\n"
14128             "    // line starts with '\t'\n"
14129             "};",
14130             format("void a(){\n"
14131                    "\t// line starts with '\t'\n"
14132                    "};",
14133                    Tab));
14134 
14135   EXPECT_EQ("void a(){\n"
14136             "    // line starts with '\t'\n"
14137             "};",
14138             format("void a(){\n"
14139                    "\t\t// line starts with '\t'\n"
14140                    "};",
14141                    Tab));
14142 
14143   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14144   EXPECT_EQ("void a(){\n"
14145             "    // line starts with '\t'\n"
14146             "};",
14147             format("void a(){\n"
14148                    "\t// line starts with '\t'\n"
14149                    "};",
14150                    Tab));
14151 
14152   EXPECT_EQ("void a(){\n"
14153             "    // line starts with '\t'\n"
14154             "};",
14155             format("void a(){\n"
14156                    "\t\t// line starts with '\t'\n"
14157                    "};",
14158                    Tab));
14159 
14160   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14161   EXPECT_EQ("void a(){\n"
14162             "    // line starts with '\t'\n"
14163             "};",
14164             format("void a(){\n"
14165                    "\t// line starts with '\t'\n"
14166                    "};",
14167                    Tab));
14168 
14169   EXPECT_EQ("void a(){\n"
14170             "    // line starts with '\t'\n"
14171             "};",
14172             format("void a(){\n"
14173                    "\t\t// line starts with '\t'\n"
14174                    "};",
14175                    Tab));
14176 
14177   Tab.UseTab = FormatStyle::UT_Always;
14178   EXPECT_EQ("void a(){\n"
14179             "// line starts with '\t'\n"
14180             "};",
14181             format("void a(){\n"
14182                    "\t// line starts with '\t'\n"
14183                    "};",
14184                    Tab));
14185 
14186   EXPECT_EQ("void a(){\n"
14187             "// line starts with '\t'\n"
14188             "};",
14189             format("void a(){\n"
14190                    "\t\t// line starts with '\t'\n"
14191                    "};",
14192                    Tab));
14193 }
14194 
14195 TEST_F(FormatTest, CalculatesOriginalColumn) {
14196   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14197             "q\"; /* some\n"
14198             "       comment */",
14199             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14200                    "q\"; /* some\n"
14201                    "       comment */",
14202                    getLLVMStyle()));
14203   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14204             "/* some\n"
14205             "   comment */",
14206             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14207                    " /* some\n"
14208                    "    comment */",
14209                    getLLVMStyle()));
14210   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14211             "qqq\n"
14212             "/* some\n"
14213             "   comment */",
14214             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14215                    "qqq\n"
14216                    " /* some\n"
14217                    "    comment */",
14218                    getLLVMStyle()));
14219   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14220             "wwww; /* some\n"
14221             "         comment */",
14222             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14223                    "wwww; /* some\n"
14224                    "         comment */",
14225                    getLLVMStyle()));
14226 }
14227 
14228 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14229   FormatStyle NoSpace = getLLVMStyle();
14230   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14231 
14232   verifyFormat("while(true)\n"
14233                "  continue;",
14234                NoSpace);
14235   verifyFormat("for(;;)\n"
14236                "  continue;",
14237                NoSpace);
14238   verifyFormat("if(true)\n"
14239                "  f();\n"
14240                "else if(true)\n"
14241                "  f();",
14242                NoSpace);
14243   verifyFormat("do {\n"
14244                "  do_something();\n"
14245                "} while(something());",
14246                NoSpace);
14247   verifyFormat("switch(x) {\n"
14248                "default:\n"
14249                "  break;\n"
14250                "}",
14251                NoSpace);
14252   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14253   verifyFormat("size_t x = sizeof(x);", NoSpace);
14254   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14255   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14256   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14257   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14258   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14259   verifyFormat("alignas(128) char a[128];", NoSpace);
14260   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14261   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14262   verifyFormat("int f() throw(Deprecated);", NoSpace);
14263   verifyFormat("typedef void (*cb)(int);", NoSpace);
14264   verifyFormat("T A::operator()();", NoSpace);
14265   verifyFormat("X A::operator++(T);", NoSpace);
14266   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14267 
14268   FormatStyle Space = getLLVMStyle();
14269   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14270 
14271   verifyFormat("int f ();", Space);
14272   verifyFormat("void f (int a, T b) {\n"
14273                "  while (true)\n"
14274                "    continue;\n"
14275                "}",
14276                Space);
14277   verifyFormat("if (true)\n"
14278                "  f ();\n"
14279                "else if (true)\n"
14280                "  f ();",
14281                Space);
14282   verifyFormat("do {\n"
14283                "  do_something ();\n"
14284                "} while (something ());",
14285                Space);
14286   verifyFormat("switch (x) {\n"
14287                "default:\n"
14288                "  break;\n"
14289                "}",
14290                Space);
14291   verifyFormat("A::A () : a (1) {}", Space);
14292   verifyFormat("void f () __attribute__ ((asdf));", Space);
14293   verifyFormat("*(&a + 1);\n"
14294                "&((&a)[1]);\n"
14295                "a[(b + c) * d];\n"
14296                "(((a + 1) * 2) + 3) * 4;",
14297                Space);
14298   verifyFormat("#define A(x) x", Space);
14299   verifyFormat("#define A (x) x", Space);
14300   verifyFormat("#if defined(x)\n"
14301                "#endif",
14302                Space);
14303   verifyFormat("auto i = std::make_unique<int> (5);", Space);
14304   verifyFormat("size_t x = sizeof (x);", Space);
14305   verifyFormat("auto f (int x) -> decltype (x);", Space);
14306   verifyFormat("auto f (int x) -> typeof (x);", Space);
14307   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
14308   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
14309   verifyFormat("int f (T x) noexcept (x.create ());", Space);
14310   verifyFormat("alignas (128) char a[128];", Space);
14311   verifyFormat("size_t x = alignof (MyType);", Space);
14312   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
14313   verifyFormat("int f () throw (Deprecated);", Space);
14314   verifyFormat("typedef void (*cb) (int);", Space);
14315   // FIXME these tests regressed behaviour.
14316   // verifyFormat("T A::operator() ();", Space);
14317   // verifyFormat("X A::operator++ (T);", Space);
14318   verifyFormat("auto lambda = [] () { return 0; };", Space);
14319   verifyFormat("int x = int (y);", Space);
14320 
14321   FormatStyle SomeSpace = getLLVMStyle();
14322   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
14323 
14324   verifyFormat("[]() -> float {}", SomeSpace);
14325   verifyFormat("[] (auto foo) {}", SomeSpace);
14326   verifyFormat("[foo]() -> int {}", SomeSpace);
14327   verifyFormat("int f();", SomeSpace);
14328   verifyFormat("void f (int a, T b) {\n"
14329                "  while (true)\n"
14330                "    continue;\n"
14331                "}",
14332                SomeSpace);
14333   verifyFormat("if (true)\n"
14334                "  f();\n"
14335                "else if (true)\n"
14336                "  f();",
14337                SomeSpace);
14338   verifyFormat("do {\n"
14339                "  do_something();\n"
14340                "} while (something());",
14341                SomeSpace);
14342   verifyFormat("switch (x) {\n"
14343                "default:\n"
14344                "  break;\n"
14345                "}",
14346                SomeSpace);
14347   verifyFormat("A::A() : a (1) {}", SomeSpace);
14348   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
14349   verifyFormat("*(&a + 1);\n"
14350                "&((&a)[1]);\n"
14351                "a[(b + c) * d];\n"
14352                "(((a + 1) * 2) + 3) * 4;",
14353                SomeSpace);
14354   verifyFormat("#define A(x) x", SomeSpace);
14355   verifyFormat("#define A (x) x", SomeSpace);
14356   verifyFormat("#if defined(x)\n"
14357                "#endif",
14358                SomeSpace);
14359   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
14360   verifyFormat("size_t x = sizeof (x);", SomeSpace);
14361   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
14362   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
14363   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
14364   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
14365   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
14366   verifyFormat("alignas (128) char a[128];", SomeSpace);
14367   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
14368   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14369                SomeSpace);
14370   verifyFormat("int f() throw (Deprecated);", SomeSpace);
14371   verifyFormat("typedef void (*cb) (int);", SomeSpace);
14372   verifyFormat("T A::operator()();", SomeSpace);
14373   // FIXME these tests regressed behaviour.
14374   // verifyFormat("X A::operator++ (T);", SomeSpace);
14375   verifyFormat("int x = int (y);", SomeSpace);
14376   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
14377 
14378   FormatStyle SpaceControlStatements = getLLVMStyle();
14379   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14380   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
14381 
14382   verifyFormat("while (true)\n"
14383                "  continue;",
14384                SpaceControlStatements);
14385   verifyFormat("if (true)\n"
14386                "  f();\n"
14387                "else if (true)\n"
14388                "  f();",
14389                SpaceControlStatements);
14390   verifyFormat("for (;;) {\n"
14391                "  do_something();\n"
14392                "}",
14393                SpaceControlStatements);
14394   verifyFormat("do {\n"
14395                "  do_something();\n"
14396                "} while (something());",
14397                SpaceControlStatements);
14398   verifyFormat("switch (x) {\n"
14399                "default:\n"
14400                "  break;\n"
14401                "}",
14402                SpaceControlStatements);
14403 
14404   FormatStyle SpaceFuncDecl = getLLVMStyle();
14405   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14406   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
14407 
14408   verifyFormat("int f ();", SpaceFuncDecl);
14409   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
14410   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
14411   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
14412   verifyFormat("#define A(x) x", SpaceFuncDecl);
14413   verifyFormat("#define A (x) x", SpaceFuncDecl);
14414   verifyFormat("#if defined(x)\n"
14415                "#endif",
14416                SpaceFuncDecl);
14417   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
14418   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
14419   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
14420   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
14421   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
14422   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
14423   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
14424   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
14425   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
14426   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14427                SpaceFuncDecl);
14428   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
14429   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
14430   // FIXME these tests regressed behaviour.
14431   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
14432   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
14433   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
14434   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
14435   verifyFormat("int x = int(y);", SpaceFuncDecl);
14436   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14437                SpaceFuncDecl);
14438 
14439   FormatStyle SpaceFuncDef = getLLVMStyle();
14440   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14441   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
14442 
14443   verifyFormat("int f();", SpaceFuncDef);
14444   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
14445   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
14446   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
14447   verifyFormat("#define A(x) x", SpaceFuncDef);
14448   verifyFormat("#define A (x) x", SpaceFuncDef);
14449   verifyFormat("#if defined(x)\n"
14450                "#endif",
14451                SpaceFuncDef);
14452   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
14453   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
14454   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
14455   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
14456   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
14457   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
14458   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
14459   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
14460   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
14461   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14462                SpaceFuncDef);
14463   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
14464   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
14465   verifyFormat("T A::operator()();", SpaceFuncDef);
14466   verifyFormat("X A::operator++(T);", SpaceFuncDef);
14467   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
14468   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
14469   verifyFormat("int x = int(y);", SpaceFuncDef);
14470   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14471                SpaceFuncDef);
14472 
14473   FormatStyle SpaceIfMacros = getLLVMStyle();
14474   SpaceIfMacros.IfMacros.clear();
14475   SpaceIfMacros.IfMacros.push_back("MYIF");
14476   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14477   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
14478   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
14479   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
14480   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
14481 
14482   FormatStyle SpaceForeachMacros = getLLVMStyle();
14483   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14484   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
14485   verifyFormat("foreach (Item *item, itemlist) {}", SpaceForeachMacros);
14486   verifyFormat("Q_FOREACH (Item *item, itemlist) {}", SpaceForeachMacros);
14487   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {}", SpaceForeachMacros);
14488   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
14489 
14490   FormatStyle SomeSpace2 = getLLVMStyle();
14491   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14492   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
14493   verifyFormat("[]() -> float {}", SomeSpace2);
14494   verifyFormat("[] (auto foo) {}", SomeSpace2);
14495   verifyFormat("[foo]() -> int {}", SomeSpace2);
14496   verifyFormat("int f();", SomeSpace2);
14497   verifyFormat("void f (int a, T b) {\n"
14498                "  while (true)\n"
14499                "    continue;\n"
14500                "}",
14501                SomeSpace2);
14502   verifyFormat("if (true)\n"
14503                "  f();\n"
14504                "else if (true)\n"
14505                "  f();",
14506                SomeSpace2);
14507   verifyFormat("do {\n"
14508                "  do_something();\n"
14509                "} while (something());",
14510                SomeSpace2);
14511   verifyFormat("switch (x) {\n"
14512                "default:\n"
14513                "  break;\n"
14514                "}",
14515                SomeSpace2);
14516   verifyFormat("A::A() : a (1) {}", SomeSpace2);
14517   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
14518   verifyFormat("*(&a + 1);\n"
14519                "&((&a)[1]);\n"
14520                "a[(b + c) * d];\n"
14521                "(((a + 1) * 2) + 3) * 4;",
14522                SomeSpace2);
14523   verifyFormat("#define A(x) x", SomeSpace2);
14524   verifyFormat("#define A (x) x", SomeSpace2);
14525   verifyFormat("#if defined(x)\n"
14526                "#endif",
14527                SomeSpace2);
14528   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
14529   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
14530   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
14531   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
14532   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
14533   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
14534   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
14535   verifyFormat("alignas (128) char a[128];", SomeSpace2);
14536   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
14537   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14538                SomeSpace2);
14539   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
14540   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
14541   verifyFormat("T A::operator()();", SomeSpace2);
14542   // verifyFormat("X A::operator++ (T);", SomeSpace2);
14543   verifyFormat("int x = int (y);", SomeSpace2);
14544   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
14545 }
14546 
14547 TEST_F(FormatTest, SpaceAfterLogicalNot) {
14548   FormatStyle Spaces = getLLVMStyle();
14549   Spaces.SpaceAfterLogicalNot = true;
14550 
14551   verifyFormat("bool x = ! y", Spaces);
14552   verifyFormat("if (! isFailure())", Spaces);
14553   verifyFormat("if (! (a && b))", Spaces);
14554   verifyFormat("\"Error!\"", Spaces);
14555   verifyFormat("! ! x", Spaces);
14556 }
14557 
14558 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
14559   FormatStyle Spaces = getLLVMStyle();
14560 
14561   Spaces.SpacesInParentheses = true;
14562   verifyFormat("do_something( ::globalVar );", Spaces);
14563   verifyFormat("call( x, y, z );", Spaces);
14564   verifyFormat("call();", Spaces);
14565   verifyFormat("std::function<void( int, int )> callback;", Spaces);
14566   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
14567                Spaces);
14568   verifyFormat("while ( (bool)1 )\n"
14569                "  continue;",
14570                Spaces);
14571   verifyFormat("for ( ;; )\n"
14572                "  continue;",
14573                Spaces);
14574   verifyFormat("if ( true )\n"
14575                "  f();\n"
14576                "else if ( true )\n"
14577                "  f();",
14578                Spaces);
14579   verifyFormat("do {\n"
14580                "  do_something( (int)i );\n"
14581                "} while ( something() );",
14582                Spaces);
14583   verifyFormat("switch ( x ) {\n"
14584                "default:\n"
14585                "  break;\n"
14586                "}",
14587                Spaces);
14588 
14589   Spaces.SpacesInParentheses = false;
14590   Spaces.SpacesInCStyleCastParentheses = true;
14591   verifyFormat("Type *A = ( Type * )P;", Spaces);
14592   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
14593   verifyFormat("x = ( int32 )y;", Spaces);
14594   verifyFormat("int a = ( int )(2.0f);", Spaces);
14595   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
14596   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
14597   verifyFormat("#define x (( int )-1)", Spaces);
14598 
14599   // Run the first set of tests again with:
14600   Spaces.SpacesInParentheses = false;
14601   Spaces.SpaceInEmptyParentheses = true;
14602   Spaces.SpacesInCStyleCastParentheses = true;
14603   verifyFormat("call(x, y, z);", Spaces);
14604   verifyFormat("call( );", Spaces);
14605   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14606   verifyFormat("while (( bool )1)\n"
14607                "  continue;",
14608                Spaces);
14609   verifyFormat("for (;;)\n"
14610                "  continue;",
14611                Spaces);
14612   verifyFormat("if (true)\n"
14613                "  f( );\n"
14614                "else if (true)\n"
14615                "  f( );",
14616                Spaces);
14617   verifyFormat("do {\n"
14618                "  do_something(( int )i);\n"
14619                "} while (something( ));",
14620                Spaces);
14621   verifyFormat("switch (x) {\n"
14622                "default:\n"
14623                "  break;\n"
14624                "}",
14625                Spaces);
14626 
14627   // Run the first set of tests again with:
14628   Spaces.SpaceAfterCStyleCast = true;
14629   verifyFormat("call(x, y, z);", Spaces);
14630   verifyFormat("call( );", Spaces);
14631   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14632   verifyFormat("while (( bool ) 1)\n"
14633                "  continue;",
14634                Spaces);
14635   verifyFormat("for (;;)\n"
14636                "  continue;",
14637                Spaces);
14638   verifyFormat("if (true)\n"
14639                "  f( );\n"
14640                "else if (true)\n"
14641                "  f( );",
14642                Spaces);
14643   verifyFormat("do {\n"
14644                "  do_something(( int ) i);\n"
14645                "} while (something( ));",
14646                Spaces);
14647   verifyFormat("switch (x) {\n"
14648                "default:\n"
14649                "  break;\n"
14650                "}",
14651                Spaces);
14652 
14653   // Run subset of tests again with:
14654   Spaces.SpacesInCStyleCastParentheses = false;
14655   Spaces.SpaceAfterCStyleCast = true;
14656   verifyFormat("while ((bool) 1)\n"
14657                "  continue;",
14658                Spaces);
14659   verifyFormat("do {\n"
14660                "  do_something((int) i);\n"
14661                "} while (something( ));",
14662                Spaces);
14663 
14664   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
14665   verifyFormat("size_t idx = (size_t) a;", Spaces);
14666   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
14667   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14668   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14669   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14670   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14671   Spaces.ColumnLimit = 80;
14672   Spaces.IndentWidth = 4;
14673   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14674   verifyFormat("void foo( ) {\n"
14675                "    size_t foo = (*(function))(\n"
14676                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14677                "BarrrrrrrrrrrrLong,\n"
14678                "        FoooooooooLooooong);\n"
14679                "}",
14680                Spaces);
14681   Spaces.SpaceAfterCStyleCast = false;
14682   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
14683   verifyFormat("size_t idx = (size_t)a;", Spaces);
14684   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
14685   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14686   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14687   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14688   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14689 
14690   verifyFormat("void foo( ) {\n"
14691                "    size_t foo = (*(function))(\n"
14692                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14693                "BarrrrrrrrrrrrLong,\n"
14694                "        FoooooooooLooooong);\n"
14695                "}",
14696                Spaces);
14697 }
14698 
14699 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
14700   verifyFormat("int a[5];");
14701   verifyFormat("a[3] += 42;");
14702 
14703   FormatStyle Spaces = getLLVMStyle();
14704   Spaces.SpacesInSquareBrackets = true;
14705   // Not lambdas.
14706   verifyFormat("int a[ 5 ];", Spaces);
14707   verifyFormat("a[ 3 ] += 42;", Spaces);
14708   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
14709   verifyFormat("double &operator[](int i) { return 0; }\n"
14710                "int i;",
14711                Spaces);
14712   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
14713   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
14714   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
14715   // Lambdas.
14716   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
14717   verifyFormat("return [ i, args... ] {};", Spaces);
14718   verifyFormat("int foo = [ &bar ]() {};", Spaces);
14719   verifyFormat("int foo = [ = ]() {};", Spaces);
14720   verifyFormat("int foo = [ & ]() {};", Spaces);
14721   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
14722   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
14723 }
14724 
14725 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
14726   FormatStyle NoSpaceStyle = getLLVMStyle();
14727   verifyFormat("int a[5];", NoSpaceStyle);
14728   verifyFormat("a[3] += 42;", NoSpaceStyle);
14729 
14730   verifyFormat("int a[1];", NoSpaceStyle);
14731   verifyFormat("int 1 [a];", NoSpaceStyle);
14732   verifyFormat("int a[1][2];", NoSpaceStyle);
14733   verifyFormat("a[7] = 5;", NoSpaceStyle);
14734   verifyFormat("int a = (f())[23];", NoSpaceStyle);
14735   verifyFormat("f([] {})", NoSpaceStyle);
14736 
14737   FormatStyle Space = getLLVMStyle();
14738   Space.SpaceBeforeSquareBrackets = true;
14739   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
14740   verifyFormat("return [i, args...] {};", Space);
14741 
14742   verifyFormat("int a [5];", Space);
14743   verifyFormat("a [3] += 42;", Space);
14744   verifyFormat("constexpr char hello []{\"hello\"};", Space);
14745   verifyFormat("double &operator[](int i) { return 0; }\n"
14746                "int i;",
14747                Space);
14748   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
14749   verifyFormat("int i = a [a][a]->f();", Space);
14750   verifyFormat("int i = (*b) [a]->f();", Space);
14751 
14752   verifyFormat("int a [1];", Space);
14753   verifyFormat("int 1 [a];", Space);
14754   verifyFormat("int a [1][2];", Space);
14755   verifyFormat("a [7] = 5;", Space);
14756   verifyFormat("int a = (f()) [23];", Space);
14757   verifyFormat("f([] {})", Space);
14758 }
14759 
14760 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
14761   verifyFormat("int a = 5;");
14762   verifyFormat("a += 42;");
14763   verifyFormat("a or_eq 8;");
14764 
14765   FormatStyle Spaces = getLLVMStyle();
14766   Spaces.SpaceBeforeAssignmentOperators = false;
14767   verifyFormat("int a= 5;", Spaces);
14768   verifyFormat("a+= 42;", Spaces);
14769   verifyFormat("a or_eq 8;", Spaces);
14770 }
14771 
14772 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
14773   verifyFormat("class Foo : public Bar {};");
14774   verifyFormat("Foo::Foo() : foo(1) {}");
14775   verifyFormat("for (auto a : b) {\n}");
14776   verifyFormat("int x = a ? b : c;");
14777   verifyFormat("{\n"
14778                "label0:\n"
14779                "  int x = 0;\n"
14780                "}");
14781   verifyFormat("switch (x) {\n"
14782                "case 1:\n"
14783                "default:\n"
14784                "}");
14785   verifyFormat("switch (allBraces) {\n"
14786                "case 1: {\n"
14787                "  break;\n"
14788                "}\n"
14789                "case 2: {\n"
14790                "  [[fallthrough]];\n"
14791                "}\n"
14792                "default: {\n"
14793                "  break;\n"
14794                "}\n"
14795                "}");
14796 
14797   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
14798   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
14799   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
14800   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
14801   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
14802   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
14803   verifyFormat("{\n"
14804                "label1:\n"
14805                "  int x = 0;\n"
14806                "}",
14807                CtorInitializerStyle);
14808   verifyFormat("switch (x) {\n"
14809                "case 1:\n"
14810                "default:\n"
14811                "}",
14812                CtorInitializerStyle);
14813   verifyFormat("switch (allBraces) {\n"
14814                "case 1: {\n"
14815                "  break;\n"
14816                "}\n"
14817                "case 2: {\n"
14818                "  [[fallthrough]];\n"
14819                "}\n"
14820                "default: {\n"
14821                "  break;\n"
14822                "}\n"
14823                "}",
14824                CtorInitializerStyle);
14825   CtorInitializerStyle.BreakConstructorInitializers =
14826       FormatStyle::BCIS_AfterColon;
14827   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
14828                "    aaaaaaaaaaaaaaaa(1),\n"
14829                "    bbbbbbbbbbbbbbbb(2) {}",
14830                CtorInitializerStyle);
14831   CtorInitializerStyle.BreakConstructorInitializers =
14832       FormatStyle::BCIS_BeforeComma;
14833   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14834                "    : aaaaaaaaaaaaaaaa(1)\n"
14835                "    , bbbbbbbbbbbbbbbb(2) {}",
14836                CtorInitializerStyle);
14837   CtorInitializerStyle.BreakConstructorInitializers =
14838       FormatStyle::BCIS_BeforeColon;
14839   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14840                "    : aaaaaaaaaaaaaaaa(1),\n"
14841                "      bbbbbbbbbbbbbbbb(2) {}",
14842                CtorInitializerStyle);
14843   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
14844   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14845                ": aaaaaaaaaaaaaaaa(1),\n"
14846                "  bbbbbbbbbbbbbbbb(2) {}",
14847                CtorInitializerStyle);
14848 
14849   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
14850   InheritanceStyle.SpaceBeforeInheritanceColon = false;
14851   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
14852   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
14853   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
14854   verifyFormat("int x = a ? b : c;", InheritanceStyle);
14855   verifyFormat("{\n"
14856                "label2:\n"
14857                "  int x = 0;\n"
14858                "}",
14859                InheritanceStyle);
14860   verifyFormat("switch (x) {\n"
14861                "case 1:\n"
14862                "default:\n"
14863                "}",
14864                InheritanceStyle);
14865   verifyFormat("switch (allBraces) {\n"
14866                "case 1: {\n"
14867                "  break;\n"
14868                "}\n"
14869                "case 2: {\n"
14870                "  [[fallthrough]];\n"
14871                "}\n"
14872                "default: {\n"
14873                "  break;\n"
14874                "}\n"
14875                "}",
14876                InheritanceStyle);
14877   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
14878   verifyFormat("class Foooooooooooooooooooooo\n"
14879                "    : public aaaaaaaaaaaaaaaaaa,\n"
14880                "      public bbbbbbbbbbbbbbbbbb {\n"
14881                "}",
14882                InheritanceStyle);
14883   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
14884   verifyFormat("class Foooooooooooooooooooooo:\n"
14885                "    public aaaaaaaaaaaaaaaaaa,\n"
14886                "    public bbbbbbbbbbbbbbbbbb {\n"
14887                "}",
14888                InheritanceStyle);
14889   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
14890   verifyFormat("class Foooooooooooooooooooooo\n"
14891                "    : public aaaaaaaaaaaaaaaaaa\n"
14892                "    , public bbbbbbbbbbbbbbbbbb {\n"
14893                "}",
14894                InheritanceStyle);
14895   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
14896   verifyFormat("class Foooooooooooooooooooooo\n"
14897                "    : public aaaaaaaaaaaaaaaaaa,\n"
14898                "      public bbbbbbbbbbbbbbbbbb {\n"
14899                "}",
14900                InheritanceStyle);
14901   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
14902   verifyFormat("class Foooooooooooooooooooooo\n"
14903                ": public aaaaaaaaaaaaaaaaaa,\n"
14904                "  public bbbbbbbbbbbbbbbbbb {}",
14905                InheritanceStyle);
14906 
14907   FormatStyle ForLoopStyle = getLLVMStyle();
14908   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
14909   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
14910   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
14911   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
14912   verifyFormat("int x = a ? b : c;", ForLoopStyle);
14913   verifyFormat("{\n"
14914                "label2:\n"
14915                "  int x = 0;\n"
14916                "}",
14917                ForLoopStyle);
14918   verifyFormat("switch (x) {\n"
14919                "case 1:\n"
14920                "default:\n"
14921                "}",
14922                ForLoopStyle);
14923   verifyFormat("switch (allBraces) {\n"
14924                "case 1: {\n"
14925                "  break;\n"
14926                "}\n"
14927                "case 2: {\n"
14928                "  [[fallthrough]];\n"
14929                "}\n"
14930                "default: {\n"
14931                "  break;\n"
14932                "}\n"
14933                "}",
14934                ForLoopStyle);
14935 
14936   FormatStyle CaseStyle = getLLVMStyle();
14937   CaseStyle.SpaceBeforeCaseColon = true;
14938   verifyFormat("class Foo : public Bar {};", CaseStyle);
14939   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
14940   verifyFormat("for (auto a : b) {\n}", CaseStyle);
14941   verifyFormat("int x = a ? b : c;", CaseStyle);
14942   verifyFormat("switch (x) {\n"
14943                "case 1 :\n"
14944                "default :\n"
14945                "}",
14946                CaseStyle);
14947   verifyFormat("switch (allBraces) {\n"
14948                "case 1 : {\n"
14949                "  break;\n"
14950                "}\n"
14951                "case 2 : {\n"
14952                "  [[fallthrough]];\n"
14953                "}\n"
14954                "default : {\n"
14955                "  break;\n"
14956                "}\n"
14957                "}",
14958                CaseStyle);
14959 
14960   FormatStyle NoSpaceStyle = getLLVMStyle();
14961   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
14962   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
14963   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
14964   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
14965   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
14966   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
14967   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
14968   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
14969   verifyFormat("{\n"
14970                "label3:\n"
14971                "  int x = 0;\n"
14972                "}",
14973                NoSpaceStyle);
14974   verifyFormat("switch (x) {\n"
14975                "case 1:\n"
14976                "default:\n"
14977                "}",
14978                NoSpaceStyle);
14979   verifyFormat("switch (allBraces) {\n"
14980                "case 1: {\n"
14981                "  break;\n"
14982                "}\n"
14983                "case 2: {\n"
14984                "  [[fallthrough]];\n"
14985                "}\n"
14986                "default: {\n"
14987                "  break;\n"
14988                "}\n"
14989                "}",
14990                NoSpaceStyle);
14991 
14992   FormatStyle InvertedSpaceStyle = getLLVMStyle();
14993   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
14994   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
14995   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
14996   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
14997   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
14998   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
14999   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15000   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15001   verifyFormat("{\n"
15002                "label3:\n"
15003                "  int x = 0;\n"
15004                "}",
15005                InvertedSpaceStyle);
15006   verifyFormat("switch (x) {\n"
15007                "case 1 :\n"
15008                "case 2 : {\n"
15009                "  break;\n"
15010                "}\n"
15011                "default :\n"
15012                "  break;\n"
15013                "}",
15014                InvertedSpaceStyle);
15015   verifyFormat("switch (allBraces) {\n"
15016                "case 1 : {\n"
15017                "  break;\n"
15018                "}\n"
15019                "case 2 : {\n"
15020                "  [[fallthrough]];\n"
15021                "}\n"
15022                "default : {\n"
15023                "  break;\n"
15024                "}\n"
15025                "}",
15026                InvertedSpaceStyle);
15027 }
15028 
15029 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15030   FormatStyle Style = getLLVMStyle();
15031 
15032   Style.PointerAlignment = FormatStyle::PAS_Left;
15033   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15034   verifyFormat("void* const* x = NULL;", Style);
15035 
15036 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15037   do {                                                                         \
15038     Style.PointerAlignment = FormatStyle::Pointers;                            \
15039     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15040     verifyFormat(Code, Style);                                                 \
15041   } while (false)
15042 
15043   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15044   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15045   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15046 
15047   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15048   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15049   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15050 
15051   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15052   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15053   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15054 
15055   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15056   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15057   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15058 
15059   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15060   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15061                         SAPQ_Default);
15062   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15063                         SAPQ_Default);
15064 
15065   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15066   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15067                         SAPQ_Before);
15068   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15069                         SAPQ_Before);
15070 
15071   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15072   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15073   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15074                         SAPQ_After);
15075 
15076   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15077   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15078   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15079 
15080 #undef verifyQualifierSpaces
15081 
15082   FormatStyle Spaces = getLLVMStyle();
15083   Spaces.AttributeMacros.push_back("qualified");
15084   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15085   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15086   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15087   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15088   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15089   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15090   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15091   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15092   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15093   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15094   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15095   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15096   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15097 
15098   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15099   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15100   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15101   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15102   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15103   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15104   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15105   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15106   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15107   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15108   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15109   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15110   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15111   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15112   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15113 
15114   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15115   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15116   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15117   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15118   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15119   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15120   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15121   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15122 }
15123 
15124 TEST_F(FormatTest, AlignConsecutiveMacros) {
15125   FormatStyle Style = getLLVMStyle();
15126   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15127   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15128   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15129 
15130   verifyFormat("#define a 3\n"
15131                "#define bbbb 4\n"
15132                "#define ccc (5)",
15133                Style);
15134 
15135   verifyFormat("#define f(x) (x * x)\n"
15136                "#define fff(x, y, z) (x * y + z)\n"
15137                "#define ffff(x, y) (x - y)",
15138                Style);
15139 
15140   verifyFormat("#define foo(x, y) (x + y)\n"
15141                "#define bar (5, 6)(2 + 2)",
15142                Style);
15143 
15144   verifyFormat("#define a 3\n"
15145                "#define bbbb 4\n"
15146                "#define ccc (5)\n"
15147                "#define f(x) (x * x)\n"
15148                "#define fff(x, y, z) (x * y + z)\n"
15149                "#define ffff(x, y) (x - y)",
15150                Style);
15151 
15152   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15153   verifyFormat("#define a    3\n"
15154                "#define bbbb 4\n"
15155                "#define ccc  (5)",
15156                Style);
15157 
15158   verifyFormat("#define f(x)         (x * x)\n"
15159                "#define fff(x, y, z) (x * y + z)\n"
15160                "#define ffff(x, y)   (x - y)",
15161                Style);
15162 
15163   verifyFormat("#define foo(x, y) (x + y)\n"
15164                "#define bar       (5, 6)(2 + 2)",
15165                Style);
15166 
15167   verifyFormat("#define a            3\n"
15168                "#define bbbb         4\n"
15169                "#define ccc          (5)\n"
15170                "#define f(x)         (x * x)\n"
15171                "#define fff(x, y, z) (x * y + z)\n"
15172                "#define ffff(x, y)   (x - y)",
15173                Style);
15174 
15175   verifyFormat("#define a         5\n"
15176                "#define foo(x, y) (x + y)\n"
15177                "#define CCC       (6)\n"
15178                "auto lambda = []() {\n"
15179                "  auto  ii = 0;\n"
15180                "  float j  = 0;\n"
15181                "  return 0;\n"
15182                "};\n"
15183                "int   i  = 0;\n"
15184                "float i2 = 0;\n"
15185                "auto  v  = type{\n"
15186                "    i = 1,   //\n"
15187                "    (i = 2), //\n"
15188                "    i = 3    //\n"
15189                "};",
15190                Style);
15191 
15192   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15193   Style.ColumnLimit = 20;
15194 
15195   verifyFormat("#define a          \\\n"
15196                "  \"aabbbbbbbbbbbb\"\n"
15197                "#define D          \\\n"
15198                "  \"aabbbbbbbbbbbb\" \\\n"
15199                "  \"ccddeeeeeeeee\"\n"
15200                "#define B          \\\n"
15201                "  \"QQQQQQQQQQQQQ\"  \\\n"
15202                "  \"FFFFFFFFFFFFF\"  \\\n"
15203                "  \"LLLLLLLL\"\n",
15204                Style);
15205 
15206   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15207   verifyFormat("#define a          \\\n"
15208                "  \"aabbbbbbbbbbbb\"\n"
15209                "#define D          \\\n"
15210                "  \"aabbbbbbbbbbbb\" \\\n"
15211                "  \"ccddeeeeeeeee\"\n"
15212                "#define B          \\\n"
15213                "  \"QQQQQQQQQQQQQ\"  \\\n"
15214                "  \"FFFFFFFFFFFFF\"  \\\n"
15215                "  \"LLLLLLLL\"\n",
15216                Style);
15217 
15218   // Test across comments
15219   Style.MaxEmptyLinesToKeep = 10;
15220   Style.ReflowComments = false;
15221   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
15222   EXPECT_EQ("#define a    3\n"
15223             "// line comment\n"
15224             "#define bbbb 4\n"
15225             "#define ccc  (5)",
15226             format("#define a 3\n"
15227                    "// line comment\n"
15228                    "#define bbbb 4\n"
15229                    "#define ccc (5)",
15230                    Style));
15231 
15232   EXPECT_EQ("#define a    3\n"
15233             "/* block comment */\n"
15234             "#define bbbb 4\n"
15235             "#define ccc  (5)",
15236             format("#define a  3\n"
15237                    "/* block comment */\n"
15238                    "#define bbbb 4\n"
15239                    "#define ccc (5)",
15240                    Style));
15241 
15242   EXPECT_EQ("#define a    3\n"
15243             "/* multi-line *\n"
15244             " * block comment */\n"
15245             "#define bbbb 4\n"
15246             "#define ccc  (5)",
15247             format("#define a 3\n"
15248                    "/* multi-line *\n"
15249                    " * block comment */\n"
15250                    "#define bbbb 4\n"
15251                    "#define ccc (5)",
15252                    Style));
15253 
15254   EXPECT_EQ("#define a    3\n"
15255             "// multi-line line comment\n"
15256             "//\n"
15257             "#define bbbb 4\n"
15258             "#define ccc  (5)",
15259             format("#define a  3\n"
15260                    "// multi-line line comment\n"
15261                    "//\n"
15262                    "#define bbbb 4\n"
15263                    "#define ccc (5)",
15264                    Style));
15265 
15266   EXPECT_EQ("#define a 3\n"
15267             "// empty lines still break.\n"
15268             "\n"
15269             "#define bbbb 4\n"
15270             "#define ccc  (5)",
15271             format("#define a     3\n"
15272                    "// empty lines still break.\n"
15273                    "\n"
15274                    "#define bbbb     4\n"
15275                    "#define ccc  (5)",
15276                    Style));
15277 
15278   // Test across empty lines
15279   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
15280   EXPECT_EQ("#define a    3\n"
15281             "\n"
15282             "#define bbbb 4\n"
15283             "#define ccc  (5)",
15284             format("#define a 3\n"
15285                    "\n"
15286                    "#define bbbb 4\n"
15287                    "#define ccc (5)",
15288                    Style));
15289 
15290   EXPECT_EQ("#define a    3\n"
15291             "\n"
15292             "\n"
15293             "\n"
15294             "#define bbbb 4\n"
15295             "#define ccc  (5)",
15296             format("#define a        3\n"
15297                    "\n"
15298                    "\n"
15299                    "\n"
15300                    "#define bbbb 4\n"
15301                    "#define ccc (5)",
15302                    Style));
15303 
15304   EXPECT_EQ("#define a 3\n"
15305             "// comments should break alignment\n"
15306             "//\n"
15307             "#define bbbb 4\n"
15308             "#define ccc  (5)",
15309             format("#define a        3\n"
15310                    "// comments should break alignment\n"
15311                    "//\n"
15312                    "#define bbbb 4\n"
15313                    "#define ccc (5)",
15314                    Style));
15315 
15316   // Test across empty lines and comments
15317   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
15318   verifyFormat("#define a    3\n"
15319                "\n"
15320                "// line comment\n"
15321                "#define bbbb 4\n"
15322                "#define ccc  (5)",
15323                Style);
15324 
15325   EXPECT_EQ("#define a    3\n"
15326             "\n"
15327             "\n"
15328             "/* multi-line *\n"
15329             " * block comment */\n"
15330             "\n"
15331             "\n"
15332             "#define bbbb 4\n"
15333             "#define ccc  (5)",
15334             format("#define a 3\n"
15335                    "\n"
15336                    "\n"
15337                    "/* multi-line *\n"
15338                    " * block comment */\n"
15339                    "\n"
15340                    "\n"
15341                    "#define bbbb 4\n"
15342                    "#define ccc (5)",
15343                    Style));
15344 
15345   EXPECT_EQ("#define a    3\n"
15346             "\n"
15347             "\n"
15348             "/* multi-line *\n"
15349             " * block comment */\n"
15350             "\n"
15351             "\n"
15352             "#define bbbb 4\n"
15353             "#define ccc  (5)",
15354             format("#define a 3\n"
15355                    "\n"
15356                    "\n"
15357                    "/* multi-line *\n"
15358                    " * block comment */\n"
15359                    "\n"
15360                    "\n"
15361                    "#define bbbb 4\n"
15362                    "#define ccc       (5)",
15363                    Style));
15364 }
15365 
15366 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
15367   FormatStyle Alignment = getLLVMStyle();
15368   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15369   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
15370 
15371   Alignment.MaxEmptyLinesToKeep = 10;
15372   /* Test alignment across empty lines */
15373   EXPECT_EQ("int a           = 5;\n"
15374             "\n"
15375             "int oneTwoThree = 123;",
15376             format("int a       = 5;\n"
15377                    "\n"
15378                    "int oneTwoThree= 123;",
15379                    Alignment));
15380   EXPECT_EQ("int a           = 5;\n"
15381             "int one         = 1;\n"
15382             "\n"
15383             "int oneTwoThree = 123;",
15384             format("int a = 5;\n"
15385                    "int one = 1;\n"
15386                    "\n"
15387                    "int oneTwoThree = 123;",
15388                    Alignment));
15389   EXPECT_EQ("int a           = 5;\n"
15390             "int one         = 1;\n"
15391             "\n"
15392             "int oneTwoThree = 123;\n"
15393             "int oneTwo      = 12;",
15394             format("int a = 5;\n"
15395                    "int one = 1;\n"
15396                    "\n"
15397                    "int oneTwoThree = 123;\n"
15398                    "int oneTwo = 12;",
15399                    Alignment));
15400 
15401   /* Test across comments */
15402   EXPECT_EQ("int a = 5;\n"
15403             "/* block comment */\n"
15404             "int oneTwoThree = 123;",
15405             format("int a = 5;\n"
15406                    "/* block comment */\n"
15407                    "int oneTwoThree=123;",
15408                    Alignment));
15409 
15410   EXPECT_EQ("int a = 5;\n"
15411             "// line comment\n"
15412             "int oneTwoThree = 123;",
15413             format("int a = 5;\n"
15414                    "// line comment\n"
15415                    "int oneTwoThree=123;",
15416                    Alignment));
15417 
15418   /* Test across comments and newlines */
15419   EXPECT_EQ("int a = 5;\n"
15420             "\n"
15421             "/* block comment */\n"
15422             "int oneTwoThree = 123;",
15423             format("int a = 5;\n"
15424                    "\n"
15425                    "/* block comment */\n"
15426                    "int oneTwoThree=123;",
15427                    Alignment));
15428 
15429   EXPECT_EQ("int a = 5;\n"
15430             "\n"
15431             "// line comment\n"
15432             "int oneTwoThree = 123;",
15433             format("int a = 5;\n"
15434                    "\n"
15435                    "// line comment\n"
15436                    "int oneTwoThree=123;",
15437                    Alignment));
15438 }
15439 
15440 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
15441   FormatStyle Alignment = getLLVMStyle();
15442   Alignment.AlignConsecutiveDeclarations =
15443       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15444   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15445 
15446   Alignment.MaxEmptyLinesToKeep = 10;
15447   /* Test alignment across empty lines */
15448   EXPECT_EQ("int         a = 5;\n"
15449             "\n"
15450             "float const oneTwoThree = 123;",
15451             format("int a = 5;\n"
15452                    "\n"
15453                    "float const oneTwoThree = 123;",
15454                    Alignment));
15455   EXPECT_EQ("int         a = 5;\n"
15456             "float const one = 1;\n"
15457             "\n"
15458             "int         oneTwoThree = 123;",
15459             format("int a = 5;\n"
15460                    "float const one = 1;\n"
15461                    "\n"
15462                    "int oneTwoThree = 123;",
15463                    Alignment));
15464 
15465   /* Test across comments */
15466   EXPECT_EQ("float const a = 5;\n"
15467             "/* block comment */\n"
15468             "int         oneTwoThree = 123;",
15469             format("float const a = 5;\n"
15470                    "/* block comment */\n"
15471                    "int oneTwoThree=123;",
15472                    Alignment));
15473 
15474   EXPECT_EQ("float const a = 5;\n"
15475             "// line comment\n"
15476             "int         oneTwoThree = 123;",
15477             format("float const a = 5;\n"
15478                    "// line comment\n"
15479                    "int oneTwoThree=123;",
15480                    Alignment));
15481 
15482   /* Test across comments and newlines */
15483   EXPECT_EQ("float const a = 5;\n"
15484             "\n"
15485             "/* block comment */\n"
15486             "int         oneTwoThree = 123;",
15487             format("float const a = 5;\n"
15488                    "\n"
15489                    "/* block comment */\n"
15490                    "int         oneTwoThree=123;",
15491                    Alignment));
15492 
15493   EXPECT_EQ("float const a = 5;\n"
15494             "\n"
15495             "// line comment\n"
15496             "int         oneTwoThree = 123;",
15497             format("float const a = 5;\n"
15498                    "\n"
15499                    "// line comment\n"
15500                    "int oneTwoThree=123;",
15501                    Alignment));
15502 }
15503 
15504 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
15505   FormatStyle Alignment = getLLVMStyle();
15506   Alignment.AlignConsecutiveBitFields =
15507       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15508 
15509   Alignment.MaxEmptyLinesToKeep = 10;
15510   /* Test alignment across empty lines */
15511   EXPECT_EQ("int a            : 5;\n"
15512             "\n"
15513             "int longbitfield : 6;",
15514             format("int a : 5;\n"
15515                    "\n"
15516                    "int longbitfield : 6;",
15517                    Alignment));
15518   EXPECT_EQ("int a            : 5;\n"
15519             "int one          : 1;\n"
15520             "\n"
15521             "int longbitfield : 6;",
15522             format("int a : 5;\n"
15523                    "int one : 1;\n"
15524                    "\n"
15525                    "int longbitfield : 6;",
15526                    Alignment));
15527 
15528   /* Test across comments */
15529   EXPECT_EQ("int a            : 5;\n"
15530             "/* block comment */\n"
15531             "int longbitfield : 6;",
15532             format("int a : 5;\n"
15533                    "/* block comment */\n"
15534                    "int longbitfield : 6;",
15535                    Alignment));
15536   EXPECT_EQ("int a            : 5;\n"
15537             "int one          : 1;\n"
15538             "// line comment\n"
15539             "int longbitfield : 6;",
15540             format("int a : 5;\n"
15541                    "int one : 1;\n"
15542                    "// line comment\n"
15543                    "int longbitfield : 6;",
15544                    Alignment));
15545 
15546   /* Test across comments and newlines */
15547   EXPECT_EQ("int a            : 5;\n"
15548             "/* block comment */\n"
15549             "\n"
15550             "int longbitfield : 6;",
15551             format("int a : 5;\n"
15552                    "/* block comment */\n"
15553                    "\n"
15554                    "int longbitfield : 6;",
15555                    Alignment));
15556   EXPECT_EQ("int a            : 5;\n"
15557             "int one          : 1;\n"
15558             "\n"
15559             "// line comment\n"
15560             "\n"
15561             "int longbitfield : 6;",
15562             format("int a : 5;\n"
15563                    "int one : 1;\n"
15564                    "\n"
15565                    "// line comment \n"
15566                    "\n"
15567                    "int longbitfield : 6;",
15568                    Alignment));
15569 }
15570 
15571 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
15572   FormatStyle Alignment = getLLVMStyle();
15573   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15574   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
15575 
15576   Alignment.MaxEmptyLinesToKeep = 10;
15577   /* Test alignment across empty lines */
15578   EXPECT_EQ("int a = 5;\n"
15579             "\n"
15580             "int oneTwoThree = 123;",
15581             format("int a       = 5;\n"
15582                    "\n"
15583                    "int oneTwoThree= 123;",
15584                    Alignment));
15585   EXPECT_EQ("int a   = 5;\n"
15586             "int one = 1;\n"
15587             "\n"
15588             "int oneTwoThree = 123;",
15589             format("int a = 5;\n"
15590                    "int one = 1;\n"
15591                    "\n"
15592                    "int oneTwoThree = 123;",
15593                    Alignment));
15594 
15595   /* Test across comments */
15596   EXPECT_EQ("int a           = 5;\n"
15597             "/* block comment */\n"
15598             "int oneTwoThree = 123;",
15599             format("int a = 5;\n"
15600                    "/* block comment */\n"
15601                    "int oneTwoThree=123;",
15602                    Alignment));
15603 
15604   EXPECT_EQ("int a           = 5;\n"
15605             "// line comment\n"
15606             "int oneTwoThree = 123;",
15607             format("int a = 5;\n"
15608                    "// line comment\n"
15609                    "int oneTwoThree=123;",
15610                    Alignment));
15611 
15612   EXPECT_EQ("int a           = 5;\n"
15613             "/*\n"
15614             " * multi-line block comment\n"
15615             " */\n"
15616             "int oneTwoThree = 123;",
15617             format("int a = 5;\n"
15618                    "/*\n"
15619                    " * multi-line block comment\n"
15620                    " */\n"
15621                    "int oneTwoThree=123;",
15622                    Alignment));
15623 
15624   EXPECT_EQ("int a           = 5;\n"
15625             "//\n"
15626             "// multi-line line comment\n"
15627             "//\n"
15628             "int oneTwoThree = 123;",
15629             format("int a = 5;\n"
15630                    "//\n"
15631                    "// multi-line line comment\n"
15632                    "//\n"
15633                    "int oneTwoThree=123;",
15634                    Alignment));
15635 
15636   /* Test across comments and newlines */
15637   EXPECT_EQ("int a = 5;\n"
15638             "\n"
15639             "/* block comment */\n"
15640             "int oneTwoThree = 123;",
15641             format("int a = 5;\n"
15642                    "\n"
15643                    "/* block comment */\n"
15644                    "int oneTwoThree=123;",
15645                    Alignment));
15646 
15647   EXPECT_EQ("int a = 5;\n"
15648             "\n"
15649             "// line comment\n"
15650             "int oneTwoThree = 123;",
15651             format("int a = 5;\n"
15652                    "\n"
15653                    "// line comment\n"
15654                    "int oneTwoThree=123;",
15655                    Alignment));
15656 }
15657 
15658 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
15659   FormatStyle Alignment = getLLVMStyle();
15660   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15661   Alignment.AlignConsecutiveAssignments =
15662       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15663   verifyFormat("int a           = 5;\n"
15664                "int oneTwoThree = 123;",
15665                Alignment);
15666   verifyFormat("int a           = method();\n"
15667                "int oneTwoThree = 133;",
15668                Alignment);
15669   verifyFormat("a &= 5;\n"
15670                "bcd *= 5;\n"
15671                "ghtyf += 5;\n"
15672                "dvfvdb -= 5;\n"
15673                "a /= 5;\n"
15674                "vdsvsv %= 5;\n"
15675                "sfdbddfbdfbb ^= 5;\n"
15676                "dvsdsv |= 5;\n"
15677                "int dsvvdvsdvvv = 123;",
15678                Alignment);
15679   verifyFormat("int i = 1, j = 10;\n"
15680                "something = 2000;",
15681                Alignment);
15682   verifyFormat("something = 2000;\n"
15683                "int i = 1, j = 10;\n",
15684                Alignment);
15685   verifyFormat("something = 2000;\n"
15686                "another   = 911;\n"
15687                "int i = 1, j = 10;\n"
15688                "oneMore = 1;\n"
15689                "i       = 2;",
15690                Alignment);
15691   verifyFormat("int a   = 5;\n"
15692                "int one = 1;\n"
15693                "method();\n"
15694                "int oneTwoThree = 123;\n"
15695                "int oneTwo      = 12;",
15696                Alignment);
15697   verifyFormat("int oneTwoThree = 123;\n"
15698                "int oneTwo      = 12;\n"
15699                "method();\n",
15700                Alignment);
15701   verifyFormat("int oneTwoThree = 123; // comment\n"
15702                "int oneTwo      = 12;  // comment",
15703                Alignment);
15704 
15705   // Bug 25167
15706   /* Uncomment when fixed
15707     verifyFormat("#if A\n"
15708                  "#else\n"
15709                  "int aaaaaaaa = 12;\n"
15710                  "#endif\n"
15711                  "#if B\n"
15712                  "#else\n"
15713                  "int a = 12;\n"
15714                  "#endif\n",
15715                  Alignment);
15716     verifyFormat("enum foo {\n"
15717                  "#if A\n"
15718                  "#else\n"
15719                  "  aaaaaaaa = 12;\n"
15720                  "#endif\n"
15721                  "#if B\n"
15722                  "#else\n"
15723                  "  a = 12;\n"
15724                  "#endif\n"
15725                  "};\n",
15726                  Alignment);
15727   */
15728 
15729   Alignment.MaxEmptyLinesToKeep = 10;
15730   /* Test alignment across empty lines */
15731   EXPECT_EQ("int a           = 5;\n"
15732             "\n"
15733             "int oneTwoThree = 123;",
15734             format("int a       = 5;\n"
15735                    "\n"
15736                    "int oneTwoThree= 123;",
15737                    Alignment));
15738   EXPECT_EQ("int a           = 5;\n"
15739             "int one         = 1;\n"
15740             "\n"
15741             "int oneTwoThree = 123;",
15742             format("int a = 5;\n"
15743                    "int one = 1;\n"
15744                    "\n"
15745                    "int oneTwoThree = 123;",
15746                    Alignment));
15747   EXPECT_EQ("int a           = 5;\n"
15748             "int one         = 1;\n"
15749             "\n"
15750             "int oneTwoThree = 123;\n"
15751             "int oneTwo      = 12;",
15752             format("int a = 5;\n"
15753                    "int one = 1;\n"
15754                    "\n"
15755                    "int oneTwoThree = 123;\n"
15756                    "int oneTwo = 12;",
15757                    Alignment));
15758 
15759   /* Test across comments */
15760   EXPECT_EQ("int a           = 5;\n"
15761             "/* block comment */\n"
15762             "int oneTwoThree = 123;",
15763             format("int a = 5;\n"
15764                    "/* block comment */\n"
15765                    "int oneTwoThree=123;",
15766                    Alignment));
15767 
15768   EXPECT_EQ("int a           = 5;\n"
15769             "// line comment\n"
15770             "int oneTwoThree = 123;",
15771             format("int a = 5;\n"
15772                    "// line comment\n"
15773                    "int oneTwoThree=123;",
15774                    Alignment));
15775 
15776   /* Test across comments and newlines */
15777   EXPECT_EQ("int a           = 5;\n"
15778             "\n"
15779             "/* block comment */\n"
15780             "int oneTwoThree = 123;",
15781             format("int a = 5;\n"
15782                    "\n"
15783                    "/* block comment */\n"
15784                    "int oneTwoThree=123;",
15785                    Alignment));
15786 
15787   EXPECT_EQ("int a           = 5;\n"
15788             "\n"
15789             "// line comment\n"
15790             "int oneTwoThree = 123;",
15791             format("int a = 5;\n"
15792                    "\n"
15793                    "// line comment\n"
15794                    "int oneTwoThree=123;",
15795                    Alignment));
15796 
15797   EXPECT_EQ("int a           = 5;\n"
15798             "//\n"
15799             "// multi-line line comment\n"
15800             "//\n"
15801             "int oneTwoThree = 123;",
15802             format("int a = 5;\n"
15803                    "//\n"
15804                    "// multi-line line comment\n"
15805                    "//\n"
15806                    "int oneTwoThree=123;",
15807                    Alignment));
15808 
15809   EXPECT_EQ("int a           = 5;\n"
15810             "/*\n"
15811             " *  multi-line block comment\n"
15812             " */\n"
15813             "int oneTwoThree = 123;",
15814             format("int a = 5;\n"
15815                    "/*\n"
15816                    " *  multi-line block comment\n"
15817                    " */\n"
15818                    "int oneTwoThree=123;",
15819                    Alignment));
15820 
15821   EXPECT_EQ("int a           = 5;\n"
15822             "\n"
15823             "/* block comment */\n"
15824             "\n"
15825             "\n"
15826             "\n"
15827             "int oneTwoThree = 123;",
15828             format("int a = 5;\n"
15829                    "\n"
15830                    "/* block comment */\n"
15831                    "\n"
15832                    "\n"
15833                    "\n"
15834                    "int oneTwoThree=123;",
15835                    Alignment));
15836 
15837   EXPECT_EQ("int a           = 5;\n"
15838             "\n"
15839             "// line comment\n"
15840             "\n"
15841             "\n"
15842             "\n"
15843             "int oneTwoThree = 123;",
15844             format("int a = 5;\n"
15845                    "\n"
15846                    "// line comment\n"
15847                    "\n"
15848                    "\n"
15849                    "\n"
15850                    "int oneTwoThree=123;",
15851                    Alignment));
15852 
15853   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
15854   verifyFormat("#define A \\\n"
15855                "  int aaaa       = 12; \\\n"
15856                "  int b          = 23; \\\n"
15857                "  int ccc        = 234; \\\n"
15858                "  int dddddddddd = 2345;",
15859                Alignment);
15860   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
15861   verifyFormat("#define A               \\\n"
15862                "  int aaaa       = 12;  \\\n"
15863                "  int b          = 23;  \\\n"
15864                "  int ccc        = 234; \\\n"
15865                "  int dddddddddd = 2345;",
15866                Alignment);
15867   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
15868   verifyFormat("#define A                                                      "
15869                "                \\\n"
15870                "  int aaaa       = 12;                                         "
15871                "                \\\n"
15872                "  int b          = 23;                                         "
15873                "                \\\n"
15874                "  int ccc        = 234;                                        "
15875                "                \\\n"
15876                "  int dddddddddd = 2345;",
15877                Alignment);
15878   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
15879                "k = 4, int l = 5,\n"
15880                "                  int m = 6) {\n"
15881                "  int j      = 10;\n"
15882                "  otherThing = 1;\n"
15883                "}",
15884                Alignment);
15885   verifyFormat("void SomeFunction(int parameter = 0) {\n"
15886                "  int i   = 1;\n"
15887                "  int j   = 2;\n"
15888                "  int big = 10000;\n"
15889                "}",
15890                Alignment);
15891   verifyFormat("class C {\n"
15892                "public:\n"
15893                "  int i            = 1;\n"
15894                "  virtual void f() = 0;\n"
15895                "};",
15896                Alignment);
15897   verifyFormat("int i = 1;\n"
15898                "if (SomeType t = getSomething()) {\n"
15899                "}\n"
15900                "int j   = 2;\n"
15901                "int big = 10000;",
15902                Alignment);
15903   verifyFormat("int j = 7;\n"
15904                "for (int k = 0; k < N; ++k) {\n"
15905                "}\n"
15906                "int j   = 2;\n"
15907                "int big = 10000;\n"
15908                "}",
15909                Alignment);
15910   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15911   verifyFormat("int i = 1;\n"
15912                "LooooooooooongType loooooooooooooooooooooongVariable\n"
15913                "    = someLooooooooooooooooongFunction();\n"
15914                "int j = 2;",
15915                Alignment);
15916   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
15917   verifyFormat("int i = 1;\n"
15918                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
15919                "    someLooooooooooooooooongFunction();\n"
15920                "int j = 2;",
15921                Alignment);
15922 
15923   verifyFormat("auto lambda = []() {\n"
15924                "  auto i = 0;\n"
15925                "  return 0;\n"
15926                "};\n"
15927                "int i  = 0;\n"
15928                "auto v = type{\n"
15929                "    i = 1,   //\n"
15930                "    (i = 2), //\n"
15931                "    i = 3    //\n"
15932                "};",
15933                Alignment);
15934 
15935   verifyFormat(
15936       "int i      = 1;\n"
15937       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
15938       "                          loooooooooooooooooooooongParameterB);\n"
15939       "int j      = 2;",
15940       Alignment);
15941 
15942   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
15943                "          typename B   = very_long_type_name_1,\n"
15944                "          typename T_2 = very_long_type_name_2>\n"
15945                "auto foo() {}\n",
15946                Alignment);
15947   verifyFormat("int a, b = 1;\n"
15948                "int c  = 2;\n"
15949                "int dd = 3;\n",
15950                Alignment);
15951   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
15952                "float b[1][] = {{3.f}};\n",
15953                Alignment);
15954   verifyFormat("for (int i = 0; i < 1; i++)\n"
15955                "  int x = 1;\n",
15956                Alignment);
15957   verifyFormat("for (i = 0; i < 1; i++)\n"
15958                "  x = 1;\n"
15959                "y = 1;\n",
15960                Alignment);
15961 
15962   Alignment.ReflowComments = true;
15963   Alignment.ColumnLimit = 50;
15964   EXPECT_EQ("int x   = 0;\n"
15965             "int yy  = 1; /// specificlennospace\n"
15966             "int zzz = 2;\n",
15967             format("int x   = 0;\n"
15968                    "int yy  = 1; ///specificlennospace\n"
15969                    "int zzz = 2;\n",
15970                    Alignment));
15971 }
15972 
15973 TEST_F(FormatTest, AlignConsecutiveAssignments) {
15974   FormatStyle Alignment = getLLVMStyle();
15975   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15976   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15977   verifyFormat("int a = 5;\n"
15978                "int oneTwoThree = 123;",
15979                Alignment);
15980   verifyFormat("int a = 5;\n"
15981                "int oneTwoThree = 123;",
15982                Alignment);
15983 
15984   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15985   verifyFormat("int a           = 5;\n"
15986                "int oneTwoThree = 123;",
15987                Alignment);
15988   verifyFormat("int a           = method();\n"
15989                "int oneTwoThree = 133;",
15990                Alignment);
15991   verifyFormat("a &= 5;\n"
15992                "bcd *= 5;\n"
15993                "ghtyf += 5;\n"
15994                "dvfvdb -= 5;\n"
15995                "a /= 5;\n"
15996                "vdsvsv %= 5;\n"
15997                "sfdbddfbdfbb ^= 5;\n"
15998                "dvsdsv |= 5;\n"
15999                "int dsvvdvsdvvv = 123;",
16000                Alignment);
16001   verifyFormat("int i = 1, j = 10;\n"
16002                "something = 2000;",
16003                Alignment);
16004   verifyFormat("something = 2000;\n"
16005                "int i = 1, j = 10;\n",
16006                Alignment);
16007   verifyFormat("something = 2000;\n"
16008                "another   = 911;\n"
16009                "int i = 1, j = 10;\n"
16010                "oneMore = 1;\n"
16011                "i       = 2;",
16012                Alignment);
16013   verifyFormat("int a   = 5;\n"
16014                "int one = 1;\n"
16015                "method();\n"
16016                "int oneTwoThree = 123;\n"
16017                "int oneTwo      = 12;",
16018                Alignment);
16019   verifyFormat("int oneTwoThree = 123;\n"
16020                "int oneTwo      = 12;\n"
16021                "method();\n",
16022                Alignment);
16023   verifyFormat("int oneTwoThree = 123; // comment\n"
16024                "int oneTwo      = 12;  // comment",
16025                Alignment);
16026 
16027   // Bug 25167
16028   /* Uncomment when fixed
16029     verifyFormat("#if A\n"
16030                  "#else\n"
16031                  "int aaaaaaaa = 12;\n"
16032                  "#endif\n"
16033                  "#if B\n"
16034                  "#else\n"
16035                  "int a = 12;\n"
16036                  "#endif\n",
16037                  Alignment);
16038     verifyFormat("enum foo {\n"
16039                  "#if A\n"
16040                  "#else\n"
16041                  "  aaaaaaaa = 12;\n"
16042                  "#endif\n"
16043                  "#if B\n"
16044                  "#else\n"
16045                  "  a = 12;\n"
16046                  "#endif\n"
16047                  "};\n",
16048                  Alignment);
16049   */
16050 
16051   EXPECT_EQ("int a = 5;\n"
16052             "\n"
16053             "int oneTwoThree = 123;",
16054             format("int a       = 5;\n"
16055                    "\n"
16056                    "int oneTwoThree= 123;",
16057                    Alignment));
16058   EXPECT_EQ("int a   = 5;\n"
16059             "int one = 1;\n"
16060             "\n"
16061             "int oneTwoThree = 123;",
16062             format("int a = 5;\n"
16063                    "int one = 1;\n"
16064                    "\n"
16065                    "int oneTwoThree = 123;",
16066                    Alignment));
16067   EXPECT_EQ("int a   = 5;\n"
16068             "int one = 1;\n"
16069             "\n"
16070             "int oneTwoThree = 123;\n"
16071             "int oneTwo      = 12;",
16072             format("int a = 5;\n"
16073                    "int one = 1;\n"
16074                    "\n"
16075                    "int oneTwoThree = 123;\n"
16076                    "int oneTwo = 12;",
16077                    Alignment));
16078   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16079   verifyFormat("#define A \\\n"
16080                "  int aaaa       = 12; \\\n"
16081                "  int b          = 23; \\\n"
16082                "  int ccc        = 234; \\\n"
16083                "  int dddddddddd = 2345;",
16084                Alignment);
16085   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16086   verifyFormat("#define A               \\\n"
16087                "  int aaaa       = 12;  \\\n"
16088                "  int b          = 23;  \\\n"
16089                "  int ccc        = 234; \\\n"
16090                "  int dddddddddd = 2345;",
16091                Alignment);
16092   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16093   verifyFormat("#define A                                                      "
16094                "                \\\n"
16095                "  int aaaa       = 12;                                         "
16096                "                \\\n"
16097                "  int b          = 23;                                         "
16098                "                \\\n"
16099                "  int ccc        = 234;                                        "
16100                "                \\\n"
16101                "  int dddddddddd = 2345;",
16102                Alignment);
16103   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16104                "k = 4, int l = 5,\n"
16105                "                  int m = 6) {\n"
16106                "  int j      = 10;\n"
16107                "  otherThing = 1;\n"
16108                "}",
16109                Alignment);
16110   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16111                "  int i   = 1;\n"
16112                "  int j   = 2;\n"
16113                "  int big = 10000;\n"
16114                "}",
16115                Alignment);
16116   verifyFormat("class C {\n"
16117                "public:\n"
16118                "  int i            = 1;\n"
16119                "  virtual void f() = 0;\n"
16120                "};",
16121                Alignment);
16122   verifyFormat("int i = 1;\n"
16123                "if (SomeType t = getSomething()) {\n"
16124                "}\n"
16125                "int j   = 2;\n"
16126                "int big = 10000;",
16127                Alignment);
16128   verifyFormat("int j = 7;\n"
16129                "for (int k = 0; k < N; ++k) {\n"
16130                "}\n"
16131                "int j   = 2;\n"
16132                "int big = 10000;\n"
16133                "}",
16134                Alignment);
16135   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16136   verifyFormat("int i = 1;\n"
16137                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16138                "    = someLooooooooooooooooongFunction();\n"
16139                "int j = 2;",
16140                Alignment);
16141   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16142   verifyFormat("int i = 1;\n"
16143                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16144                "    someLooooooooooooooooongFunction();\n"
16145                "int j = 2;",
16146                Alignment);
16147 
16148   verifyFormat("auto lambda = []() {\n"
16149                "  auto i = 0;\n"
16150                "  return 0;\n"
16151                "};\n"
16152                "int i  = 0;\n"
16153                "auto v = type{\n"
16154                "    i = 1,   //\n"
16155                "    (i = 2), //\n"
16156                "    i = 3    //\n"
16157                "};",
16158                Alignment);
16159 
16160   verifyFormat(
16161       "int i      = 1;\n"
16162       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16163       "                          loooooooooooooooooooooongParameterB);\n"
16164       "int j      = 2;",
16165       Alignment);
16166 
16167   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16168                "          typename B   = very_long_type_name_1,\n"
16169                "          typename T_2 = very_long_type_name_2>\n"
16170                "auto foo() {}\n",
16171                Alignment);
16172   verifyFormat("int a, b = 1;\n"
16173                "int c  = 2;\n"
16174                "int dd = 3;\n",
16175                Alignment);
16176   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16177                "float b[1][] = {{3.f}};\n",
16178                Alignment);
16179   verifyFormat("for (int i = 0; i < 1; i++)\n"
16180                "  int x = 1;\n",
16181                Alignment);
16182   verifyFormat("for (i = 0; i < 1; i++)\n"
16183                "  x = 1;\n"
16184                "y = 1;\n",
16185                Alignment);
16186 
16187   Alignment.ReflowComments = true;
16188   Alignment.ColumnLimit = 50;
16189   EXPECT_EQ("int x   = 0;\n"
16190             "int yy  = 1; /// specificlennospace\n"
16191             "int zzz = 2;\n",
16192             format("int x   = 0;\n"
16193                    "int yy  = 1; ///specificlennospace\n"
16194                    "int zzz = 2;\n",
16195                    Alignment));
16196 }
16197 
16198 TEST_F(FormatTest, AlignConsecutiveBitFields) {
16199   FormatStyle Alignment = getLLVMStyle();
16200   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
16201   verifyFormat("int const a     : 5;\n"
16202                "int oneTwoThree : 23;",
16203                Alignment);
16204 
16205   // Initializers are allowed starting with c++2a
16206   verifyFormat("int const a     : 5 = 1;\n"
16207                "int oneTwoThree : 23 = 0;",
16208                Alignment);
16209 
16210   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16211   verifyFormat("int const a           : 5;\n"
16212                "int       oneTwoThree : 23;",
16213                Alignment);
16214 
16215   verifyFormat("int const a           : 5;  // comment\n"
16216                "int       oneTwoThree : 23; // comment",
16217                Alignment);
16218 
16219   verifyFormat("int const a           : 5 = 1;\n"
16220                "int       oneTwoThree : 23 = 0;",
16221                Alignment);
16222 
16223   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16224   verifyFormat("int const a           : 5  = 1;\n"
16225                "int       oneTwoThree : 23 = 0;",
16226                Alignment);
16227   verifyFormat("int const a           : 5  = {1};\n"
16228                "int       oneTwoThree : 23 = 0;",
16229                Alignment);
16230 
16231   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
16232   verifyFormat("int const a          :5;\n"
16233                "int       oneTwoThree:23;",
16234                Alignment);
16235 
16236   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
16237   verifyFormat("int const a           :5;\n"
16238                "int       oneTwoThree :23;",
16239                Alignment);
16240 
16241   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
16242   verifyFormat("int const a          : 5;\n"
16243                "int       oneTwoThree: 23;",
16244                Alignment);
16245 
16246   // Known limitations: ':' is only recognized as a bitfield colon when
16247   // followed by a number.
16248   /*
16249   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
16250                "int a           : 5;",
16251                Alignment);
16252   */
16253 }
16254 
16255 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
16256   FormatStyle Alignment = getLLVMStyle();
16257   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16258   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16259   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16260   verifyFormat("float const a = 5;\n"
16261                "int oneTwoThree = 123;",
16262                Alignment);
16263   verifyFormat("int a = 5;\n"
16264                "float const oneTwoThree = 123;",
16265                Alignment);
16266 
16267   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16268   verifyFormat("float const a = 5;\n"
16269                "int         oneTwoThree = 123;",
16270                Alignment);
16271   verifyFormat("int         a = method();\n"
16272                "float const oneTwoThree = 133;",
16273                Alignment);
16274   verifyFormat("int i = 1, j = 10;\n"
16275                "something = 2000;",
16276                Alignment);
16277   verifyFormat("something = 2000;\n"
16278                "int i = 1, j = 10;\n",
16279                Alignment);
16280   verifyFormat("float      something = 2000;\n"
16281                "double     another = 911;\n"
16282                "int        i = 1, j = 10;\n"
16283                "const int *oneMore = 1;\n"
16284                "unsigned   i = 2;",
16285                Alignment);
16286   verifyFormat("float a = 5;\n"
16287                "int   one = 1;\n"
16288                "method();\n"
16289                "const double       oneTwoThree = 123;\n"
16290                "const unsigned int oneTwo = 12;",
16291                Alignment);
16292   verifyFormat("int      oneTwoThree{0}; // comment\n"
16293                "unsigned oneTwo;         // comment",
16294                Alignment);
16295   verifyFormat("unsigned int       *a;\n"
16296                "int                *b;\n"
16297                "unsigned int Const *c;\n"
16298                "unsigned int const *d;\n"
16299                "unsigned int Const &e;\n"
16300                "unsigned int const &f;",
16301                Alignment);
16302   verifyFormat("Const unsigned int *c;\n"
16303                "const unsigned int *d;\n"
16304                "Const unsigned int &e;\n"
16305                "const unsigned int &f;\n"
16306                "const unsigned      g;\n"
16307                "Const unsigned      h;",
16308                Alignment);
16309   EXPECT_EQ("float const a = 5;\n"
16310             "\n"
16311             "int oneTwoThree = 123;",
16312             format("float const   a = 5;\n"
16313                    "\n"
16314                    "int           oneTwoThree= 123;",
16315                    Alignment));
16316   EXPECT_EQ("float a = 5;\n"
16317             "int   one = 1;\n"
16318             "\n"
16319             "unsigned oneTwoThree = 123;",
16320             format("float    a = 5;\n"
16321                    "int      one = 1;\n"
16322                    "\n"
16323                    "unsigned oneTwoThree = 123;",
16324                    Alignment));
16325   EXPECT_EQ("float a = 5;\n"
16326             "int   one = 1;\n"
16327             "\n"
16328             "unsigned oneTwoThree = 123;\n"
16329             "int      oneTwo = 12;",
16330             format("float    a = 5;\n"
16331                    "int one = 1;\n"
16332                    "\n"
16333                    "unsigned oneTwoThree = 123;\n"
16334                    "int oneTwo = 12;",
16335                    Alignment));
16336   // Function prototype alignment
16337   verifyFormat("int    a();\n"
16338                "double b();",
16339                Alignment);
16340   verifyFormat("int    a(int x);\n"
16341                "double b();",
16342                Alignment);
16343   unsigned OldColumnLimit = Alignment.ColumnLimit;
16344   // We need to set ColumnLimit to zero, in order to stress nested alignments,
16345   // otherwise the function parameters will be re-flowed onto a single line.
16346   Alignment.ColumnLimit = 0;
16347   EXPECT_EQ("int    a(int   x,\n"
16348             "         float y);\n"
16349             "double b(int    x,\n"
16350             "         double y);",
16351             format("int a(int x,\n"
16352                    " float y);\n"
16353                    "double b(int x,\n"
16354                    " double y);",
16355                    Alignment));
16356   // This ensures that function parameters of function declarations are
16357   // correctly indented when their owning functions are indented.
16358   // The failure case here is for 'double y' to not be indented enough.
16359   EXPECT_EQ("double a(int x);\n"
16360             "int    b(int    y,\n"
16361             "         double z);",
16362             format("double a(int x);\n"
16363                    "int b(int y,\n"
16364                    " double z);",
16365                    Alignment));
16366   // Set ColumnLimit low so that we induce wrapping immediately after
16367   // the function name and opening paren.
16368   Alignment.ColumnLimit = 13;
16369   verifyFormat("int function(\n"
16370                "    int  x,\n"
16371                "    bool y);",
16372                Alignment);
16373   Alignment.ColumnLimit = OldColumnLimit;
16374   // Ensure function pointers don't screw up recursive alignment
16375   verifyFormat("int    a(int x, void (*fp)(int y));\n"
16376                "double b();",
16377                Alignment);
16378   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16379   // Ensure recursive alignment is broken by function braces, so that the
16380   // "a = 1" does not align with subsequent assignments inside the function
16381   // body.
16382   verifyFormat("int func(int a = 1) {\n"
16383                "  int b  = 2;\n"
16384                "  int cc = 3;\n"
16385                "}",
16386                Alignment);
16387   verifyFormat("float      something = 2000;\n"
16388                "double     another   = 911;\n"
16389                "int        i = 1, j = 10;\n"
16390                "const int *oneMore = 1;\n"
16391                "unsigned   i       = 2;",
16392                Alignment);
16393   verifyFormat("int      oneTwoThree = {0}; // comment\n"
16394                "unsigned oneTwo      = 0;   // comment",
16395                Alignment);
16396   // Make sure that scope is correctly tracked, in the absence of braces
16397   verifyFormat("for (int i = 0; i < n; i++)\n"
16398                "  j = i;\n"
16399                "double x = 1;\n",
16400                Alignment);
16401   verifyFormat("if (int i = 0)\n"
16402                "  j = i;\n"
16403                "double x = 1;\n",
16404                Alignment);
16405   // Ensure operator[] and operator() are comprehended
16406   verifyFormat("struct test {\n"
16407                "  long long int foo();\n"
16408                "  int           operator[](int a);\n"
16409                "  double        bar();\n"
16410                "};\n",
16411                Alignment);
16412   verifyFormat("struct test {\n"
16413                "  long long int foo();\n"
16414                "  int           operator()(int a);\n"
16415                "  double        bar();\n"
16416                "};\n",
16417                Alignment);
16418 
16419   // PAS_Right
16420   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16421             "  int const i   = 1;\n"
16422             "  int      *j   = 2;\n"
16423             "  int       big = 10000;\n"
16424             "\n"
16425             "  unsigned oneTwoThree = 123;\n"
16426             "  int      oneTwo      = 12;\n"
16427             "  method();\n"
16428             "  float k  = 2;\n"
16429             "  int   ll = 10000;\n"
16430             "}",
16431             format("void SomeFunction(int parameter= 0) {\n"
16432                    " int const  i= 1;\n"
16433                    "  int *j=2;\n"
16434                    " int big  =  10000;\n"
16435                    "\n"
16436                    "unsigned oneTwoThree  =123;\n"
16437                    "int oneTwo = 12;\n"
16438                    "  method();\n"
16439                    "float k= 2;\n"
16440                    "int ll=10000;\n"
16441                    "}",
16442                    Alignment));
16443   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16444             "  int const i   = 1;\n"
16445             "  int     **j   = 2, ***k;\n"
16446             "  int      &k   = i;\n"
16447             "  int     &&l   = i + j;\n"
16448             "  int       big = 10000;\n"
16449             "\n"
16450             "  unsigned oneTwoThree = 123;\n"
16451             "  int      oneTwo      = 12;\n"
16452             "  method();\n"
16453             "  float k  = 2;\n"
16454             "  int   ll = 10000;\n"
16455             "}",
16456             format("void SomeFunction(int parameter= 0) {\n"
16457                    " int const  i= 1;\n"
16458                    "  int **j=2,***k;\n"
16459                    "int &k=i;\n"
16460                    "int &&l=i+j;\n"
16461                    " int big  =  10000;\n"
16462                    "\n"
16463                    "unsigned oneTwoThree  =123;\n"
16464                    "int oneTwo = 12;\n"
16465                    "  method();\n"
16466                    "float k= 2;\n"
16467                    "int ll=10000;\n"
16468                    "}",
16469                    Alignment));
16470   // variables are aligned at their name, pointers are at the right most
16471   // position
16472   verifyFormat("int   *a;\n"
16473                "int  **b;\n"
16474                "int ***c;\n"
16475                "int    foobar;\n",
16476                Alignment);
16477 
16478   // PAS_Left
16479   FormatStyle AlignmentLeft = Alignment;
16480   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
16481   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16482             "  int const i   = 1;\n"
16483             "  int*      j   = 2;\n"
16484             "  int       big = 10000;\n"
16485             "\n"
16486             "  unsigned oneTwoThree = 123;\n"
16487             "  int      oneTwo      = 12;\n"
16488             "  method();\n"
16489             "  float k  = 2;\n"
16490             "  int   ll = 10000;\n"
16491             "}",
16492             format("void SomeFunction(int parameter= 0) {\n"
16493                    " int const  i= 1;\n"
16494                    "  int *j=2;\n"
16495                    " int big  =  10000;\n"
16496                    "\n"
16497                    "unsigned oneTwoThree  =123;\n"
16498                    "int oneTwo = 12;\n"
16499                    "  method();\n"
16500                    "float k= 2;\n"
16501                    "int ll=10000;\n"
16502                    "}",
16503                    AlignmentLeft));
16504   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16505             "  int const i   = 1;\n"
16506             "  int**     j   = 2;\n"
16507             "  int&      k   = i;\n"
16508             "  int&&     l   = i + j;\n"
16509             "  int       big = 10000;\n"
16510             "\n"
16511             "  unsigned oneTwoThree = 123;\n"
16512             "  int      oneTwo      = 12;\n"
16513             "  method();\n"
16514             "  float k  = 2;\n"
16515             "  int   ll = 10000;\n"
16516             "}",
16517             format("void SomeFunction(int parameter= 0) {\n"
16518                    " int const  i= 1;\n"
16519                    "  int **j=2;\n"
16520                    "int &k=i;\n"
16521                    "int &&l=i+j;\n"
16522                    " int big  =  10000;\n"
16523                    "\n"
16524                    "unsigned oneTwoThree  =123;\n"
16525                    "int oneTwo = 12;\n"
16526                    "  method();\n"
16527                    "float k= 2;\n"
16528                    "int ll=10000;\n"
16529                    "}",
16530                    AlignmentLeft));
16531   // variables are aligned at their name, pointers are at the left most position
16532   verifyFormat("int*   a;\n"
16533                "int**  b;\n"
16534                "int*** c;\n"
16535                "int    foobar;\n",
16536                AlignmentLeft);
16537 
16538   // PAS_Middle
16539   FormatStyle AlignmentMiddle = Alignment;
16540   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
16541   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16542             "  int const i   = 1;\n"
16543             "  int *     j   = 2;\n"
16544             "  int       big = 10000;\n"
16545             "\n"
16546             "  unsigned oneTwoThree = 123;\n"
16547             "  int      oneTwo      = 12;\n"
16548             "  method();\n"
16549             "  float k  = 2;\n"
16550             "  int   ll = 10000;\n"
16551             "}",
16552             format("void SomeFunction(int parameter= 0) {\n"
16553                    " int const  i= 1;\n"
16554                    "  int *j=2;\n"
16555                    " int big  =  10000;\n"
16556                    "\n"
16557                    "unsigned oneTwoThree  =123;\n"
16558                    "int oneTwo = 12;\n"
16559                    "  method();\n"
16560                    "float k= 2;\n"
16561                    "int ll=10000;\n"
16562                    "}",
16563                    AlignmentMiddle));
16564   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16565             "  int const i   = 1;\n"
16566             "  int **    j   = 2, ***k;\n"
16567             "  int &     k   = i;\n"
16568             "  int &&    l   = i + j;\n"
16569             "  int       big = 10000;\n"
16570             "\n"
16571             "  unsigned oneTwoThree = 123;\n"
16572             "  int      oneTwo      = 12;\n"
16573             "  method();\n"
16574             "  float k  = 2;\n"
16575             "  int   ll = 10000;\n"
16576             "}",
16577             format("void SomeFunction(int parameter= 0) {\n"
16578                    " int const  i= 1;\n"
16579                    "  int **j=2,***k;\n"
16580                    "int &k=i;\n"
16581                    "int &&l=i+j;\n"
16582                    " int big  =  10000;\n"
16583                    "\n"
16584                    "unsigned oneTwoThree  =123;\n"
16585                    "int oneTwo = 12;\n"
16586                    "  method();\n"
16587                    "float k= 2;\n"
16588                    "int ll=10000;\n"
16589                    "}",
16590                    AlignmentMiddle));
16591   // variables are aligned at their name, pointers are in the middle
16592   verifyFormat("int *   a;\n"
16593                "int *   b;\n"
16594                "int *** c;\n"
16595                "int     foobar;\n",
16596                AlignmentMiddle);
16597 
16598   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16599   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16600   verifyFormat("#define A \\\n"
16601                "  int       aaaa = 12; \\\n"
16602                "  float     b = 23; \\\n"
16603                "  const int ccc = 234; \\\n"
16604                "  unsigned  dddddddddd = 2345;",
16605                Alignment);
16606   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16607   verifyFormat("#define A              \\\n"
16608                "  int       aaaa = 12; \\\n"
16609                "  float     b = 23;    \\\n"
16610                "  const int ccc = 234; \\\n"
16611                "  unsigned  dddddddddd = 2345;",
16612                Alignment);
16613   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16614   Alignment.ColumnLimit = 30;
16615   verifyFormat("#define A                    \\\n"
16616                "  int       aaaa = 12;       \\\n"
16617                "  float     b = 23;          \\\n"
16618                "  const int ccc = 234;       \\\n"
16619                "  int       dddddddddd = 2345;",
16620                Alignment);
16621   Alignment.ColumnLimit = 80;
16622   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16623                "k = 4, int l = 5,\n"
16624                "                  int m = 6) {\n"
16625                "  const int j = 10;\n"
16626                "  otherThing = 1;\n"
16627                "}",
16628                Alignment);
16629   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16630                "  int const i = 1;\n"
16631                "  int      *j = 2;\n"
16632                "  int       big = 10000;\n"
16633                "}",
16634                Alignment);
16635   verifyFormat("class C {\n"
16636                "public:\n"
16637                "  int          i = 1;\n"
16638                "  virtual void f() = 0;\n"
16639                "};",
16640                Alignment);
16641   verifyFormat("float i = 1;\n"
16642                "if (SomeType t = getSomething()) {\n"
16643                "}\n"
16644                "const unsigned j = 2;\n"
16645                "int            big = 10000;",
16646                Alignment);
16647   verifyFormat("float j = 7;\n"
16648                "for (int k = 0; k < N; ++k) {\n"
16649                "}\n"
16650                "unsigned j = 2;\n"
16651                "int      big = 10000;\n"
16652                "}",
16653                Alignment);
16654   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16655   verifyFormat("float              i = 1;\n"
16656                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16657                "    = someLooooooooooooooooongFunction();\n"
16658                "int j = 2;",
16659                Alignment);
16660   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16661   verifyFormat("int                i = 1;\n"
16662                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16663                "    someLooooooooooooooooongFunction();\n"
16664                "int j = 2;",
16665                Alignment);
16666 
16667   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16668   verifyFormat("auto lambda = []() {\n"
16669                "  auto  ii = 0;\n"
16670                "  float j  = 0;\n"
16671                "  return 0;\n"
16672                "};\n"
16673                "int   i  = 0;\n"
16674                "float i2 = 0;\n"
16675                "auto  v  = type{\n"
16676                "    i = 1,   //\n"
16677                "    (i = 2), //\n"
16678                "    i = 3    //\n"
16679                "};",
16680                Alignment);
16681   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16682 
16683   verifyFormat(
16684       "int      i = 1;\n"
16685       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16686       "                          loooooooooooooooooooooongParameterB);\n"
16687       "int      j = 2;",
16688       Alignment);
16689 
16690   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
16691   // We expect declarations and assignments to align, as long as it doesn't
16692   // exceed the column limit, starting a new alignment sequence whenever it
16693   // happens.
16694   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16695   Alignment.ColumnLimit = 30;
16696   verifyFormat("float    ii              = 1;\n"
16697                "unsigned j               = 2;\n"
16698                "int someVerylongVariable = 1;\n"
16699                "AnotherLongType  ll = 123456;\n"
16700                "VeryVeryLongType k  = 2;\n"
16701                "int              myvar = 1;",
16702                Alignment);
16703   Alignment.ColumnLimit = 80;
16704   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16705 
16706   verifyFormat(
16707       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
16708       "          typename LongType, typename B>\n"
16709       "auto foo() {}\n",
16710       Alignment);
16711   verifyFormat("float a, b = 1;\n"
16712                "int   c = 2;\n"
16713                "int   dd = 3;\n",
16714                Alignment);
16715   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
16716                "float b[1][] = {{3.f}};\n",
16717                Alignment);
16718   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16719   verifyFormat("float a, b = 1;\n"
16720                "int   c  = 2;\n"
16721                "int   dd = 3;\n",
16722                Alignment);
16723   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
16724                "float b[1][] = {{3.f}};\n",
16725                Alignment);
16726   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16727 
16728   Alignment.ColumnLimit = 30;
16729   Alignment.BinPackParameters = false;
16730   verifyFormat("void foo(float     a,\n"
16731                "         float     b,\n"
16732                "         int       c,\n"
16733                "         uint32_t *d) {\n"
16734                "  int   *e = 0;\n"
16735                "  float  f = 0;\n"
16736                "  double g = 0;\n"
16737                "}\n"
16738                "void bar(ino_t     a,\n"
16739                "         int       b,\n"
16740                "         uint32_t *c,\n"
16741                "         bool      d) {}\n",
16742                Alignment);
16743   Alignment.BinPackParameters = true;
16744   Alignment.ColumnLimit = 80;
16745 
16746   // Bug 33507
16747   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16748   verifyFormat(
16749       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
16750       "  static const Version verVs2017;\n"
16751       "  return true;\n"
16752       "});\n",
16753       Alignment);
16754   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16755 
16756   // See llvm.org/PR35641
16757   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16758   verifyFormat("int func() { //\n"
16759                "  int      b;\n"
16760                "  unsigned c;\n"
16761                "}",
16762                Alignment);
16763 
16764   // See PR37175
16765   FormatStyle Style = getMozillaStyle();
16766   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16767   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
16768             "foo(int a);",
16769             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
16770 
16771   Alignment.PointerAlignment = FormatStyle::PAS_Left;
16772   verifyFormat("unsigned int*       a;\n"
16773                "int*                b;\n"
16774                "unsigned int Const* c;\n"
16775                "unsigned int const* d;\n"
16776                "unsigned int Const& e;\n"
16777                "unsigned int const& f;",
16778                Alignment);
16779   verifyFormat("Const unsigned int* c;\n"
16780                "const unsigned int* d;\n"
16781                "Const unsigned int& e;\n"
16782                "const unsigned int& f;\n"
16783                "const unsigned      g;\n"
16784                "Const unsigned      h;",
16785                Alignment);
16786 
16787   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16788   verifyFormat("unsigned int *       a;\n"
16789                "int *                b;\n"
16790                "unsigned int Const * c;\n"
16791                "unsigned int const * d;\n"
16792                "unsigned int Const & e;\n"
16793                "unsigned int const & f;",
16794                Alignment);
16795   verifyFormat("Const unsigned int * c;\n"
16796                "const unsigned int * d;\n"
16797                "Const unsigned int & e;\n"
16798                "const unsigned int & f;\n"
16799                "const unsigned       g;\n"
16800                "Const unsigned       h;",
16801                Alignment);
16802 }
16803 
16804 TEST_F(FormatTest, AlignWithLineBreaks) {
16805   auto Style = getLLVMStyleWithColumns(120);
16806 
16807   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
16808   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16809   verifyFormat("void foo() {\n"
16810                "  int myVar = 5;\n"
16811                "  double x = 3.14;\n"
16812                "  auto str = \"Hello \"\n"
16813                "             \"World\";\n"
16814                "  auto s = \"Hello \"\n"
16815                "           \"Again\";\n"
16816                "}",
16817                Style);
16818 
16819   // clang-format off
16820   verifyFormat("void foo() {\n"
16821                "  const int capacityBefore = Entries.capacity();\n"
16822                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16823                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16824                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16825                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16826                "}",
16827                Style);
16828   // clang-format on
16829 
16830   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16831   verifyFormat("void foo() {\n"
16832                "  int myVar = 5;\n"
16833                "  double x  = 3.14;\n"
16834                "  auto str  = \"Hello \"\n"
16835                "              \"World\";\n"
16836                "  auto s    = \"Hello \"\n"
16837                "              \"Again\";\n"
16838                "}",
16839                Style);
16840 
16841   // clang-format off
16842   verifyFormat("void foo() {\n"
16843                "  const int capacityBefore = Entries.capacity();\n"
16844                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16845                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16846                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16847                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16848                "}",
16849                Style);
16850   // clang-format on
16851 
16852   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16853   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16854   verifyFormat("void foo() {\n"
16855                "  int    myVar = 5;\n"
16856                "  double x = 3.14;\n"
16857                "  auto   str = \"Hello \"\n"
16858                "               \"World\";\n"
16859                "  auto   s = \"Hello \"\n"
16860                "             \"Again\";\n"
16861                "}",
16862                Style);
16863 
16864   // clang-format off
16865   verifyFormat("void foo() {\n"
16866                "  const int  capacityBefore = Entries.capacity();\n"
16867                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16868                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16869                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16870                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16871                "}",
16872                Style);
16873   // clang-format on
16874 
16875   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16876   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16877 
16878   verifyFormat("void foo() {\n"
16879                "  int    myVar = 5;\n"
16880                "  double x     = 3.14;\n"
16881                "  auto   str   = \"Hello \"\n"
16882                "                 \"World\";\n"
16883                "  auto   s     = \"Hello \"\n"
16884                "                 \"Again\";\n"
16885                "}",
16886                Style);
16887 
16888   // clang-format off
16889   verifyFormat("void foo() {\n"
16890                "  const int  capacityBefore = Entries.capacity();\n"
16891                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16892                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16893                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16894                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16895                "}",
16896                Style);
16897   // clang-format on
16898 
16899   Style = getLLVMStyleWithColumns(120);
16900   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16901   Style.ContinuationIndentWidth = 4;
16902   Style.IndentWidth = 4;
16903 
16904   // clang-format off
16905   verifyFormat("void SomeFunc() {\n"
16906                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16907                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16908                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16909                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16910                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16911                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16912                "}",
16913                Style);
16914   // clang-format on
16915 
16916   Style.BinPackArguments = false;
16917 
16918   // clang-format off
16919   verifyFormat("void SomeFunc() {\n"
16920                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
16921                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16922                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
16923                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16924                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
16925                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16926                "}",
16927                Style);
16928   // clang-format on
16929 }
16930 
16931 TEST_F(FormatTest, AlignWithInitializerPeriods) {
16932   auto Style = getLLVMStyleWithColumns(60);
16933 
16934   verifyFormat("void foo1(void) {\n"
16935                "  BYTE p[1] = 1;\n"
16936                "  A B = {.one_foooooooooooooooo = 2,\n"
16937                "         .two_fooooooooooooo = 3,\n"
16938                "         .three_fooooooooooooo = 4};\n"
16939                "  BYTE payload = 2;\n"
16940                "}",
16941                Style);
16942 
16943   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16944   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16945   verifyFormat("void foo2(void) {\n"
16946                "  BYTE p[1]    = 1;\n"
16947                "  A B          = {.one_foooooooooooooooo = 2,\n"
16948                "                  .two_fooooooooooooo    = 3,\n"
16949                "                  .three_fooooooooooooo  = 4};\n"
16950                "  BYTE payload = 2;\n"
16951                "}",
16952                Style);
16953 
16954   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16955   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16956   verifyFormat("void foo3(void) {\n"
16957                "  BYTE p[1] = 1;\n"
16958                "  A    B = {.one_foooooooooooooooo = 2,\n"
16959                "            .two_fooooooooooooo = 3,\n"
16960                "            .three_fooooooooooooo = 4};\n"
16961                "  BYTE payload = 2;\n"
16962                "}",
16963                Style);
16964 
16965   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16966   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16967   verifyFormat("void foo4(void) {\n"
16968                "  BYTE p[1]    = 1;\n"
16969                "  A    B       = {.one_foooooooooooooooo = 2,\n"
16970                "                  .two_fooooooooooooo    = 3,\n"
16971                "                  .three_fooooooooooooo  = 4};\n"
16972                "  BYTE payload = 2;\n"
16973                "}",
16974                Style);
16975 }
16976 
16977 TEST_F(FormatTest, LinuxBraceBreaking) {
16978   FormatStyle LinuxBraceStyle = getLLVMStyle();
16979   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
16980   verifyFormat("namespace a\n"
16981                "{\n"
16982                "class A\n"
16983                "{\n"
16984                "  void f()\n"
16985                "  {\n"
16986                "    if (true) {\n"
16987                "      a();\n"
16988                "      b();\n"
16989                "    } else {\n"
16990                "      a();\n"
16991                "    }\n"
16992                "  }\n"
16993                "  void g() { return; }\n"
16994                "};\n"
16995                "struct B {\n"
16996                "  int x;\n"
16997                "};\n"
16998                "} // namespace a\n",
16999                LinuxBraceStyle);
17000   verifyFormat("enum X {\n"
17001                "  Y = 0,\n"
17002                "}\n",
17003                LinuxBraceStyle);
17004   verifyFormat("struct S {\n"
17005                "  int Type;\n"
17006                "  union {\n"
17007                "    int x;\n"
17008                "    double y;\n"
17009                "  } Value;\n"
17010                "  class C\n"
17011                "  {\n"
17012                "    MyFavoriteType Value;\n"
17013                "  } Class;\n"
17014                "}\n",
17015                LinuxBraceStyle);
17016 }
17017 
17018 TEST_F(FormatTest, MozillaBraceBreaking) {
17019   FormatStyle MozillaBraceStyle = getLLVMStyle();
17020   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
17021   MozillaBraceStyle.FixNamespaceComments = false;
17022   verifyFormat("namespace a {\n"
17023                "class A\n"
17024                "{\n"
17025                "  void f()\n"
17026                "  {\n"
17027                "    if (true) {\n"
17028                "      a();\n"
17029                "      b();\n"
17030                "    }\n"
17031                "  }\n"
17032                "  void g() { return; }\n"
17033                "};\n"
17034                "enum E\n"
17035                "{\n"
17036                "  A,\n"
17037                "  // foo\n"
17038                "  B,\n"
17039                "  C\n"
17040                "};\n"
17041                "struct B\n"
17042                "{\n"
17043                "  int x;\n"
17044                "};\n"
17045                "}\n",
17046                MozillaBraceStyle);
17047   verifyFormat("struct S\n"
17048                "{\n"
17049                "  int Type;\n"
17050                "  union\n"
17051                "  {\n"
17052                "    int x;\n"
17053                "    double y;\n"
17054                "  } Value;\n"
17055                "  class C\n"
17056                "  {\n"
17057                "    MyFavoriteType Value;\n"
17058                "  } Class;\n"
17059                "}\n",
17060                MozillaBraceStyle);
17061 }
17062 
17063 TEST_F(FormatTest, StroustrupBraceBreaking) {
17064   FormatStyle StroustrupBraceStyle = getLLVMStyle();
17065   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
17066   verifyFormat("namespace a {\n"
17067                "class A {\n"
17068                "  void f()\n"
17069                "  {\n"
17070                "    if (true) {\n"
17071                "      a();\n"
17072                "      b();\n"
17073                "    }\n"
17074                "  }\n"
17075                "  void g() { return; }\n"
17076                "};\n"
17077                "struct B {\n"
17078                "  int x;\n"
17079                "};\n"
17080                "} // namespace a\n",
17081                StroustrupBraceStyle);
17082 
17083   verifyFormat("void foo()\n"
17084                "{\n"
17085                "  if (a) {\n"
17086                "    a();\n"
17087                "  }\n"
17088                "  else {\n"
17089                "    b();\n"
17090                "  }\n"
17091                "}\n",
17092                StroustrupBraceStyle);
17093 
17094   verifyFormat("#ifdef _DEBUG\n"
17095                "int foo(int i = 0)\n"
17096                "#else\n"
17097                "int foo(int i = 5)\n"
17098                "#endif\n"
17099                "{\n"
17100                "  return i;\n"
17101                "}",
17102                StroustrupBraceStyle);
17103 
17104   verifyFormat("void foo() {}\n"
17105                "void bar()\n"
17106                "#ifdef _DEBUG\n"
17107                "{\n"
17108                "  foo();\n"
17109                "}\n"
17110                "#else\n"
17111                "{\n"
17112                "}\n"
17113                "#endif",
17114                StroustrupBraceStyle);
17115 
17116   verifyFormat("void foobar() { int i = 5; }\n"
17117                "#ifdef _DEBUG\n"
17118                "void bar() {}\n"
17119                "#else\n"
17120                "void bar() { foobar(); }\n"
17121                "#endif",
17122                StroustrupBraceStyle);
17123 }
17124 
17125 TEST_F(FormatTest, AllmanBraceBreaking) {
17126   FormatStyle AllmanBraceStyle = getLLVMStyle();
17127   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
17128 
17129   EXPECT_EQ("namespace a\n"
17130             "{\n"
17131             "void f();\n"
17132             "void g();\n"
17133             "} // namespace a\n",
17134             format("namespace a\n"
17135                    "{\n"
17136                    "void f();\n"
17137                    "void g();\n"
17138                    "}\n",
17139                    AllmanBraceStyle));
17140 
17141   verifyFormat("namespace a\n"
17142                "{\n"
17143                "class A\n"
17144                "{\n"
17145                "  void f()\n"
17146                "  {\n"
17147                "    if (true)\n"
17148                "    {\n"
17149                "      a();\n"
17150                "      b();\n"
17151                "    }\n"
17152                "  }\n"
17153                "  void g() { return; }\n"
17154                "};\n"
17155                "struct B\n"
17156                "{\n"
17157                "  int x;\n"
17158                "};\n"
17159                "union C\n"
17160                "{\n"
17161                "};\n"
17162                "} // namespace a",
17163                AllmanBraceStyle);
17164 
17165   verifyFormat("void f()\n"
17166                "{\n"
17167                "  if (true)\n"
17168                "  {\n"
17169                "    a();\n"
17170                "  }\n"
17171                "  else if (false)\n"
17172                "  {\n"
17173                "    b();\n"
17174                "  }\n"
17175                "  else\n"
17176                "  {\n"
17177                "    c();\n"
17178                "  }\n"
17179                "}\n",
17180                AllmanBraceStyle);
17181 
17182   verifyFormat("void f()\n"
17183                "{\n"
17184                "  for (int i = 0; i < 10; ++i)\n"
17185                "  {\n"
17186                "    a();\n"
17187                "  }\n"
17188                "  while (false)\n"
17189                "  {\n"
17190                "    b();\n"
17191                "  }\n"
17192                "  do\n"
17193                "  {\n"
17194                "    c();\n"
17195                "  } while (false)\n"
17196                "}\n",
17197                AllmanBraceStyle);
17198 
17199   verifyFormat("void f(int a)\n"
17200                "{\n"
17201                "  switch (a)\n"
17202                "  {\n"
17203                "  case 0:\n"
17204                "    break;\n"
17205                "  case 1:\n"
17206                "  {\n"
17207                "    break;\n"
17208                "  }\n"
17209                "  case 2:\n"
17210                "  {\n"
17211                "  }\n"
17212                "  break;\n"
17213                "  default:\n"
17214                "    break;\n"
17215                "  }\n"
17216                "}\n",
17217                AllmanBraceStyle);
17218 
17219   verifyFormat("enum X\n"
17220                "{\n"
17221                "  Y = 0,\n"
17222                "}\n",
17223                AllmanBraceStyle);
17224   verifyFormat("enum X\n"
17225                "{\n"
17226                "  Y = 0\n"
17227                "}\n",
17228                AllmanBraceStyle);
17229 
17230   verifyFormat("@interface BSApplicationController ()\n"
17231                "{\n"
17232                "@private\n"
17233                "  id _extraIvar;\n"
17234                "}\n"
17235                "@end\n",
17236                AllmanBraceStyle);
17237 
17238   verifyFormat("#ifdef _DEBUG\n"
17239                "int foo(int i = 0)\n"
17240                "#else\n"
17241                "int foo(int i = 5)\n"
17242                "#endif\n"
17243                "{\n"
17244                "  return i;\n"
17245                "}",
17246                AllmanBraceStyle);
17247 
17248   verifyFormat("void foo() {}\n"
17249                "void bar()\n"
17250                "#ifdef _DEBUG\n"
17251                "{\n"
17252                "  foo();\n"
17253                "}\n"
17254                "#else\n"
17255                "{\n"
17256                "}\n"
17257                "#endif",
17258                AllmanBraceStyle);
17259 
17260   verifyFormat("void foobar() { int i = 5; }\n"
17261                "#ifdef _DEBUG\n"
17262                "void bar() {}\n"
17263                "#else\n"
17264                "void bar() { foobar(); }\n"
17265                "#endif",
17266                AllmanBraceStyle);
17267 
17268   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
17269             FormatStyle::SLS_All);
17270 
17271   verifyFormat("[](int i) { return i + 2; };\n"
17272                "[](int i, int j)\n"
17273                "{\n"
17274                "  auto x = i + j;\n"
17275                "  auto y = i * j;\n"
17276                "  return x ^ y;\n"
17277                "};\n"
17278                "void foo()\n"
17279                "{\n"
17280                "  auto shortLambda = [](int i) { return i + 2; };\n"
17281                "  auto longLambda = [](int i, int j)\n"
17282                "  {\n"
17283                "    auto x = i + j;\n"
17284                "    auto y = i * j;\n"
17285                "    return x ^ y;\n"
17286                "  };\n"
17287                "}",
17288                AllmanBraceStyle);
17289 
17290   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17291 
17292   verifyFormat("[](int i)\n"
17293                "{\n"
17294                "  return i + 2;\n"
17295                "};\n"
17296                "[](int i, int j)\n"
17297                "{\n"
17298                "  auto x = i + j;\n"
17299                "  auto y = i * j;\n"
17300                "  return x ^ y;\n"
17301                "};\n"
17302                "void foo()\n"
17303                "{\n"
17304                "  auto shortLambda = [](int i)\n"
17305                "  {\n"
17306                "    return i + 2;\n"
17307                "  };\n"
17308                "  auto longLambda = [](int i, int j)\n"
17309                "  {\n"
17310                "    auto x = i + j;\n"
17311                "    auto y = i * j;\n"
17312                "    return x ^ y;\n"
17313                "  };\n"
17314                "}",
17315                AllmanBraceStyle);
17316 
17317   // Reset
17318   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
17319 
17320   // This shouldn't affect ObjC blocks..
17321   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17322                "  // ...\n"
17323                "  int i;\n"
17324                "}];",
17325                AllmanBraceStyle);
17326   verifyFormat("void (^block)(void) = ^{\n"
17327                "  // ...\n"
17328                "  int i;\n"
17329                "};",
17330                AllmanBraceStyle);
17331   // .. or dict literals.
17332   verifyFormat("void f()\n"
17333                "{\n"
17334                "  // ...\n"
17335                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
17336                "}",
17337                AllmanBraceStyle);
17338   verifyFormat("void f()\n"
17339                "{\n"
17340                "  // ...\n"
17341                "  [object someMethod:@{a : @\"b\"}];\n"
17342                "}",
17343                AllmanBraceStyle);
17344   verifyFormat("int f()\n"
17345                "{ // comment\n"
17346                "  return 42;\n"
17347                "}",
17348                AllmanBraceStyle);
17349 
17350   AllmanBraceStyle.ColumnLimit = 19;
17351   verifyFormat("void f() { int i; }", AllmanBraceStyle);
17352   AllmanBraceStyle.ColumnLimit = 18;
17353   verifyFormat("void f()\n"
17354                "{\n"
17355                "  int i;\n"
17356                "}",
17357                AllmanBraceStyle);
17358   AllmanBraceStyle.ColumnLimit = 80;
17359 
17360   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
17361   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17362       FormatStyle::SIS_WithoutElse;
17363   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17364   verifyFormat("void f(bool b)\n"
17365                "{\n"
17366                "  if (b)\n"
17367                "  {\n"
17368                "    return;\n"
17369                "  }\n"
17370                "}\n",
17371                BreakBeforeBraceShortIfs);
17372   verifyFormat("void f(bool b)\n"
17373                "{\n"
17374                "  if constexpr (b)\n"
17375                "  {\n"
17376                "    return;\n"
17377                "  }\n"
17378                "}\n",
17379                BreakBeforeBraceShortIfs);
17380   verifyFormat("void f(bool b)\n"
17381                "{\n"
17382                "  if CONSTEXPR (b)\n"
17383                "  {\n"
17384                "    return;\n"
17385                "  }\n"
17386                "}\n",
17387                BreakBeforeBraceShortIfs);
17388   verifyFormat("void f(bool b)\n"
17389                "{\n"
17390                "  if (b) return;\n"
17391                "}\n",
17392                BreakBeforeBraceShortIfs);
17393   verifyFormat("void f(bool b)\n"
17394                "{\n"
17395                "  if constexpr (b) return;\n"
17396                "}\n",
17397                BreakBeforeBraceShortIfs);
17398   verifyFormat("void f(bool b)\n"
17399                "{\n"
17400                "  if CONSTEXPR (b) return;\n"
17401                "}\n",
17402                BreakBeforeBraceShortIfs);
17403   verifyFormat("void f(bool b)\n"
17404                "{\n"
17405                "  while (b)\n"
17406                "  {\n"
17407                "    return;\n"
17408                "  }\n"
17409                "}\n",
17410                BreakBeforeBraceShortIfs);
17411 }
17412 
17413 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
17414   FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
17415   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
17416 
17417   // Make a few changes to the style for testing purposes
17418   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
17419       FormatStyle::SFS_Empty;
17420   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17421   WhitesmithsBraceStyle.ColumnLimit = 0;
17422 
17423   // FIXME: this test case can't decide whether there should be a blank line
17424   // after the ~D() line or not. It adds one if one doesn't exist in the test
17425   // and it removes the line if one exists.
17426   /*
17427   verifyFormat("class A;\n"
17428                "namespace B\n"
17429                "  {\n"
17430                "class C;\n"
17431                "// Comment\n"
17432                "class D\n"
17433                "  {\n"
17434                "public:\n"
17435                "  D();\n"
17436                "  ~D() {}\n"
17437                "private:\n"
17438                "  enum E\n"
17439                "    {\n"
17440                "    F\n"
17441                "    }\n"
17442                "  };\n"
17443                "  } // namespace B\n",
17444                WhitesmithsBraceStyle);
17445   */
17446 
17447   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
17448   verifyFormat("namespace a\n"
17449                "  {\n"
17450                "class A\n"
17451                "  {\n"
17452                "  void f()\n"
17453                "    {\n"
17454                "    if (true)\n"
17455                "      {\n"
17456                "      a();\n"
17457                "      b();\n"
17458                "      }\n"
17459                "    }\n"
17460                "  void g()\n"
17461                "    {\n"
17462                "    return;\n"
17463                "    }\n"
17464                "  };\n"
17465                "struct B\n"
17466                "  {\n"
17467                "  int x;\n"
17468                "  };\n"
17469                "  } // namespace a",
17470                WhitesmithsBraceStyle);
17471 
17472   verifyFormat("namespace a\n"
17473                "  {\n"
17474                "namespace b\n"
17475                "  {\n"
17476                "class A\n"
17477                "  {\n"
17478                "  void f()\n"
17479                "    {\n"
17480                "    if (true)\n"
17481                "      {\n"
17482                "      a();\n"
17483                "      b();\n"
17484                "      }\n"
17485                "    }\n"
17486                "  void g()\n"
17487                "    {\n"
17488                "    return;\n"
17489                "    }\n"
17490                "  };\n"
17491                "struct B\n"
17492                "  {\n"
17493                "  int x;\n"
17494                "  };\n"
17495                "  } // namespace b\n"
17496                "  } // namespace a",
17497                WhitesmithsBraceStyle);
17498 
17499   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
17500   verifyFormat("namespace a\n"
17501                "  {\n"
17502                "namespace b\n"
17503                "  {\n"
17504                "  class A\n"
17505                "    {\n"
17506                "    void f()\n"
17507                "      {\n"
17508                "      if (true)\n"
17509                "        {\n"
17510                "        a();\n"
17511                "        b();\n"
17512                "        }\n"
17513                "      }\n"
17514                "    void g()\n"
17515                "      {\n"
17516                "      return;\n"
17517                "      }\n"
17518                "    };\n"
17519                "  struct B\n"
17520                "    {\n"
17521                "    int x;\n"
17522                "    };\n"
17523                "  } // namespace b\n"
17524                "  } // namespace a",
17525                WhitesmithsBraceStyle);
17526 
17527   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
17528   verifyFormat("namespace a\n"
17529                "  {\n"
17530                "  namespace b\n"
17531                "    {\n"
17532                "    class A\n"
17533                "      {\n"
17534                "      void f()\n"
17535                "        {\n"
17536                "        if (true)\n"
17537                "          {\n"
17538                "          a();\n"
17539                "          b();\n"
17540                "          }\n"
17541                "        }\n"
17542                "      void g()\n"
17543                "        {\n"
17544                "        return;\n"
17545                "        }\n"
17546                "      };\n"
17547                "    struct B\n"
17548                "      {\n"
17549                "      int x;\n"
17550                "      };\n"
17551                "    } // namespace b\n"
17552                "  }   // namespace a",
17553                WhitesmithsBraceStyle);
17554 
17555   verifyFormat("void f()\n"
17556                "  {\n"
17557                "  if (true)\n"
17558                "    {\n"
17559                "    a();\n"
17560                "    }\n"
17561                "  else if (false)\n"
17562                "    {\n"
17563                "    b();\n"
17564                "    }\n"
17565                "  else\n"
17566                "    {\n"
17567                "    c();\n"
17568                "    }\n"
17569                "  }\n",
17570                WhitesmithsBraceStyle);
17571 
17572   verifyFormat("void f()\n"
17573                "  {\n"
17574                "  for (int i = 0; i < 10; ++i)\n"
17575                "    {\n"
17576                "    a();\n"
17577                "    }\n"
17578                "  while (false)\n"
17579                "    {\n"
17580                "    b();\n"
17581                "    }\n"
17582                "  do\n"
17583                "    {\n"
17584                "    c();\n"
17585                "    } while (false)\n"
17586                "  }\n",
17587                WhitesmithsBraceStyle);
17588 
17589   WhitesmithsBraceStyle.IndentCaseLabels = true;
17590   verifyFormat("void switchTest1(int a)\n"
17591                "  {\n"
17592                "  switch (a)\n"
17593                "    {\n"
17594                "    case 2:\n"
17595                "      {\n"
17596                "      }\n"
17597                "      break;\n"
17598                "    }\n"
17599                "  }\n",
17600                WhitesmithsBraceStyle);
17601 
17602   verifyFormat("void switchTest2(int a)\n"
17603                "  {\n"
17604                "  switch (a)\n"
17605                "    {\n"
17606                "    case 0:\n"
17607                "      break;\n"
17608                "    case 1:\n"
17609                "      {\n"
17610                "      break;\n"
17611                "      }\n"
17612                "    case 2:\n"
17613                "      {\n"
17614                "      }\n"
17615                "      break;\n"
17616                "    default:\n"
17617                "      break;\n"
17618                "    }\n"
17619                "  }\n",
17620                WhitesmithsBraceStyle);
17621 
17622   verifyFormat("void switchTest3(int a)\n"
17623                "  {\n"
17624                "  switch (a)\n"
17625                "    {\n"
17626                "    case 0:\n"
17627                "      {\n"
17628                "      foo(x);\n"
17629                "      }\n"
17630                "      break;\n"
17631                "    default:\n"
17632                "      {\n"
17633                "      foo(1);\n"
17634                "      }\n"
17635                "      break;\n"
17636                "    }\n"
17637                "  }\n",
17638                WhitesmithsBraceStyle);
17639 
17640   WhitesmithsBraceStyle.IndentCaseLabels = false;
17641 
17642   verifyFormat("void switchTest4(int a)\n"
17643                "  {\n"
17644                "  switch (a)\n"
17645                "    {\n"
17646                "  case 2:\n"
17647                "    {\n"
17648                "    }\n"
17649                "    break;\n"
17650                "    }\n"
17651                "  }\n",
17652                WhitesmithsBraceStyle);
17653 
17654   verifyFormat("void switchTest5(int a)\n"
17655                "  {\n"
17656                "  switch (a)\n"
17657                "    {\n"
17658                "  case 0:\n"
17659                "    break;\n"
17660                "  case 1:\n"
17661                "    {\n"
17662                "    foo();\n"
17663                "    break;\n"
17664                "    }\n"
17665                "  case 2:\n"
17666                "    {\n"
17667                "    }\n"
17668                "    break;\n"
17669                "  default:\n"
17670                "    break;\n"
17671                "    }\n"
17672                "  }\n",
17673                WhitesmithsBraceStyle);
17674 
17675   verifyFormat("void switchTest6(int a)\n"
17676                "  {\n"
17677                "  switch (a)\n"
17678                "    {\n"
17679                "  case 0:\n"
17680                "    {\n"
17681                "    foo(x);\n"
17682                "    }\n"
17683                "    break;\n"
17684                "  default:\n"
17685                "    {\n"
17686                "    foo(1);\n"
17687                "    }\n"
17688                "    break;\n"
17689                "    }\n"
17690                "  }\n",
17691                WhitesmithsBraceStyle);
17692 
17693   verifyFormat("enum X\n"
17694                "  {\n"
17695                "  Y = 0, // testing\n"
17696                "  }\n",
17697                WhitesmithsBraceStyle);
17698 
17699   verifyFormat("enum X\n"
17700                "  {\n"
17701                "  Y = 0\n"
17702                "  }\n",
17703                WhitesmithsBraceStyle);
17704   verifyFormat("enum X\n"
17705                "  {\n"
17706                "  Y = 0,\n"
17707                "  Z = 1\n"
17708                "  };\n",
17709                WhitesmithsBraceStyle);
17710 
17711   verifyFormat("@interface BSApplicationController ()\n"
17712                "  {\n"
17713                "@private\n"
17714                "  id _extraIvar;\n"
17715                "  }\n"
17716                "@end\n",
17717                WhitesmithsBraceStyle);
17718 
17719   verifyFormat("#ifdef _DEBUG\n"
17720                "int foo(int i = 0)\n"
17721                "#else\n"
17722                "int foo(int i = 5)\n"
17723                "#endif\n"
17724                "  {\n"
17725                "  return i;\n"
17726                "  }",
17727                WhitesmithsBraceStyle);
17728 
17729   verifyFormat("void foo() {}\n"
17730                "void bar()\n"
17731                "#ifdef _DEBUG\n"
17732                "  {\n"
17733                "  foo();\n"
17734                "  }\n"
17735                "#else\n"
17736                "  {\n"
17737                "  }\n"
17738                "#endif",
17739                WhitesmithsBraceStyle);
17740 
17741   verifyFormat("void foobar()\n"
17742                "  {\n"
17743                "  int i = 5;\n"
17744                "  }\n"
17745                "#ifdef _DEBUG\n"
17746                "void bar()\n"
17747                "  {\n"
17748                "  }\n"
17749                "#else\n"
17750                "void bar()\n"
17751                "  {\n"
17752                "  foobar();\n"
17753                "  }\n"
17754                "#endif",
17755                WhitesmithsBraceStyle);
17756 
17757   // This shouldn't affect ObjC blocks..
17758   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17759                "  // ...\n"
17760                "  int i;\n"
17761                "}];",
17762                WhitesmithsBraceStyle);
17763   verifyFormat("void (^block)(void) = ^{\n"
17764                "  // ...\n"
17765                "  int i;\n"
17766                "};",
17767                WhitesmithsBraceStyle);
17768   // .. or dict literals.
17769   verifyFormat("void f()\n"
17770                "  {\n"
17771                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
17772                "  }",
17773                WhitesmithsBraceStyle);
17774 
17775   verifyFormat("int f()\n"
17776                "  { // comment\n"
17777                "  return 42;\n"
17778                "  }",
17779                WhitesmithsBraceStyle);
17780 
17781   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
17782   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17783       FormatStyle::SIS_OnlyFirstIf;
17784   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17785   verifyFormat("void f(bool b)\n"
17786                "  {\n"
17787                "  if (b)\n"
17788                "    {\n"
17789                "    return;\n"
17790                "    }\n"
17791                "  }\n",
17792                BreakBeforeBraceShortIfs);
17793   verifyFormat("void f(bool b)\n"
17794                "  {\n"
17795                "  if (b) return;\n"
17796                "  }\n",
17797                BreakBeforeBraceShortIfs);
17798   verifyFormat("void f(bool b)\n"
17799                "  {\n"
17800                "  while (b)\n"
17801                "    {\n"
17802                "    return;\n"
17803                "    }\n"
17804                "  }\n",
17805                BreakBeforeBraceShortIfs);
17806 }
17807 
17808 TEST_F(FormatTest, GNUBraceBreaking) {
17809   FormatStyle GNUBraceStyle = getLLVMStyle();
17810   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
17811   verifyFormat("namespace a\n"
17812                "{\n"
17813                "class A\n"
17814                "{\n"
17815                "  void f()\n"
17816                "  {\n"
17817                "    int a;\n"
17818                "    {\n"
17819                "      int b;\n"
17820                "    }\n"
17821                "    if (true)\n"
17822                "      {\n"
17823                "        a();\n"
17824                "        b();\n"
17825                "      }\n"
17826                "  }\n"
17827                "  void g() { return; }\n"
17828                "}\n"
17829                "} // namespace a",
17830                GNUBraceStyle);
17831 
17832   verifyFormat("void f()\n"
17833                "{\n"
17834                "  if (true)\n"
17835                "    {\n"
17836                "      a();\n"
17837                "    }\n"
17838                "  else if (false)\n"
17839                "    {\n"
17840                "      b();\n"
17841                "    }\n"
17842                "  else\n"
17843                "    {\n"
17844                "      c();\n"
17845                "    }\n"
17846                "}\n",
17847                GNUBraceStyle);
17848 
17849   verifyFormat("void f()\n"
17850                "{\n"
17851                "  for (int i = 0; i < 10; ++i)\n"
17852                "    {\n"
17853                "      a();\n"
17854                "    }\n"
17855                "  while (false)\n"
17856                "    {\n"
17857                "      b();\n"
17858                "    }\n"
17859                "  do\n"
17860                "    {\n"
17861                "      c();\n"
17862                "    }\n"
17863                "  while (false);\n"
17864                "}\n",
17865                GNUBraceStyle);
17866 
17867   verifyFormat("void f(int a)\n"
17868                "{\n"
17869                "  switch (a)\n"
17870                "    {\n"
17871                "    case 0:\n"
17872                "      break;\n"
17873                "    case 1:\n"
17874                "      {\n"
17875                "        break;\n"
17876                "      }\n"
17877                "    case 2:\n"
17878                "      {\n"
17879                "      }\n"
17880                "      break;\n"
17881                "    default:\n"
17882                "      break;\n"
17883                "    }\n"
17884                "}\n",
17885                GNUBraceStyle);
17886 
17887   verifyFormat("enum X\n"
17888                "{\n"
17889                "  Y = 0,\n"
17890                "}\n",
17891                GNUBraceStyle);
17892 
17893   verifyFormat("@interface BSApplicationController ()\n"
17894                "{\n"
17895                "@private\n"
17896                "  id _extraIvar;\n"
17897                "}\n"
17898                "@end\n",
17899                GNUBraceStyle);
17900 
17901   verifyFormat("#ifdef _DEBUG\n"
17902                "int foo(int i = 0)\n"
17903                "#else\n"
17904                "int foo(int i = 5)\n"
17905                "#endif\n"
17906                "{\n"
17907                "  return i;\n"
17908                "}",
17909                GNUBraceStyle);
17910 
17911   verifyFormat("void foo() {}\n"
17912                "void bar()\n"
17913                "#ifdef _DEBUG\n"
17914                "{\n"
17915                "  foo();\n"
17916                "}\n"
17917                "#else\n"
17918                "{\n"
17919                "}\n"
17920                "#endif",
17921                GNUBraceStyle);
17922 
17923   verifyFormat("void foobar() { int i = 5; }\n"
17924                "#ifdef _DEBUG\n"
17925                "void bar() {}\n"
17926                "#else\n"
17927                "void bar() { foobar(); }\n"
17928                "#endif",
17929                GNUBraceStyle);
17930 }
17931 
17932 TEST_F(FormatTest, WebKitBraceBreaking) {
17933   FormatStyle WebKitBraceStyle = getLLVMStyle();
17934   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
17935   WebKitBraceStyle.FixNamespaceComments = false;
17936   verifyFormat("namespace a {\n"
17937                "class A {\n"
17938                "  void f()\n"
17939                "  {\n"
17940                "    if (true) {\n"
17941                "      a();\n"
17942                "      b();\n"
17943                "    }\n"
17944                "  }\n"
17945                "  void g() { return; }\n"
17946                "};\n"
17947                "enum E {\n"
17948                "  A,\n"
17949                "  // foo\n"
17950                "  B,\n"
17951                "  C\n"
17952                "};\n"
17953                "struct B {\n"
17954                "  int x;\n"
17955                "};\n"
17956                "}\n",
17957                WebKitBraceStyle);
17958   verifyFormat("struct S {\n"
17959                "  int Type;\n"
17960                "  union {\n"
17961                "    int x;\n"
17962                "    double y;\n"
17963                "  } Value;\n"
17964                "  class C {\n"
17965                "    MyFavoriteType Value;\n"
17966                "  } Class;\n"
17967                "};\n",
17968                WebKitBraceStyle);
17969 }
17970 
17971 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
17972   verifyFormat("void f() {\n"
17973                "  try {\n"
17974                "  } catch (const Exception &e) {\n"
17975                "  }\n"
17976                "}\n",
17977                getLLVMStyle());
17978 }
17979 
17980 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
17981   auto Style = getLLVMStyle();
17982   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
17983   Style.AlignConsecutiveAssignments =
17984       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17985   Style.AlignConsecutiveDeclarations =
17986       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17987   verifyFormat("struct test demo[] = {\n"
17988                "    {56,    23, \"hello\"},\n"
17989                "    {-1, 93463, \"world\"},\n"
17990                "    { 7,     5,    \"!!\"}\n"
17991                "};\n",
17992                Style);
17993 
17994   verifyFormat("struct test demo[] = {\n"
17995                "    {56,    23, \"hello\"}, // first line\n"
17996                "    {-1, 93463, \"world\"}, // second line\n"
17997                "    { 7,     5,    \"!!\"}  // third line\n"
17998                "};\n",
17999                Style);
18000 
18001   verifyFormat("struct test demo[4] = {\n"
18002                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18003                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18004                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18005                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18006                "};\n",
18007                Style);
18008 
18009   verifyFormat("struct test demo[3] = {\n"
18010                "    {56,    23, \"hello\"},\n"
18011                "    {-1, 93463, \"world\"},\n"
18012                "    { 7,     5,    \"!!\"}\n"
18013                "};\n",
18014                Style);
18015 
18016   verifyFormat("struct test demo[3] = {\n"
18017                "    {int{56},    23, \"hello\"},\n"
18018                "    {int{-1}, 93463, \"world\"},\n"
18019                "    { int{7},     5,    \"!!\"}\n"
18020                "};\n",
18021                Style);
18022 
18023   verifyFormat("struct test demo[] = {\n"
18024                "    {56,    23, \"hello\"},\n"
18025                "    {-1, 93463, \"world\"},\n"
18026                "    { 7,     5,    \"!!\"},\n"
18027                "};\n",
18028                Style);
18029 
18030   verifyFormat("test demo[] = {\n"
18031                "    {56,    23, \"hello\"},\n"
18032                "    {-1, 93463, \"world\"},\n"
18033                "    { 7,     5,    \"!!\"},\n"
18034                "};\n",
18035                Style);
18036 
18037   verifyFormat("demo = std::array<struct test, 3>{\n"
18038                "    test{56,    23, \"hello\"},\n"
18039                "    test{-1, 93463, \"world\"},\n"
18040                "    test{ 7,     5,    \"!!\"},\n"
18041                "};\n",
18042                Style);
18043 
18044   verifyFormat("test demo[] = {\n"
18045                "    {56,    23, \"hello\"},\n"
18046                "#if X\n"
18047                "    {-1, 93463, \"world\"},\n"
18048                "#endif\n"
18049                "    { 7,     5,    \"!!\"}\n"
18050                "};\n",
18051                Style);
18052 
18053   verifyFormat(
18054       "test demo[] = {\n"
18055       "    { 7,    23,\n"
18056       "     \"hello world i am a very long line that really, in any\"\n"
18057       "     \"just world, ought to be split over multiple lines\"},\n"
18058       "    {-1, 93463,                                  \"world\"},\n"
18059       "    {56,     5,                                     \"!!\"}\n"
18060       "};\n",
18061       Style);
18062 
18063   verifyFormat("return GradForUnaryCwise(g, {\n"
18064                "                                {{\"sign\"}, \"Sign\",  "
18065                "  {\"x\", \"dy\"}},\n"
18066                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
18067                ", \"sign\"}},\n"
18068                "});\n",
18069                Style);
18070 
18071   Style.ColumnLimit = 0;
18072   EXPECT_EQ(
18073       "test demo[] = {\n"
18074       "    {56,    23, \"hello world i am a very long line that really, "
18075       "in any just world, ought to be split over multiple lines\"},\n"
18076       "    {-1, 93463,                                                  "
18077       "                                                 \"world\"},\n"
18078       "    { 7,     5,                                                  "
18079       "                                                    \"!!\"},\n"
18080       "};",
18081       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18082              "that really, in any just world, ought to be split over multiple "
18083              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18084              Style));
18085 
18086   Style.ColumnLimit = 80;
18087   verifyFormat("test demo[] = {\n"
18088                "    {56,    23, /* a comment */ \"hello\"},\n"
18089                "    {-1, 93463,                 \"world\"},\n"
18090                "    { 7,     5,                    \"!!\"}\n"
18091                "};\n",
18092                Style);
18093 
18094   verifyFormat("test demo[] = {\n"
18095                "    {56,    23,                    \"hello\"},\n"
18096                "    {-1, 93463, \"world\" /* comment here */},\n"
18097                "    { 7,     5,                       \"!!\"}\n"
18098                "};\n",
18099                Style);
18100 
18101   verifyFormat("test demo[] = {\n"
18102                "    {56, /* a comment */ 23, \"hello\"},\n"
18103                "    {-1,              93463, \"world\"},\n"
18104                "    { 7,                  5,    \"!!\"}\n"
18105                "};\n",
18106                Style);
18107 
18108   Style.ColumnLimit = 20;
18109   EXPECT_EQ(
18110       "demo = std::array<\n"
18111       "    struct test, 3>{\n"
18112       "    test{\n"
18113       "         56,    23,\n"
18114       "         \"hello \"\n"
18115       "         \"world i \"\n"
18116       "         \"am a very \"\n"
18117       "         \"long line \"\n"
18118       "         \"that \"\n"
18119       "         \"really, \"\n"
18120       "         \"in any \"\n"
18121       "         \"just \"\n"
18122       "         \"world, \"\n"
18123       "         \"ought to \"\n"
18124       "         \"be split \"\n"
18125       "         \"over \"\n"
18126       "         \"multiple \"\n"
18127       "         \"lines\"},\n"
18128       "    test{-1, 93463,\n"
18129       "         \"world\"},\n"
18130       "    test{ 7,     5,\n"
18131       "         \"!!\"   },\n"
18132       "};",
18133       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18134              "i am a very long line that really, in any just world, ought "
18135              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18136              "test{7, 5, \"!!\"},};",
18137              Style));
18138   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18139   Style = getLLVMStyleWithColumns(50);
18140   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18141   verifyFormat("static A x = {\n"
18142                "    {{init1, init2, init3, init4},\n"
18143                "     {init1, init2, init3, init4}}\n"
18144                "};",
18145                Style);
18146   Style.ColumnLimit = 100;
18147   EXPECT_EQ(
18148       "test demo[] = {\n"
18149       "    {56,    23,\n"
18150       "     \"hello world i am a very long line that really, in any just world"
18151       ", ought to be split over \"\n"
18152       "     \"multiple lines\"  },\n"
18153       "    {-1, 93463, \"world\"},\n"
18154       "    { 7,     5,    \"!!\"},\n"
18155       "};",
18156       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18157              "that really, in any just world, ought to be split over multiple "
18158              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18159              Style));
18160 
18161   Style = getLLVMStyleWithColumns(50);
18162   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18163   Style.AlignConsecutiveAssignments =
18164       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18165   Style.AlignConsecutiveDeclarations =
18166       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18167   verifyFormat("struct test demo[] = {\n"
18168                "    {56,    23, \"hello\"},\n"
18169                "    {-1, 93463, \"world\"},\n"
18170                "    { 7,     5,    \"!!\"}\n"
18171                "};\n"
18172                "static A x = {\n"
18173                "    {{init1, init2, init3, init4},\n"
18174                "     {init1, init2, init3, init4}}\n"
18175                "};",
18176                Style);
18177   Style.ColumnLimit = 100;
18178   Style.AlignConsecutiveAssignments =
18179       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18180   Style.AlignConsecutiveDeclarations =
18181       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18182   verifyFormat("struct test demo[] = {\n"
18183                "    {56,    23, \"hello\"},\n"
18184                "    {-1, 93463, \"world\"},\n"
18185                "    { 7,     5,    \"!!\"}\n"
18186                "};\n"
18187                "struct test demo[4] = {\n"
18188                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18189                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18190                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18191                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18192                "};\n",
18193                Style);
18194   EXPECT_EQ(
18195       "test demo[] = {\n"
18196       "    {56,\n"
18197       "     \"hello world i am a very long line that really, in any just world"
18198       ", ought to be split over \"\n"
18199       "     \"multiple lines\",    23},\n"
18200       "    {-1,      \"world\", 93463},\n"
18201       "    { 7,         \"!!\",     5},\n"
18202       "};",
18203       format("test demo[] = {{56, \"hello world i am a very long line "
18204              "that really, in any just world, ought to be split over multiple "
18205              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
18206              Style));
18207 }
18208 
18209 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
18210   auto Style = getLLVMStyle();
18211   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18212   /* FIXME: This case gets misformatted.
18213   verifyFormat("auto foo = Items{\n"
18214                "    Section{0, bar(), },\n"
18215                "    Section{1, boo()  }\n"
18216                "};\n",
18217                Style);
18218   */
18219   verifyFormat("auto foo = Items{\n"
18220                "    Section{\n"
18221                "            0, bar(),\n"
18222                "            }\n"
18223                "};\n",
18224                Style);
18225   verifyFormat("struct test demo[] = {\n"
18226                "    {56, 23,    \"hello\"},\n"
18227                "    {-1, 93463, \"world\"},\n"
18228                "    {7,  5,     \"!!\"   }\n"
18229                "};\n",
18230                Style);
18231   verifyFormat("struct test demo[] = {\n"
18232                "    {56, 23,    \"hello\"}, // first line\n"
18233                "    {-1, 93463, \"world\"}, // second line\n"
18234                "    {7,  5,     \"!!\"   }  // third line\n"
18235                "};\n",
18236                Style);
18237   verifyFormat("struct test demo[4] = {\n"
18238                "    {56,  23,    21, \"oh\"      }, // first line\n"
18239                "    {-1,  93463, 22, \"my\"      }, // second line\n"
18240                "    {7,   5,     1,  \"goodness\"}  // third line\n"
18241                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
18242                "};\n",
18243                Style);
18244   verifyFormat("struct test demo[3] = {\n"
18245                "    {56, 23,    \"hello\"},\n"
18246                "    {-1, 93463, \"world\"},\n"
18247                "    {7,  5,     \"!!\"   }\n"
18248                "};\n",
18249                Style);
18250 
18251   verifyFormat("struct test demo[3] = {\n"
18252                "    {int{56}, 23,    \"hello\"},\n"
18253                "    {int{-1}, 93463, \"world\"},\n"
18254                "    {int{7},  5,     \"!!\"   }\n"
18255                "};\n",
18256                Style);
18257   verifyFormat("struct test demo[] = {\n"
18258                "    {56, 23,    \"hello\"},\n"
18259                "    {-1, 93463, \"world\"},\n"
18260                "    {7,  5,     \"!!\"   },\n"
18261                "};\n",
18262                Style);
18263   verifyFormat("test demo[] = {\n"
18264                "    {56, 23,    \"hello\"},\n"
18265                "    {-1, 93463, \"world\"},\n"
18266                "    {7,  5,     \"!!\"   },\n"
18267                "};\n",
18268                Style);
18269   verifyFormat("demo = std::array<struct test, 3>{\n"
18270                "    test{56, 23,    \"hello\"},\n"
18271                "    test{-1, 93463, \"world\"},\n"
18272                "    test{7,  5,     \"!!\"   },\n"
18273                "};\n",
18274                Style);
18275   verifyFormat("test demo[] = {\n"
18276                "    {56, 23,    \"hello\"},\n"
18277                "#if X\n"
18278                "    {-1, 93463, \"world\"},\n"
18279                "#endif\n"
18280                "    {7,  5,     \"!!\"   }\n"
18281                "};\n",
18282                Style);
18283   verifyFormat(
18284       "test demo[] = {\n"
18285       "    {7,  23,\n"
18286       "     \"hello world i am a very long line that really, in any\"\n"
18287       "     \"just world, ought to be split over multiple lines\"},\n"
18288       "    {-1, 93463, \"world\"                                 },\n"
18289       "    {56, 5,     \"!!\"                                    }\n"
18290       "};\n",
18291       Style);
18292 
18293   verifyFormat("return GradForUnaryCwise(g, {\n"
18294                "                                {{\"sign\"}, \"Sign\", {\"x\", "
18295                "\"dy\"}   },\n"
18296                "                                {{\"dx\"},   \"Mul\",  "
18297                "{\"dy\", \"sign\"}},\n"
18298                "});\n",
18299                Style);
18300 
18301   Style.ColumnLimit = 0;
18302   EXPECT_EQ(
18303       "test demo[] = {\n"
18304       "    {56, 23,    \"hello world i am a very long line that really, in any "
18305       "just world, ought to be split over multiple lines\"},\n"
18306       "    {-1, 93463, \"world\"                                               "
18307       "                                                   },\n"
18308       "    {7,  5,     \"!!\"                                                  "
18309       "                                                   },\n"
18310       "};",
18311       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18312              "that really, in any just world, ought to be split over multiple "
18313              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18314              Style));
18315 
18316   Style.ColumnLimit = 80;
18317   verifyFormat("test demo[] = {\n"
18318                "    {56, 23,    /* a comment */ \"hello\"},\n"
18319                "    {-1, 93463, \"world\"                },\n"
18320                "    {7,  5,     \"!!\"                   }\n"
18321                "};\n",
18322                Style);
18323 
18324   verifyFormat("test demo[] = {\n"
18325                "    {56, 23,    \"hello\"                   },\n"
18326                "    {-1, 93463, \"world\" /* comment here */},\n"
18327                "    {7,  5,     \"!!\"                      }\n"
18328                "};\n",
18329                Style);
18330 
18331   verifyFormat("test demo[] = {\n"
18332                "    {56, /* a comment */ 23, \"hello\"},\n"
18333                "    {-1, 93463,              \"world\"},\n"
18334                "    {7,  5,                  \"!!\"   }\n"
18335                "};\n",
18336                Style);
18337 
18338   Style.ColumnLimit = 20;
18339   EXPECT_EQ(
18340       "demo = std::array<\n"
18341       "    struct test, 3>{\n"
18342       "    test{\n"
18343       "         56, 23,\n"
18344       "         \"hello \"\n"
18345       "         \"world i \"\n"
18346       "         \"am a very \"\n"
18347       "         \"long line \"\n"
18348       "         \"that \"\n"
18349       "         \"really, \"\n"
18350       "         \"in any \"\n"
18351       "         \"just \"\n"
18352       "         \"world, \"\n"
18353       "         \"ought to \"\n"
18354       "         \"be split \"\n"
18355       "         \"over \"\n"
18356       "         \"multiple \"\n"
18357       "         \"lines\"},\n"
18358       "    test{-1, 93463,\n"
18359       "         \"world\"},\n"
18360       "    test{7,  5,\n"
18361       "         \"!!\"   },\n"
18362       "};",
18363       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18364              "i am a very long line that really, in any just world, ought "
18365              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18366              "test{7, 5, \"!!\"},};",
18367              Style));
18368 
18369   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18370   Style = getLLVMStyleWithColumns(50);
18371   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18372   verifyFormat("static A x = {\n"
18373                "    {{init1, init2, init3, init4},\n"
18374                "     {init1, init2, init3, init4}}\n"
18375                "};",
18376                Style);
18377   Style.ColumnLimit = 100;
18378   EXPECT_EQ(
18379       "test demo[] = {\n"
18380       "    {56, 23,\n"
18381       "     \"hello world i am a very long line that really, in any just world"
18382       ", ought to be split over \"\n"
18383       "     \"multiple lines\"  },\n"
18384       "    {-1, 93463, \"world\"},\n"
18385       "    {7,  5,     \"!!\"   },\n"
18386       "};",
18387       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18388              "that really, in any just world, ought to be split over multiple "
18389              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18390              Style));
18391 }
18392 
18393 TEST_F(FormatTest, UnderstandsPragmas) {
18394   verifyFormat("#pragma omp reduction(| : var)");
18395   verifyFormat("#pragma omp reduction(+ : var)");
18396 
18397   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
18398             "(including parentheses).",
18399             format("#pragma    mark   Any non-hyphenated or hyphenated string "
18400                    "(including parentheses)."));
18401 }
18402 
18403 TEST_F(FormatTest, UnderstandPragmaOption) {
18404   verifyFormat("#pragma option -C -A");
18405 
18406   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
18407 }
18408 
18409 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
18410   FormatStyle Style = getLLVMStyle();
18411   Style.ColumnLimit = 20;
18412 
18413   // See PR41213
18414   EXPECT_EQ("/*\n"
18415             " *\t9012345\n"
18416             " * /8901\n"
18417             " */",
18418             format("/*\n"
18419                    " *\t9012345 /8901\n"
18420                    " */",
18421                    Style));
18422   EXPECT_EQ("/*\n"
18423             " *345678\n"
18424             " *\t/8901\n"
18425             " */",
18426             format("/*\n"
18427                    " *345678\t/8901\n"
18428                    " */",
18429                    Style));
18430 
18431   verifyFormat("int a; // the\n"
18432                "       // comment",
18433                Style);
18434   EXPECT_EQ("int a; /* first line\n"
18435             "        * second\n"
18436             "        * line third\n"
18437             "        * line\n"
18438             "        */",
18439             format("int a; /* first line\n"
18440                    "        * second\n"
18441                    "        * line third\n"
18442                    "        * line\n"
18443                    "        */",
18444                    Style));
18445   EXPECT_EQ("int a; // first line\n"
18446             "       // second\n"
18447             "       // line third\n"
18448             "       // line",
18449             format("int a; // first line\n"
18450                    "       // second line\n"
18451                    "       // third line",
18452                    Style));
18453 
18454   Style.PenaltyExcessCharacter = 90;
18455   verifyFormat("int a; // the comment", Style);
18456   EXPECT_EQ("int a; // the comment\n"
18457             "       // aaa",
18458             format("int a; // the comment aaa", Style));
18459   EXPECT_EQ("int a; /* first line\n"
18460             "        * second line\n"
18461             "        * third line\n"
18462             "        */",
18463             format("int a; /* first line\n"
18464                    "        * second line\n"
18465                    "        * third line\n"
18466                    "        */",
18467                    Style));
18468   EXPECT_EQ("int a; // first line\n"
18469             "       // second line\n"
18470             "       // third line",
18471             format("int a; // first line\n"
18472                    "       // second line\n"
18473                    "       // third line",
18474                    Style));
18475   // FIXME: Investigate why this is not getting the same layout as the test
18476   // above.
18477   EXPECT_EQ("int a; /* first line\n"
18478             "        * second line\n"
18479             "        * third line\n"
18480             "        */",
18481             format("int a; /* first line second line third line"
18482                    "\n*/",
18483                    Style));
18484 
18485   EXPECT_EQ("// foo bar baz bazfoo\n"
18486             "// foo bar foo bar\n",
18487             format("// foo bar baz bazfoo\n"
18488                    "// foo bar foo           bar\n",
18489                    Style));
18490   EXPECT_EQ("// foo bar baz bazfoo\n"
18491             "// foo bar foo bar\n",
18492             format("// foo bar baz      bazfoo\n"
18493                    "// foo            bar foo bar\n",
18494                    Style));
18495 
18496   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
18497   // next one.
18498   EXPECT_EQ("// foo bar baz bazfoo\n"
18499             "// bar foo bar\n",
18500             format("// foo bar baz      bazfoo bar\n"
18501                    "// foo            bar\n",
18502                    Style));
18503 
18504   EXPECT_EQ("// foo bar baz bazfoo\n"
18505             "// foo bar baz bazfoo\n"
18506             "// bar foo bar\n",
18507             format("// foo bar baz      bazfoo\n"
18508                    "// foo bar baz      bazfoo bar\n"
18509                    "// foo bar\n",
18510                    Style));
18511 
18512   EXPECT_EQ("// foo bar baz bazfoo\n"
18513             "// foo bar baz bazfoo\n"
18514             "// bar foo bar\n",
18515             format("// foo bar baz      bazfoo\n"
18516                    "// foo bar baz      bazfoo bar\n"
18517                    "// foo           bar\n",
18518                    Style));
18519 
18520   // Make sure we do not keep protruding characters if strict mode reflow is
18521   // cheaper than keeping protruding characters.
18522   Style.ColumnLimit = 21;
18523   EXPECT_EQ(
18524       "// foo foo foo foo\n"
18525       "// foo foo foo foo\n"
18526       "// foo foo foo foo\n",
18527       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
18528 
18529   EXPECT_EQ("int a = /* long block\n"
18530             "           comment */\n"
18531             "    42;",
18532             format("int a = /* long block comment */ 42;", Style));
18533 }
18534 
18535 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
18536   for (size_t i = 1; i < Styles.size(); ++i)                                   \
18537   EXPECT_EQ(Styles[0], Styles[i])                                              \
18538       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
18539 
18540 TEST_F(FormatTest, GetsPredefinedStyleByName) {
18541   SmallVector<FormatStyle, 3> Styles;
18542   Styles.resize(3);
18543 
18544   Styles[0] = getLLVMStyle();
18545   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
18546   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
18547   EXPECT_ALL_STYLES_EQUAL(Styles);
18548 
18549   Styles[0] = getGoogleStyle();
18550   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
18551   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
18552   EXPECT_ALL_STYLES_EQUAL(Styles);
18553 
18554   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18555   EXPECT_TRUE(
18556       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
18557   EXPECT_TRUE(
18558       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
18559   EXPECT_ALL_STYLES_EQUAL(Styles);
18560 
18561   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
18562   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
18563   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
18564   EXPECT_ALL_STYLES_EQUAL(Styles);
18565 
18566   Styles[0] = getMozillaStyle();
18567   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
18568   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
18569   EXPECT_ALL_STYLES_EQUAL(Styles);
18570 
18571   Styles[0] = getWebKitStyle();
18572   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
18573   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
18574   EXPECT_ALL_STYLES_EQUAL(Styles);
18575 
18576   Styles[0] = getGNUStyle();
18577   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
18578   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
18579   EXPECT_ALL_STYLES_EQUAL(Styles);
18580 
18581   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
18582 }
18583 
18584 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
18585   SmallVector<FormatStyle, 8> Styles;
18586   Styles.resize(2);
18587 
18588   Styles[0] = getGoogleStyle();
18589   Styles[1] = getLLVMStyle();
18590   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18591   EXPECT_ALL_STYLES_EQUAL(Styles);
18592 
18593   Styles.resize(5);
18594   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18595   Styles[1] = getLLVMStyle();
18596   Styles[1].Language = FormatStyle::LK_JavaScript;
18597   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18598 
18599   Styles[2] = getLLVMStyle();
18600   Styles[2].Language = FormatStyle::LK_JavaScript;
18601   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
18602                                   "BasedOnStyle: Google",
18603                                   &Styles[2])
18604                    .value());
18605 
18606   Styles[3] = getLLVMStyle();
18607   Styles[3].Language = FormatStyle::LK_JavaScript;
18608   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
18609                                   "Language: JavaScript",
18610                                   &Styles[3])
18611                    .value());
18612 
18613   Styles[4] = getLLVMStyle();
18614   Styles[4].Language = FormatStyle::LK_JavaScript;
18615   EXPECT_EQ(0, parseConfiguration("---\n"
18616                                   "BasedOnStyle: LLVM\n"
18617                                   "IndentWidth: 123\n"
18618                                   "---\n"
18619                                   "BasedOnStyle: Google\n"
18620                                   "Language: JavaScript",
18621                                   &Styles[4])
18622                    .value());
18623   EXPECT_ALL_STYLES_EQUAL(Styles);
18624 }
18625 
18626 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
18627   Style.FIELD = false;                                                         \
18628   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
18629   EXPECT_TRUE(Style.FIELD);                                                    \
18630   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
18631   EXPECT_FALSE(Style.FIELD);
18632 
18633 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
18634 
18635 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
18636   Style.STRUCT.FIELD = false;                                                  \
18637   EXPECT_EQ(0,                                                                 \
18638             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
18639                 .value());                                                     \
18640   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
18641   EXPECT_EQ(0,                                                                 \
18642             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
18643                 .value());                                                     \
18644   EXPECT_FALSE(Style.STRUCT.FIELD);
18645 
18646 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
18647   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
18648 
18649 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
18650   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
18651   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
18652   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
18653 
18654 TEST_F(FormatTest, ParsesConfigurationBools) {
18655   FormatStyle Style = {};
18656   Style.Language = FormatStyle::LK_Cpp;
18657   CHECK_PARSE_BOOL(AlignTrailingComments);
18658   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
18659   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
18660   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
18661   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
18662   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
18663   CHECK_PARSE_BOOL(BinPackArguments);
18664   CHECK_PARSE_BOOL(BinPackParameters);
18665   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
18666   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
18667   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
18668   CHECK_PARSE_BOOL(BreakStringLiterals);
18669   CHECK_PARSE_BOOL(CompactNamespaces);
18670   CHECK_PARSE_BOOL(DeriveLineEnding);
18671   CHECK_PARSE_BOOL(DerivePointerAlignment);
18672   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
18673   CHECK_PARSE_BOOL(DisableFormat);
18674   CHECK_PARSE_BOOL(IndentAccessModifiers);
18675   CHECK_PARSE_BOOL(IndentCaseLabels);
18676   CHECK_PARSE_BOOL(IndentCaseBlocks);
18677   CHECK_PARSE_BOOL(IndentGotoLabels);
18678   CHECK_PARSE_BOOL(IndentRequires);
18679   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
18680   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
18681   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
18682   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
18683   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
18684   CHECK_PARSE_BOOL(ReflowComments);
18685   CHECK_PARSE_BOOL(SortUsingDeclarations);
18686   CHECK_PARSE_BOOL(SpacesInParentheses);
18687   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
18688   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
18689   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
18690   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
18691   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
18692   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
18693   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
18694   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
18695   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
18696   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
18697   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
18698   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
18699   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
18700   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
18701   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
18702   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
18703   CHECK_PARSE_BOOL(UseCRLF);
18704 
18705   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
18706   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
18707   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
18708   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
18709   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
18710   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
18711   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
18712   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
18713   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
18714   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
18715   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
18716   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
18717   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
18718   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
18719   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
18720   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
18721   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
18722 }
18723 
18724 #undef CHECK_PARSE_BOOL
18725 
18726 TEST_F(FormatTest, ParsesConfiguration) {
18727   FormatStyle Style = {};
18728   Style.Language = FormatStyle::LK_Cpp;
18729   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
18730   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
18731               ConstructorInitializerIndentWidth, 1234u);
18732   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
18733   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
18734   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
18735   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
18736   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
18737               PenaltyBreakBeforeFirstCallParameter, 1234u);
18738   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
18739               PenaltyBreakTemplateDeclaration, 1234u);
18740   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
18741   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
18742               PenaltyReturnTypeOnItsOwnLine, 1234u);
18743   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
18744               SpacesBeforeTrailingComments, 1234u);
18745   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
18746   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
18747   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
18748 
18749   Style.QualifierAlignment = FormatStyle::QAS_Right;
18750   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
18751               FormatStyle::QAS_Leave);
18752   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
18753               FormatStyle::QAS_Right);
18754   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
18755               FormatStyle::QAS_Left);
18756   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
18757               FormatStyle::QAS_Custom);
18758 
18759   Style.QualifierOrder.clear();
18760   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
18761               std::vector<std::string>({"const", "volatile", "type"}));
18762   Style.QualifierOrder.clear();
18763   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
18764               std::vector<std::string>({"const", "type"}));
18765   Style.QualifierOrder.clear();
18766   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
18767               std::vector<std::string>({"volatile", "type"}));
18768 
18769   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
18770   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
18771               FormatStyle::ACS_None);
18772   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
18773               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
18774   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
18775               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
18776   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
18777               AlignConsecutiveAssignments,
18778               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18779   // For backwards compability, false / true should still parse
18780   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
18781               FormatStyle::ACS_None);
18782   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
18783               FormatStyle::ACS_Consecutive);
18784 
18785   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
18786   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
18787               FormatStyle::ACS_None);
18788   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
18789               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
18790   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
18791               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
18792   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
18793               AlignConsecutiveBitFields,
18794               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18795   // For backwards compability, false / true should still parse
18796   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
18797               FormatStyle::ACS_None);
18798   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
18799               FormatStyle::ACS_Consecutive);
18800 
18801   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
18802   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
18803               FormatStyle::ACS_None);
18804   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
18805               FormatStyle::ACS_Consecutive);
18806   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
18807               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
18808   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
18809               AlignConsecutiveMacros,
18810               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18811   // For backwards compability, false / true should still parse
18812   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
18813               FormatStyle::ACS_None);
18814   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
18815               FormatStyle::ACS_Consecutive);
18816 
18817   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
18818   CHECK_PARSE("AlignConsecutiveDeclarations: None",
18819               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
18820   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
18821               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
18822   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
18823               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
18824   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
18825               AlignConsecutiveDeclarations,
18826               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18827   // For backwards compability, false / true should still parse
18828   CHECK_PARSE("AlignConsecutiveDeclarations: false",
18829               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
18830   CHECK_PARSE("AlignConsecutiveDeclarations: true",
18831               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
18832 
18833   Style.PointerAlignment = FormatStyle::PAS_Middle;
18834   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
18835               FormatStyle::PAS_Left);
18836   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
18837               FormatStyle::PAS_Right);
18838   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
18839               FormatStyle::PAS_Middle);
18840   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
18841   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
18842               FormatStyle::RAS_Pointer);
18843   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
18844               FormatStyle::RAS_Left);
18845   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
18846               FormatStyle::RAS_Right);
18847   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
18848               FormatStyle::RAS_Middle);
18849   // For backward compatibility:
18850   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
18851               FormatStyle::PAS_Left);
18852   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
18853               FormatStyle::PAS_Right);
18854   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
18855               FormatStyle::PAS_Middle);
18856 
18857   Style.Standard = FormatStyle::LS_Auto;
18858   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
18859   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
18860   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
18861   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
18862   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
18863   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
18864   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
18865   // Legacy aliases:
18866   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
18867   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
18868   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
18869   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
18870 
18871   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
18872   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
18873               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
18874   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
18875               FormatStyle::BOS_None);
18876   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
18877               FormatStyle::BOS_All);
18878   // For backward compatibility:
18879   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
18880               FormatStyle::BOS_None);
18881   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
18882               FormatStyle::BOS_All);
18883 
18884   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
18885   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
18886               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
18887   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
18888               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
18889   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
18890               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
18891   // For backward compatibility:
18892   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
18893               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
18894 
18895   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
18896   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
18897               FormatStyle::BILS_AfterComma);
18898   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
18899               FormatStyle::BILS_BeforeComma);
18900   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
18901               FormatStyle::BILS_AfterColon);
18902   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
18903               FormatStyle::BILS_BeforeColon);
18904   // For backward compatibility:
18905   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
18906               FormatStyle::BILS_BeforeComma);
18907 
18908   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
18909   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
18910               FormatStyle::PCIS_Never);
18911   CHECK_PARSE("PackConstructorInitializers: BinPack",
18912               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
18913   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
18914               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
18915   CHECK_PARSE("PackConstructorInitializers: NextLine",
18916               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
18917   // For backward compatibility:
18918   CHECK_PARSE("BasedOnStyle: Google\n"
18919               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
18920               "AllowAllConstructorInitializersOnNextLine: false",
18921               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
18922   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
18923   CHECK_PARSE("BasedOnStyle: Google\n"
18924               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
18925               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
18926   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
18927               "AllowAllConstructorInitializersOnNextLine: true",
18928               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
18929   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
18930   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
18931               "AllowAllConstructorInitializersOnNextLine: false",
18932               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
18933 
18934   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
18935   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
18936               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
18937   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
18938               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
18939   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
18940               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
18941   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
18942               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
18943 
18944   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
18945   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
18946               FormatStyle::BAS_Align);
18947   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
18948               FormatStyle::BAS_DontAlign);
18949   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
18950               FormatStyle::BAS_AlwaysBreak);
18951   // For backward compatibility:
18952   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
18953               FormatStyle::BAS_DontAlign);
18954   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
18955               FormatStyle::BAS_Align);
18956 
18957   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
18958   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
18959               FormatStyle::ENAS_DontAlign);
18960   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
18961               FormatStyle::ENAS_Left);
18962   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
18963               FormatStyle::ENAS_Right);
18964   // For backward compatibility:
18965   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
18966               FormatStyle::ENAS_Left);
18967   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
18968               FormatStyle::ENAS_Right);
18969 
18970   Style.AlignOperands = FormatStyle::OAS_Align;
18971   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
18972               FormatStyle::OAS_DontAlign);
18973   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
18974   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
18975               FormatStyle::OAS_AlignAfterOperator);
18976   // For backward compatibility:
18977   CHECK_PARSE("AlignOperands: false", AlignOperands,
18978               FormatStyle::OAS_DontAlign);
18979   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
18980 
18981   Style.UseTab = FormatStyle::UT_ForIndentation;
18982   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
18983   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
18984   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
18985   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
18986               FormatStyle::UT_ForContinuationAndIndentation);
18987   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
18988               FormatStyle::UT_AlignWithSpaces);
18989   // For backward compatibility:
18990   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
18991   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
18992 
18993   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
18994   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
18995               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
18996   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
18997               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
18998   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
18999               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19000   // For backward compatibility:
19001   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
19002               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19003   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
19004               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19005 
19006   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
19007   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
19008               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19009   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
19010               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
19011   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
19012               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
19013   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
19014               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19015   // For backward compatibility:
19016   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
19017               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19018   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
19019               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19020 
19021   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
19022   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
19023               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
19024   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
19025               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
19026   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
19027               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
19028   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
19029               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
19030 
19031   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
19032   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
19033               FormatStyle::SBPO_Never);
19034   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
19035               FormatStyle::SBPO_Always);
19036   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
19037               FormatStyle::SBPO_ControlStatements);
19038   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
19039               SpaceBeforeParens,
19040               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19041   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
19042               FormatStyle::SBPO_NonEmptyParentheses);
19043   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
19044               FormatStyle::SBPO_Custom);
19045   // For backward compatibility:
19046   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
19047               FormatStyle::SBPO_Never);
19048   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
19049               FormatStyle::SBPO_ControlStatements);
19050   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
19051               SpaceBeforeParens,
19052               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19053 
19054   Style.ColumnLimit = 123;
19055   FormatStyle BaseStyle = getLLVMStyle();
19056   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
19057   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
19058 
19059   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
19060   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
19061               FormatStyle::BS_Attach);
19062   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
19063               FormatStyle::BS_Linux);
19064   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
19065               FormatStyle::BS_Mozilla);
19066   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
19067               FormatStyle::BS_Stroustrup);
19068   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
19069               FormatStyle::BS_Allman);
19070   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
19071               FormatStyle::BS_Whitesmiths);
19072   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
19073   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
19074               FormatStyle::BS_WebKit);
19075   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
19076               FormatStyle::BS_Custom);
19077 
19078   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
19079   CHECK_PARSE("BraceWrapping:\n"
19080               "  AfterControlStatement: MultiLine",
19081               BraceWrapping.AfterControlStatement,
19082               FormatStyle::BWACS_MultiLine);
19083   CHECK_PARSE("BraceWrapping:\n"
19084               "  AfterControlStatement: Always",
19085               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19086   CHECK_PARSE("BraceWrapping:\n"
19087               "  AfterControlStatement: Never",
19088               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19089   // For backward compatibility:
19090   CHECK_PARSE("BraceWrapping:\n"
19091               "  AfterControlStatement: true",
19092               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19093   CHECK_PARSE("BraceWrapping:\n"
19094               "  AfterControlStatement: false",
19095               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19096 
19097   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
19098   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
19099               FormatStyle::RTBS_None);
19100   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
19101               FormatStyle::RTBS_All);
19102   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
19103               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
19104   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
19105               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
19106   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
19107               AlwaysBreakAfterReturnType,
19108               FormatStyle::RTBS_TopLevelDefinitions);
19109 
19110   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
19111   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
19112               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
19113   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
19114               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19115   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
19116               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19117   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
19118               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19119   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
19120               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19121 
19122   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
19123   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
19124               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
19125   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
19126               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
19127   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
19128               AlwaysBreakAfterDefinitionReturnType,
19129               FormatStyle::DRTBS_TopLevel);
19130 
19131   Style.NamespaceIndentation = FormatStyle::NI_All;
19132   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
19133               FormatStyle::NI_None);
19134   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
19135               FormatStyle::NI_Inner);
19136   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
19137               FormatStyle::NI_All);
19138 
19139   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
19140   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
19141               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19142   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
19143               AllowShortIfStatementsOnASingleLine,
19144               FormatStyle::SIS_WithoutElse);
19145   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
19146               AllowShortIfStatementsOnASingleLine,
19147               FormatStyle::SIS_OnlyFirstIf);
19148   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
19149               AllowShortIfStatementsOnASingleLine,
19150               FormatStyle::SIS_AllIfsAndElse);
19151   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
19152               AllowShortIfStatementsOnASingleLine,
19153               FormatStyle::SIS_OnlyFirstIf);
19154   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
19155               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19156   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
19157               AllowShortIfStatementsOnASingleLine,
19158               FormatStyle::SIS_WithoutElse);
19159 
19160   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
19161   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
19162               FormatStyle::IEBS_AfterExternBlock);
19163   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
19164               FormatStyle::IEBS_Indent);
19165   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
19166               FormatStyle::IEBS_NoIndent);
19167   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
19168               FormatStyle::IEBS_Indent);
19169   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
19170               FormatStyle::IEBS_NoIndent);
19171 
19172   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
19173   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
19174               FormatStyle::BFCS_Both);
19175   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
19176               FormatStyle::BFCS_None);
19177   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
19178               FormatStyle::BFCS_Before);
19179   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
19180               FormatStyle::BFCS_After);
19181 
19182   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
19183   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
19184               FormatStyle::SJSIO_After);
19185   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
19186               FormatStyle::SJSIO_Before);
19187 
19188   // FIXME: This is required because parsing a configuration simply overwrites
19189   // the first N elements of the list instead of resetting it.
19190   Style.ForEachMacros.clear();
19191   std::vector<std::string> BoostForeach;
19192   BoostForeach.push_back("BOOST_FOREACH");
19193   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
19194   std::vector<std::string> BoostAndQForeach;
19195   BoostAndQForeach.push_back("BOOST_FOREACH");
19196   BoostAndQForeach.push_back("Q_FOREACH");
19197   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
19198               BoostAndQForeach);
19199 
19200   Style.IfMacros.clear();
19201   std::vector<std::string> CustomIfs;
19202   CustomIfs.push_back("MYIF");
19203   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
19204 
19205   Style.AttributeMacros.clear();
19206   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
19207               std::vector<std::string>{"__capability"});
19208   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
19209               std::vector<std::string>({"attr1", "attr2"}));
19210 
19211   Style.StatementAttributeLikeMacros.clear();
19212   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
19213               StatementAttributeLikeMacros,
19214               std::vector<std::string>({"emit", "Q_EMIT"}));
19215 
19216   Style.StatementMacros.clear();
19217   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
19218               std::vector<std::string>{"QUNUSED"});
19219   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
19220               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
19221 
19222   Style.NamespaceMacros.clear();
19223   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
19224               std::vector<std::string>{"TESTSUITE"});
19225   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
19226               std::vector<std::string>({"TESTSUITE", "SUITE"}));
19227 
19228   Style.WhitespaceSensitiveMacros.clear();
19229   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
19230               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
19231   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
19232               WhitespaceSensitiveMacros,
19233               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
19234   Style.WhitespaceSensitiveMacros.clear();
19235   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
19236               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
19237   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
19238               WhitespaceSensitiveMacros,
19239               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
19240 
19241   Style.IncludeStyle.IncludeCategories.clear();
19242   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
19243       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
19244   CHECK_PARSE("IncludeCategories:\n"
19245               "  - Regex: abc/.*\n"
19246               "    Priority: 2\n"
19247               "  - Regex: .*\n"
19248               "    Priority: 1\n"
19249               "    CaseSensitive: true\n",
19250               IncludeStyle.IncludeCategories, ExpectedCategories);
19251   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
19252               "abc$");
19253   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
19254               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
19255 
19256   Style.SortIncludes = FormatStyle::SI_Never;
19257   CHECK_PARSE("SortIncludes: true", SortIncludes,
19258               FormatStyle::SI_CaseSensitive);
19259   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
19260   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
19261               FormatStyle::SI_CaseInsensitive);
19262   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
19263               FormatStyle::SI_CaseSensitive);
19264   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
19265 
19266   Style.RawStringFormats.clear();
19267   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
19268       {
19269           FormatStyle::LK_TextProto,
19270           {"pb", "proto"},
19271           {"PARSE_TEXT_PROTO"},
19272           /*CanonicalDelimiter=*/"",
19273           "llvm",
19274       },
19275       {
19276           FormatStyle::LK_Cpp,
19277           {"cc", "cpp"},
19278           {"C_CODEBLOCK", "CPPEVAL"},
19279           /*CanonicalDelimiter=*/"cc",
19280           /*BasedOnStyle=*/"",
19281       },
19282   };
19283 
19284   CHECK_PARSE("RawStringFormats:\n"
19285               "  - Language: TextProto\n"
19286               "    Delimiters:\n"
19287               "      - 'pb'\n"
19288               "      - 'proto'\n"
19289               "    EnclosingFunctions:\n"
19290               "      - 'PARSE_TEXT_PROTO'\n"
19291               "    BasedOnStyle: llvm\n"
19292               "  - Language: Cpp\n"
19293               "    Delimiters:\n"
19294               "      - 'cc'\n"
19295               "      - 'cpp'\n"
19296               "    EnclosingFunctions:\n"
19297               "      - 'C_CODEBLOCK'\n"
19298               "      - 'CPPEVAL'\n"
19299               "    CanonicalDelimiter: 'cc'",
19300               RawStringFormats, ExpectedRawStringFormats);
19301 
19302   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19303               "  Minimum: 0\n"
19304               "  Maximum: 0",
19305               SpacesInLineCommentPrefix.Minimum, 0u);
19306   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
19307   Style.SpacesInLineCommentPrefix.Minimum = 1;
19308   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19309               "  Minimum: 2",
19310               SpacesInLineCommentPrefix.Minimum, 0u);
19311   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19312               "  Maximum: -1",
19313               SpacesInLineCommentPrefix.Maximum, -1u);
19314   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19315               "  Minimum: 2",
19316               SpacesInLineCommentPrefix.Minimum, 2u);
19317   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19318               "  Maximum: 1",
19319               SpacesInLineCommentPrefix.Maximum, 1u);
19320   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
19321 
19322   Style.SpacesInAngles = FormatStyle::SIAS_Always;
19323   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
19324   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
19325               FormatStyle::SIAS_Always);
19326   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
19327   // For backward compatibility:
19328   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
19329   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
19330 }
19331 
19332 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
19333   FormatStyle Style = {};
19334   Style.Language = FormatStyle::LK_Cpp;
19335   CHECK_PARSE("Language: Cpp\n"
19336               "IndentWidth: 12",
19337               IndentWidth, 12u);
19338   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
19339                                "IndentWidth: 34",
19340                                &Style),
19341             ParseError::Unsuitable);
19342   FormatStyle BinPackedTCS = {};
19343   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
19344   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
19345                                "InsertTrailingCommas: Wrapped",
19346                                &BinPackedTCS),
19347             ParseError::BinPackTrailingCommaConflict);
19348   EXPECT_EQ(12u, Style.IndentWidth);
19349   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
19350   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19351 
19352   Style.Language = FormatStyle::LK_JavaScript;
19353   CHECK_PARSE("Language: JavaScript\n"
19354               "IndentWidth: 12",
19355               IndentWidth, 12u);
19356   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
19357   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
19358                                "IndentWidth: 34",
19359                                &Style),
19360             ParseError::Unsuitable);
19361   EXPECT_EQ(23u, Style.IndentWidth);
19362   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
19363   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19364 
19365   CHECK_PARSE("BasedOnStyle: LLVM\n"
19366               "IndentWidth: 67",
19367               IndentWidth, 67u);
19368 
19369   CHECK_PARSE("---\n"
19370               "Language: JavaScript\n"
19371               "IndentWidth: 12\n"
19372               "---\n"
19373               "Language: Cpp\n"
19374               "IndentWidth: 34\n"
19375               "...\n",
19376               IndentWidth, 12u);
19377 
19378   Style.Language = FormatStyle::LK_Cpp;
19379   CHECK_PARSE("---\n"
19380               "Language: JavaScript\n"
19381               "IndentWidth: 12\n"
19382               "---\n"
19383               "Language: Cpp\n"
19384               "IndentWidth: 34\n"
19385               "...\n",
19386               IndentWidth, 34u);
19387   CHECK_PARSE("---\n"
19388               "IndentWidth: 78\n"
19389               "---\n"
19390               "Language: JavaScript\n"
19391               "IndentWidth: 56\n"
19392               "...\n",
19393               IndentWidth, 78u);
19394 
19395   Style.ColumnLimit = 123;
19396   Style.IndentWidth = 234;
19397   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
19398   Style.TabWidth = 345;
19399   EXPECT_FALSE(parseConfiguration("---\n"
19400                                   "IndentWidth: 456\n"
19401                                   "BreakBeforeBraces: Allman\n"
19402                                   "---\n"
19403                                   "Language: JavaScript\n"
19404                                   "IndentWidth: 111\n"
19405                                   "TabWidth: 111\n"
19406                                   "---\n"
19407                                   "Language: Cpp\n"
19408                                   "BreakBeforeBraces: Stroustrup\n"
19409                                   "TabWidth: 789\n"
19410                                   "...\n",
19411                                   &Style));
19412   EXPECT_EQ(123u, Style.ColumnLimit);
19413   EXPECT_EQ(456u, Style.IndentWidth);
19414   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
19415   EXPECT_EQ(789u, Style.TabWidth);
19416 
19417   EXPECT_EQ(parseConfiguration("---\n"
19418                                "Language: JavaScript\n"
19419                                "IndentWidth: 56\n"
19420                                "---\n"
19421                                "IndentWidth: 78\n"
19422                                "...\n",
19423                                &Style),
19424             ParseError::Error);
19425   EXPECT_EQ(parseConfiguration("---\n"
19426                                "Language: JavaScript\n"
19427                                "IndentWidth: 56\n"
19428                                "---\n"
19429                                "Language: JavaScript\n"
19430                                "IndentWidth: 78\n"
19431                                "...\n",
19432                                &Style),
19433             ParseError::Error);
19434 
19435   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19436 }
19437 
19438 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
19439   FormatStyle Style = {};
19440   Style.Language = FormatStyle::LK_JavaScript;
19441   Style.BreakBeforeTernaryOperators = true;
19442   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
19443   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19444 
19445   Style.BreakBeforeTernaryOperators = true;
19446   EXPECT_EQ(0, parseConfiguration("---\n"
19447                                   "BasedOnStyle: Google\n"
19448                                   "---\n"
19449                                   "Language: JavaScript\n"
19450                                   "IndentWidth: 76\n"
19451                                   "...\n",
19452                                   &Style)
19453                    .value());
19454   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19455   EXPECT_EQ(76u, Style.IndentWidth);
19456   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19457 }
19458 
19459 TEST_F(FormatTest, ConfigurationRoundTripTest) {
19460   FormatStyle Style = getLLVMStyle();
19461   std::string YAML = configurationAsText(Style);
19462   FormatStyle ParsedStyle = {};
19463   ParsedStyle.Language = FormatStyle::LK_Cpp;
19464   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
19465   EXPECT_EQ(Style, ParsedStyle);
19466 }
19467 
19468 TEST_F(FormatTest, WorksFor8bitEncodings) {
19469   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
19470             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
19471             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
19472             "\"\xef\xee\xf0\xf3...\"",
19473             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
19474                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
19475                    "\xef\xee\xf0\xf3...\"",
19476                    getLLVMStyleWithColumns(12)));
19477 }
19478 
19479 TEST_F(FormatTest, HandlesUTF8BOM) {
19480   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
19481   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
19482             format("\xef\xbb\xbf#include <iostream>"));
19483   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
19484             format("\xef\xbb\xbf\n#include <iostream>"));
19485 }
19486 
19487 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
19488 #if !defined(_MSC_VER)
19489 
19490 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
19491   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
19492                getLLVMStyleWithColumns(35));
19493   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
19494                getLLVMStyleWithColumns(31));
19495   verifyFormat("// Однажды в студёную зимнюю пору...",
19496                getLLVMStyleWithColumns(36));
19497   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
19498   verifyFormat("/* Однажды в студёную зимнюю пору... */",
19499                getLLVMStyleWithColumns(39));
19500   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
19501                getLLVMStyleWithColumns(35));
19502 }
19503 
19504 TEST_F(FormatTest, SplitsUTF8Strings) {
19505   // Non-printable characters' width is currently considered to be the length in
19506   // bytes in UTF8. The characters can be displayed in very different manner
19507   // (zero-width, single width with a substitution glyph, expanded to their code
19508   // (e.g. "<8d>"), so there's no single correct way to handle them.
19509   EXPECT_EQ("\"aaaaÄ\"\n"
19510             "\"\xc2\x8d\";",
19511             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19512   EXPECT_EQ("\"aaaaaaaÄ\"\n"
19513             "\"\xc2\x8d\";",
19514             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19515   EXPECT_EQ("\"Однажды, в \"\n"
19516             "\"студёную \"\n"
19517             "\"зимнюю \"\n"
19518             "\"пору,\"",
19519             format("\"Однажды, в студёную зимнюю пору,\"",
19520                    getLLVMStyleWithColumns(13)));
19521   EXPECT_EQ(
19522       "\"一 二 三 \"\n"
19523       "\"四 五六 \"\n"
19524       "\"七 八 九 \"\n"
19525       "\"十\"",
19526       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
19527   EXPECT_EQ("\"一\t\"\n"
19528             "\"二 \t\"\n"
19529             "\"三 四 \"\n"
19530             "\"五\t\"\n"
19531             "\"六 \t\"\n"
19532             "\"七 \"\n"
19533             "\"八九十\tqq\"",
19534             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
19535                    getLLVMStyleWithColumns(11)));
19536 
19537   // UTF8 character in an escape sequence.
19538   EXPECT_EQ("\"aaaaaa\"\n"
19539             "\"\\\xC2\x8D\"",
19540             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
19541 }
19542 
19543 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
19544   EXPECT_EQ("const char *sssss =\n"
19545             "    \"一二三四五六七八\\\n"
19546             " 九 十\";",
19547             format("const char *sssss = \"一二三四五六七八\\\n"
19548                    " 九 十\";",
19549                    getLLVMStyleWithColumns(30)));
19550 }
19551 
19552 TEST_F(FormatTest, SplitsUTF8LineComments) {
19553   EXPECT_EQ("// aaaaÄ\xc2\x8d",
19554             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
19555   EXPECT_EQ("// Я из лесу\n"
19556             "// вышел; был\n"
19557             "// сильный\n"
19558             "// мороз.",
19559             format("// Я из лесу вышел; был сильный мороз.",
19560                    getLLVMStyleWithColumns(13)));
19561   EXPECT_EQ("// 一二三\n"
19562             "// 四五六七\n"
19563             "// 八  九\n"
19564             "// 十",
19565             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
19566 }
19567 
19568 TEST_F(FormatTest, SplitsUTF8BlockComments) {
19569   EXPECT_EQ("/* Гляжу,\n"
19570             " * поднимается\n"
19571             " * медленно в\n"
19572             " * гору\n"
19573             " * Лошадка,\n"
19574             " * везущая\n"
19575             " * хворосту\n"
19576             " * воз. */",
19577             format("/* Гляжу, поднимается медленно в гору\n"
19578                    " * Лошадка, везущая хворосту воз. */",
19579                    getLLVMStyleWithColumns(13)));
19580   EXPECT_EQ(
19581       "/* 一二三\n"
19582       " * 四五六七\n"
19583       " * 八  九\n"
19584       " * 十  */",
19585       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
19586   EXPECT_EQ("/* �������� ��������\n"
19587             " * ��������\n"
19588             " * ������-�� */",
19589             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
19590 }
19591 
19592 #endif // _MSC_VER
19593 
19594 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
19595   FormatStyle Style = getLLVMStyle();
19596 
19597   Style.ConstructorInitializerIndentWidth = 4;
19598   verifyFormat(
19599       "SomeClass::Constructor()\n"
19600       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19601       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19602       Style);
19603 
19604   Style.ConstructorInitializerIndentWidth = 2;
19605   verifyFormat(
19606       "SomeClass::Constructor()\n"
19607       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19608       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19609       Style);
19610 
19611   Style.ConstructorInitializerIndentWidth = 0;
19612   verifyFormat(
19613       "SomeClass::Constructor()\n"
19614       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19615       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19616       Style);
19617   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19618   verifyFormat(
19619       "SomeLongTemplateVariableName<\n"
19620       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
19621       Style);
19622   verifyFormat("bool smaller = 1 < "
19623                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
19624                "                       "
19625                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
19626                Style);
19627 
19628   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
19629   verifyFormat("SomeClass::Constructor() :\n"
19630                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
19631                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
19632                Style);
19633 }
19634 
19635 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
19636   FormatStyle Style = getLLVMStyle();
19637   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19638   Style.ConstructorInitializerIndentWidth = 4;
19639   verifyFormat("SomeClass::Constructor()\n"
19640                "    : a(a)\n"
19641                "    , b(b)\n"
19642                "    , c(c) {}",
19643                Style);
19644   verifyFormat("SomeClass::Constructor()\n"
19645                "    : a(a) {}",
19646                Style);
19647 
19648   Style.ColumnLimit = 0;
19649   verifyFormat("SomeClass::Constructor()\n"
19650                "    : a(a) {}",
19651                Style);
19652   verifyFormat("SomeClass::Constructor() noexcept\n"
19653                "    : a(a) {}",
19654                Style);
19655   verifyFormat("SomeClass::Constructor()\n"
19656                "    : a(a)\n"
19657                "    , b(b)\n"
19658                "    , c(c) {}",
19659                Style);
19660   verifyFormat("SomeClass::Constructor()\n"
19661                "    : a(a) {\n"
19662                "  foo();\n"
19663                "  bar();\n"
19664                "}",
19665                Style);
19666 
19667   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
19668   verifyFormat("SomeClass::Constructor()\n"
19669                "    : a(a)\n"
19670                "    , b(b)\n"
19671                "    , c(c) {\n}",
19672                Style);
19673   verifyFormat("SomeClass::Constructor()\n"
19674                "    : a(a) {\n}",
19675                Style);
19676 
19677   Style.ColumnLimit = 80;
19678   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
19679   Style.ConstructorInitializerIndentWidth = 2;
19680   verifyFormat("SomeClass::Constructor()\n"
19681                "  : a(a)\n"
19682                "  , b(b)\n"
19683                "  , c(c) {}",
19684                Style);
19685 
19686   Style.ConstructorInitializerIndentWidth = 0;
19687   verifyFormat("SomeClass::Constructor()\n"
19688                ": a(a)\n"
19689                ", b(b)\n"
19690                ", c(c) {}",
19691                Style);
19692 
19693   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19694   Style.ConstructorInitializerIndentWidth = 4;
19695   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
19696   verifyFormat(
19697       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
19698       Style);
19699   verifyFormat(
19700       "SomeClass::Constructor()\n"
19701       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
19702       Style);
19703   Style.ConstructorInitializerIndentWidth = 4;
19704   Style.ColumnLimit = 60;
19705   verifyFormat("SomeClass::Constructor()\n"
19706                "    : aaaaaaaa(aaaaaaaa)\n"
19707                "    , aaaaaaaa(aaaaaaaa)\n"
19708                "    , aaaaaaaa(aaaaaaaa) {}",
19709                Style);
19710 }
19711 
19712 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
19713   FormatStyle Style = getLLVMStyle();
19714   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19715   Style.ConstructorInitializerIndentWidth = 4;
19716   verifyFormat("SomeClass::Constructor()\n"
19717                "    : a{a}\n"
19718                "    , b{b} {}",
19719                Style);
19720   verifyFormat("SomeClass::Constructor()\n"
19721                "    : a{a}\n"
19722                "#if CONDITION\n"
19723                "    , b{b}\n"
19724                "#endif\n"
19725                "{\n}",
19726                Style);
19727   Style.ConstructorInitializerIndentWidth = 2;
19728   verifyFormat("SomeClass::Constructor()\n"
19729                "#if CONDITION\n"
19730                "  : a{a}\n"
19731                "#endif\n"
19732                "  , b{b}\n"
19733                "  , c{c} {\n}",
19734                Style);
19735   Style.ConstructorInitializerIndentWidth = 0;
19736   verifyFormat("SomeClass::Constructor()\n"
19737                ": a{a}\n"
19738                "#ifdef CONDITION\n"
19739                ", b{b}\n"
19740                "#else\n"
19741                ", c{c}\n"
19742                "#endif\n"
19743                ", d{d} {\n}",
19744                Style);
19745   Style.ConstructorInitializerIndentWidth = 4;
19746   verifyFormat("SomeClass::Constructor()\n"
19747                "    : a{a}\n"
19748                "#if WINDOWS\n"
19749                "#if DEBUG\n"
19750                "    , b{0}\n"
19751                "#else\n"
19752                "    , b{1}\n"
19753                "#endif\n"
19754                "#else\n"
19755                "#if DEBUG\n"
19756                "    , b{2}\n"
19757                "#else\n"
19758                "    , b{3}\n"
19759                "#endif\n"
19760                "#endif\n"
19761                "{\n}",
19762                Style);
19763   verifyFormat("SomeClass::Constructor()\n"
19764                "    : a{a}\n"
19765                "#if WINDOWS\n"
19766                "    , b{0}\n"
19767                "#if DEBUG\n"
19768                "    , c{0}\n"
19769                "#else\n"
19770                "    , c{1}\n"
19771                "#endif\n"
19772                "#else\n"
19773                "#if DEBUG\n"
19774                "    , c{2}\n"
19775                "#else\n"
19776                "    , c{3}\n"
19777                "#endif\n"
19778                "    , b{1}\n"
19779                "#endif\n"
19780                "{\n}",
19781                Style);
19782 }
19783 
19784 TEST_F(FormatTest, Destructors) {
19785   verifyFormat("void F(int &i) { i.~int(); }");
19786   verifyFormat("void F(int &i) { i->~int(); }");
19787 }
19788 
19789 TEST_F(FormatTest, FormatsWithWebKitStyle) {
19790   FormatStyle Style = getWebKitStyle();
19791 
19792   // Don't indent in outer namespaces.
19793   verifyFormat("namespace outer {\n"
19794                "int i;\n"
19795                "namespace inner {\n"
19796                "    int i;\n"
19797                "} // namespace inner\n"
19798                "} // namespace outer\n"
19799                "namespace other_outer {\n"
19800                "int i;\n"
19801                "}",
19802                Style);
19803 
19804   // Don't indent case labels.
19805   verifyFormat("switch (variable) {\n"
19806                "case 1:\n"
19807                "case 2:\n"
19808                "    doSomething();\n"
19809                "    break;\n"
19810                "default:\n"
19811                "    ++variable;\n"
19812                "}",
19813                Style);
19814 
19815   // Wrap before binary operators.
19816   EXPECT_EQ("void f()\n"
19817             "{\n"
19818             "    if (aaaaaaaaaaaaaaaa\n"
19819             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
19820             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
19821             "        return;\n"
19822             "}",
19823             format("void f() {\n"
19824                    "if (aaaaaaaaaaaaaaaa\n"
19825                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
19826                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
19827                    "return;\n"
19828                    "}",
19829                    Style));
19830 
19831   // Allow functions on a single line.
19832   verifyFormat("void f() { return; }", Style);
19833 
19834   // Allow empty blocks on a single line and insert a space in empty blocks.
19835   EXPECT_EQ("void f() { }", format("void f() {}", Style));
19836   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
19837   // However, don't merge non-empty short loops.
19838   EXPECT_EQ("while (true) {\n"
19839             "    continue;\n"
19840             "}",
19841             format("while (true) { continue; }", Style));
19842 
19843   // Constructor initializers are formatted one per line with the "," on the
19844   // new line.
19845   verifyFormat("Constructor()\n"
19846                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
19847                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
19848                "          aaaaaaaaaaaaaa)\n"
19849                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
19850                "{\n"
19851                "}",
19852                Style);
19853   verifyFormat("SomeClass::Constructor()\n"
19854                "    : a(a)\n"
19855                "{\n"
19856                "}",
19857                Style);
19858   EXPECT_EQ("SomeClass::Constructor()\n"
19859             "    : a(a)\n"
19860             "{\n"
19861             "}",
19862             format("SomeClass::Constructor():a(a){}", Style));
19863   verifyFormat("SomeClass::Constructor()\n"
19864                "    : a(a)\n"
19865                "    , b(b)\n"
19866                "    , c(c)\n"
19867                "{\n"
19868                "}",
19869                Style);
19870   verifyFormat("SomeClass::Constructor()\n"
19871                "    : a(a)\n"
19872                "{\n"
19873                "    foo();\n"
19874                "    bar();\n"
19875                "}",
19876                Style);
19877 
19878   // Access specifiers should be aligned left.
19879   verifyFormat("class C {\n"
19880                "public:\n"
19881                "    int i;\n"
19882                "};",
19883                Style);
19884 
19885   // Do not align comments.
19886   verifyFormat("int a; // Do not\n"
19887                "double b; // align comments.",
19888                Style);
19889 
19890   // Do not align operands.
19891   EXPECT_EQ("ASSERT(aaaa\n"
19892             "    || bbbb);",
19893             format("ASSERT ( aaaa\n||bbbb);", Style));
19894 
19895   // Accept input's line breaks.
19896   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
19897             "    || bbbbbbbbbbbbbbb) {\n"
19898             "    i++;\n"
19899             "}",
19900             format("if (aaaaaaaaaaaaaaa\n"
19901                    "|| bbbbbbbbbbbbbbb) { i++; }",
19902                    Style));
19903   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
19904             "    i++;\n"
19905             "}",
19906             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
19907 
19908   // Don't automatically break all macro definitions (llvm.org/PR17842).
19909   verifyFormat("#define aNumber 10", Style);
19910   // However, generally keep the line breaks that the user authored.
19911   EXPECT_EQ("#define aNumber \\\n"
19912             "    10",
19913             format("#define aNumber \\\n"
19914                    " 10",
19915                    Style));
19916 
19917   // Keep empty and one-element array literals on a single line.
19918   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
19919             "                                  copyItems:YES];",
19920             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
19921                    "copyItems:YES];",
19922                    Style));
19923   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
19924             "                                  copyItems:YES];",
19925             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
19926                    "             copyItems:YES];",
19927                    Style));
19928   // FIXME: This does not seem right, there should be more indentation before
19929   // the array literal's entries. Nested blocks have the same problem.
19930   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
19931             "    @\"a\",\n"
19932             "    @\"a\"\n"
19933             "]\n"
19934             "                                  copyItems:YES];",
19935             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
19936                    "     @\"a\",\n"
19937                    "     @\"a\"\n"
19938                    "     ]\n"
19939                    "       copyItems:YES];",
19940                    Style));
19941   EXPECT_EQ(
19942       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
19943       "                                  copyItems:YES];",
19944       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
19945              "   copyItems:YES];",
19946              Style));
19947 
19948   verifyFormat("[self.a b:c c:d];", Style);
19949   EXPECT_EQ("[self.a b:c\n"
19950             "        c:d];",
19951             format("[self.a b:c\n"
19952                    "c:d];",
19953                    Style));
19954 }
19955 
19956 TEST_F(FormatTest, FormatsLambdas) {
19957   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
19958   verifyFormat(
19959       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
19960   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
19961   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
19962   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
19963   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
19964   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
19965   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
19966   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
19967   verifyFormat("int x = f(*+[] {});");
19968   verifyFormat("void f() {\n"
19969                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
19970                "}\n");
19971   verifyFormat("void f() {\n"
19972                "  other(x.begin(), //\n"
19973                "        x.end(),   //\n"
19974                "        [&](int, int) { return 1; });\n"
19975                "}\n");
19976   verifyFormat("void f() {\n"
19977                "  other.other.other.other.other(\n"
19978                "      x.begin(), x.end(),\n"
19979                "      [something, rather](int, int, int, int, int, int, int) { "
19980                "return 1; });\n"
19981                "}\n");
19982   verifyFormat(
19983       "void f() {\n"
19984       "  other.other.other.other.other(\n"
19985       "      x.begin(), x.end(),\n"
19986       "      [something, rather](int, int, int, int, int, int, int) {\n"
19987       "        //\n"
19988       "      });\n"
19989       "}\n");
19990   verifyFormat("SomeFunction([]() { // A cool function...\n"
19991                "  return 43;\n"
19992                "});");
19993   EXPECT_EQ("SomeFunction([]() {\n"
19994             "#define A a\n"
19995             "  return 43;\n"
19996             "});",
19997             format("SomeFunction([](){\n"
19998                    "#define A a\n"
19999                    "return 43;\n"
20000                    "});"));
20001   verifyFormat("void f() {\n"
20002                "  SomeFunction([](decltype(x), A *a) {});\n"
20003                "  SomeFunction([](typeof(x), A *a) {});\n"
20004                "  SomeFunction([](_Atomic(x), A *a) {});\n"
20005                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
20006                "}");
20007   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20008                "    [](const aaaaaaaaaa &a) { return a; });");
20009   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
20010                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
20011                "});");
20012   verifyFormat("Constructor()\n"
20013                "    : Field([] { // comment\n"
20014                "        int i;\n"
20015                "      }) {}");
20016   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
20017                "  return some_parameter.size();\n"
20018                "};");
20019   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
20020                "    [](const string &s) { return s; };");
20021   verifyFormat("int i = aaaaaa ? 1 //\n"
20022                "               : [] {\n"
20023                "                   return 2; //\n"
20024                "                 }();");
20025   verifyFormat("llvm::errs() << \"number of twos is \"\n"
20026                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
20027                "                  return x == 2; // force break\n"
20028                "                });");
20029   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20030                "    [=](int iiiiiiiiiiii) {\n"
20031                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
20032                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
20033                "    });",
20034                getLLVMStyleWithColumns(60));
20035 
20036   verifyFormat("SomeFunction({[&] {\n"
20037                "                // comment\n"
20038                "              },\n"
20039                "              [&] {\n"
20040                "                // comment\n"
20041                "              }});");
20042   verifyFormat("SomeFunction({[&] {\n"
20043                "  // comment\n"
20044                "}});");
20045   verifyFormat(
20046       "virtual aaaaaaaaaaaaaaaa(\n"
20047       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
20048       "    aaaaa aaaaaaaaa);");
20049 
20050   // Lambdas with return types.
20051   verifyFormat("int c = []() -> int { return 2; }();\n");
20052   verifyFormat("int c = []() -> int * { return 2; }();\n");
20053   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
20054   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
20055   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
20056   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
20057   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
20058   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
20059   verifyFormat("[a, a]() -> a<1> {};");
20060   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
20061   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
20062   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
20063   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
20064   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
20065   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
20066   verifyFormat("[]() -> foo<!5> { return {}; };");
20067   verifyFormat("[]() -> foo<~5> { return {}; };");
20068   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
20069   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
20070   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
20071   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
20072   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
20073   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
20074   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
20075   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
20076   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
20077   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
20078   verifyFormat("namespace bar {\n"
20079                "// broken:\n"
20080                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
20081                "} // namespace bar");
20082   verifyFormat("namespace bar {\n"
20083                "// broken:\n"
20084                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
20085                "} // namespace bar");
20086   verifyFormat("namespace bar {\n"
20087                "// broken:\n"
20088                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
20089                "} // namespace bar");
20090   verifyFormat("namespace bar {\n"
20091                "// broken:\n"
20092                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
20093                "} // namespace bar");
20094   verifyFormat("namespace bar {\n"
20095                "// broken:\n"
20096                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
20097                "} // namespace bar");
20098   verifyFormat("namespace bar {\n"
20099                "// broken:\n"
20100                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
20101                "} // namespace bar");
20102   verifyFormat("namespace bar {\n"
20103                "// broken:\n"
20104                "auto foo{[]() -> foo<!5> { return {}; }};\n"
20105                "} // namespace bar");
20106   verifyFormat("namespace bar {\n"
20107                "// broken:\n"
20108                "auto foo{[]() -> foo<~5> { return {}; }};\n"
20109                "} // namespace bar");
20110   verifyFormat("namespace bar {\n"
20111                "// broken:\n"
20112                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
20113                "} // namespace bar");
20114   verifyFormat("namespace bar {\n"
20115                "// broken:\n"
20116                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
20117                "} // namespace bar");
20118   verifyFormat("namespace bar {\n"
20119                "// broken:\n"
20120                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
20121                "} // namespace bar");
20122   verifyFormat("namespace bar {\n"
20123                "// broken:\n"
20124                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
20125                "} // namespace bar");
20126   verifyFormat("namespace bar {\n"
20127                "// broken:\n"
20128                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
20129                "} // namespace bar");
20130   verifyFormat("namespace bar {\n"
20131                "// broken:\n"
20132                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
20133                "} // namespace bar");
20134   verifyFormat("namespace bar {\n"
20135                "// broken:\n"
20136                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
20137                "} // namespace bar");
20138   verifyFormat("namespace bar {\n"
20139                "// broken:\n"
20140                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
20141                "} // namespace bar");
20142   verifyFormat("namespace bar {\n"
20143                "// broken:\n"
20144                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
20145                "} // namespace bar");
20146   verifyFormat("namespace bar {\n"
20147                "// broken:\n"
20148                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
20149                "} // namespace bar");
20150   verifyFormat("[]() -> a<1> {};");
20151   verifyFormat("[]() -> a<1> { ; };");
20152   verifyFormat("[]() -> a<1> { ; }();");
20153   verifyFormat("[a, a]() -> a<true> {};");
20154   verifyFormat("[]() -> a<true> {};");
20155   verifyFormat("[]() -> a<true> { ; };");
20156   verifyFormat("[]() -> a<true> { ; }();");
20157   verifyFormat("[a, a]() -> a<false> {};");
20158   verifyFormat("[]() -> a<false> {};");
20159   verifyFormat("[]() -> a<false> { ; };");
20160   verifyFormat("[]() -> a<false> { ; }();");
20161   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
20162   verifyFormat("namespace bar {\n"
20163                "auto foo{[]() -> foo<false> { ; }};\n"
20164                "} // namespace bar");
20165   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
20166                "                   int j) -> int {\n"
20167                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
20168                "};");
20169   verifyFormat(
20170       "aaaaaaaaaaaaaaaaaaaaaa(\n"
20171       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
20172       "      return aaaaaaaaaaaaaaaaa;\n"
20173       "    });",
20174       getLLVMStyleWithColumns(70));
20175   verifyFormat("[]() //\n"
20176                "    -> int {\n"
20177                "  return 1; //\n"
20178                "};");
20179   verifyFormat("[]() -> Void<T...> {};");
20180   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
20181 
20182   // Lambdas with explicit template argument lists.
20183   verifyFormat(
20184       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
20185 
20186   // Multiple lambdas in the same parentheses change indentation rules. These
20187   // lambdas are forced to start on new lines.
20188   verifyFormat("SomeFunction(\n"
20189                "    []() {\n"
20190                "      //\n"
20191                "    },\n"
20192                "    []() {\n"
20193                "      //\n"
20194                "    });");
20195 
20196   // A lambda passed as arg0 is always pushed to the next line.
20197   verifyFormat("SomeFunction(\n"
20198                "    [this] {\n"
20199                "      //\n"
20200                "    },\n"
20201                "    1);\n");
20202 
20203   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
20204   // the arg0 case above.
20205   auto Style = getGoogleStyle();
20206   Style.BinPackArguments = false;
20207   verifyFormat("SomeFunction(\n"
20208                "    a,\n"
20209                "    [this] {\n"
20210                "      //\n"
20211                "    },\n"
20212                "    b);\n",
20213                Style);
20214   verifyFormat("SomeFunction(\n"
20215                "    a,\n"
20216                "    [this] {\n"
20217                "      //\n"
20218                "    },\n"
20219                "    b);\n");
20220 
20221   // A lambda with a very long line forces arg0 to be pushed out irrespective of
20222   // the BinPackArguments value (as long as the code is wide enough).
20223   verifyFormat(
20224       "something->SomeFunction(\n"
20225       "    a,\n"
20226       "    [this] {\n"
20227       "      "
20228       "D0000000000000000000000000000000000000000000000000000000000001();\n"
20229       "    },\n"
20230       "    b);\n");
20231 
20232   // A multi-line lambda is pulled up as long as the introducer fits on the
20233   // previous line and there are no further args.
20234   verifyFormat("function(1, [this, that] {\n"
20235                "  //\n"
20236                "});\n");
20237   verifyFormat("function([this, that] {\n"
20238                "  //\n"
20239                "});\n");
20240   // FIXME: this format is not ideal and we should consider forcing the first
20241   // arg onto its own line.
20242   verifyFormat("function(a, b, c, //\n"
20243                "         d, [this, that] {\n"
20244                "           //\n"
20245                "         });\n");
20246 
20247   // Multiple lambdas are treated correctly even when there is a short arg0.
20248   verifyFormat("SomeFunction(\n"
20249                "    1,\n"
20250                "    [this] {\n"
20251                "      //\n"
20252                "    },\n"
20253                "    [this] {\n"
20254                "      //\n"
20255                "    },\n"
20256                "    1);\n");
20257 
20258   // More complex introducers.
20259   verifyFormat("return [i, args...] {};");
20260 
20261   // Not lambdas.
20262   verifyFormat("constexpr char hello[]{\"hello\"};");
20263   verifyFormat("double &operator[](int i) { return 0; }\n"
20264                "int i;");
20265   verifyFormat("std::unique_ptr<int[]> foo() {}");
20266   verifyFormat("int i = a[a][a]->f();");
20267   verifyFormat("int i = (*b)[a]->f();");
20268 
20269   // Other corner cases.
20270   verifyFormat("void f() {\n"
20271                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
20272                "  );\n"
20273                "}");
20274 
20275   // Lambdas created through weird macros.
20276   verifyFormat("void f() {\n"
20277                "  MACRO((const AA &a) { return 1; });\n"
20278                "  MACRO((AA &a) { return 1; });\n"
20279                "}");
20280 
20281   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
20282                "      doo_dah();\n"
20283                "      doo_dah();\n"
20284                "    })) {\n"
20285                "}");
20286   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
20287                "                doo_dah();\n"
20288                "                doo_dah();\n"
20289                "              })) {\n"
20290                "}");
20291   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
20292                "                doo_dah();\n"
20293                "                doo_dah();\n"
20294                "              })) {\n"
20295                "}");
20296   verifyFormat("auto lambda = []() {\n"
20297                "  int a = 2\n"
20298                "#if A\n"
20299                "          + 2\n"
20300                "#endif\n"
20301                "      ;\n"
20302                "};");
20303 
20304   // Lambdas with complex multiline introducers.
20305   verifyFormat(
20306       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20307       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
20308       "        -> ::std::unordered_set<\n"
20309       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
20310       "      //\n"
20311       "    });");
20312 
20313   FormatStyle DoNotMerge = getLLVMStyle();
20314   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
20315   verifyFormat("auto c = []() {\n"
20316                "  return b;\n"
20317                "};",
20318                "auto c = []() { return b; };", DoNotMerge);
20319   verifyFormat("auto c = []() {\n"
20320                "};",
20321                " auto c = []() {};", DoNotMerge);
20322 
20323   FormatStyle MergeEmptyOnly = getLLVMStyle();
20324   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
20325   verifyFormat("auto c = []() {\n"
20326                "  return b;\n"
20327                "};",
20328                "auto c = []() {\n"
20329                "  return b;\n"
20330                " };",
20331                MergeEmptyOnly);
20332   verifyFormat("auto c = []() {};",
20333                "auto c = []() {\n"
20334                "};",
20335                MergeEmptyOnly);
20336 
20337   FormatStyle MergeInline = getLLVMStyle();
20338   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
20339   verifyFormat("auto c = []() {\n"
20340                "  return b;\n"
20341                "};",
20342                "auto c = []() { return b; };", MergeInline);
20343   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
20344                MergeInline);
20345   verifyFormat("function([]() { return b; }, a)",
20346                "function([]() { return b; }, a)", MergeInline);
20347   verifyFormat("function(a, []() { return b; })",
20348                "function(a, []() { return b; })", MergeInline);
20349 
20350   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
20351   // AllowShortLambdasOnASingleLine
20352   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20353   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20354   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20355   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20356       FormatStyle::ShortLambdaStyle::SLS_None;
20357   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
20358                "    []()\n"
20359                "    {\n"
20360                "      return 17;\n"
20361                "    });",
20362                LLVMWithBeforeLambdaBody);
20363   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
20364                "    []()\n"
20365                "    {\n"
20366                "    });",
20367                LLVMWithBeforeLambdaBody);
20368   verifyFormat("auto fct_SLS_None = []()\n"
20369                "{\n"
20370                "  return 17;\n"
20371                "};",
20372                LLVMWithBeforeLambdaBody);
20373   verifyFormat("TwoNestedLambdas_SLS_None(\n"
20374                "    []()\n"
20375                "    {\n"
20376                "      return Call(\n"
20377                "          []()\n"
20378                "          {\n"
20379                "            return 17;\n"
20380                "          });\n"
20381                "    });",
20382                LLVMWithBeforeLambdaBody);
20383   verifyFormat("void Fct() {\n"
20384                "  return {[]()\n"
20385                "          {\n"
20386                "            return 17;\n"
20387                "          }};\n"
20388                "}",
20389                LLVMWithBeforeLambdaBody);
20390 
20391   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20392       FormatStyle::ShortLambdaStyle::SLS_Empty;
20393   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
20394                "    []()\n"
20395                "    {\n"
20396                "      return 17;\n"
20397                "    });",
20398                LLVMWithBeforeLambdaBody);
20399   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
20400                LLVMWithBeforeLambdaBody);
20401   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
20402                "ongFunctionName_SLS_Empty(\n"
20403                "    []() {});",
20404                LLVMWithBeforeLambdaBody);
20405   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
20406                "                                []()\n"
20407                "                                {\n"
20408                "                                  return 17;\n"
20409                "                                });",
20410                LLVMWithBeforeLambdaBody);
20411   verifyFormat("auto fct_SLS_Empty = []()\n"
20412                "{\n"
20413                "  return 17;\n"
20414                "};",
20415                LLVMWithBeforeLambdaBody);
20416   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
20417                "    []()\n"
20418                "    {\n"
20419                "      return Call([]() {});\n"
20420                "    });",
20421                LLVMWithBeforeLambdaBody);
20422   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
20423                "                           []()\n"
20424                "                           {\n"
20425                "                             return Call([]() {});\n"
20426                "                           });",
20427                LLVMWithBeforeLambdaBody);
20428   verifyFormat(
20429       "FctWithLongLineInLambda_SLS_Empty(\n"
20430       "    []()\n"
20431       "    {\n"
20432       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20433       "                               AndShouldNotBeConsiderAsInline,\n"
20434       "                               LambdaBodyMustBeBreak);\n"
20435       "    });",
20436       LLVMWithBeforeLambdaBody);
20437 
20438   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20439       FormatStyle::ShortLambdaStyle::SLS_Inline;
20440   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
20441                LLVMWithBeforeLambdaBody);
20442   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
20443                LLVMWithBeforeLambdaBody);
20444   verifyFormat("auto fct_SLS_Inline = []()\n"
20445                "{\n"
20446                "  return 17;\n"
20447                "};",
20448                LLVMWithBeforeLambdaBody);
20449   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
20450                "17; }); });",
20451                LLVMWithBeforeLambdaBody);
20452   verifyFormat(
20453       "FctWithLongLineInLambda_SLS_Inline(\n"
20454       "    []()\n"
20455       "    {\n"
20456       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20457       "                               AndShouldNotBeConsiderAsInline,\n"
20458       "                               LambdaBodyMustBeBreak);\n"
20459       "    });",
20460       LLVMWithBeforeLambdaBody);
20461   verifyFormat("FctWithMultipleParams_SLS_Inline("
20462                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20463                "                                 []() { return 17; });",
20464                LLVMWithBeforeLambdaBody);
20465   verifyFormat(
20466       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
20467       LLVMWithBeforeLambdaBody);
20468 
20469   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20470       FormatStyle::ShortLambdaStyle::SLS_All;
20471   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
20472                LLVMWithBeforeLambdaBody);
20473   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
20474                LLVMWithBeforeLambdaBody);
20475   verifyFormat("auto fct_SLS_All = []() { return 17; };",
20476                LLVMWithBeforeLambdaBody);
20477   verifyFormat("FctWithOneParam_SLS_All(\n"
20478                "    []()\n"
20479                "    {\n"
20480                "      // A cool function...\n"
20481                "      return 43;\n"
20482                "    });",
20483                LLVMWithBeforeLambdaBody);
20484   verifyFormat("FctWithMultipleParams_SLS_All("
20485                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20486                "                              []() { return 17; });",
20487                LLVMWithBeforeLambdaBody);
20488   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
20489                LLVMWithBeforeLambdaBody);
20490   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
20491                LLVMWithBeforeLambdaBody);
20492   verifyFormat(
20493       "FctWithLongLineInLambda_SLS_All(\n"
20494       "    []()\n"
20495       "    {\n"
20496       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20497       "                               AndShouldNotBeConsiderAsInline,\n"
20498       "                               LambdaBodyMustBeBreak);\n"
20499       "    });",
20500       LLVMWithBeforeLambdaBody);
20501   verifyFormat(
20502       "auto fct_SLS_All = []()\n"
20503       "{\n"
20504       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20505       "                           AndShouldNotBeConsiderAsInline,\n"
20506       "                           LambdaBodyMustBeBreak);\n"
20507       "};",
20508       LLVMWithBeforeLambdaBody);
20509   LLVMWithBeforeLambdaBody.BinPackParameters = false;
20510   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
20511                LLVMWithBeforeLambdaBody);
20512   verifyFormat(
20513       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
20514       "                                FirstParam,\n"
20515       "                                SecondParam,\n"
20516       "                                ThirdParam,\n"
20517       "                                FourthParam);",
20518       LLVMWithBeforeLambdaBody);
20519   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20520                "    []() { return "
20521                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
20522                "    FirstParam,\n"
20523                "    SecondParam,\n"
20524                "    ThirdParam,\n"
20525                "    FourthParam);",
20526                LLVMWithBeforeLambdaBody);
20527   verifyFormat(
20528       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
20529       "                                SecondParam,\n"
20530       "                                ThirdParam,\n"
20531       "                                FourthParam,\n"
20532       "                                []() { return SomeValueNotSoLong; });",
20533       LLVMWithBeforeLambdaBody);
20534   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20535                "    []()\n"
20536                "    {\n"
20537                "      return "
20538                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
20539                "eConsiderAsInline;\n"
20540                "    });",
20541                LLVMWithBeforeLambdaBody);
20542   verifyFormat(
20543       "FctWithLongLineInLambda_SLS_All(\n"
20544       "    []()\n"
20545       "    {\n"
20546       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20547       "                               AndShouldNotBeConsiderAsInline,\n"
20548       "                               LambdaBodyMustBeBreak);\n"
20549       "    });",
20550       LLVMWithBeforeLambdaBody);
20551   verifyFormat("FctWithTwoParams_SLS_All(\n"
20552                "    []()\n"
20553                "    {\n"
20554                "      // A cool function...\n"
20555                "      return 43;\n"
20556                "    },\n"
20557                "    87);",
20558                LLVMWithBeforeLambdaBody);
20559   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
20560                LLVMWithBeforeLambdaBody);
20561   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
20562                LLVMWithBeforeLambdaBody);
20563   verifyFormat(
20564       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
20565       LLVMWithBeforeLambdaBody);
20566   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
20567                "}); }, x);",
20568                LLVMWithBeforeLambdaBody);
20569   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20570                "    []()\n"
20571                "    {\n"
20572                "      // A cool function...\n"
20573                "      return Call([]() { return 17; });\n"
20574                "    });",
20575                LLVMWithBeforeLambdaBody);
20576   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20577                "    []()\n"
20578                "    {\n"
20579                "      return Call(\n"
20580                "          []()\n"
20581                "          {\n"
20582                "            // A cool function...\n"
20583                "            return 17;\n"
20584                "          });\n"
20585                "    });",
20586                LLVMWithBeforeLambdaBody);
20587 
20588   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20589       FormatStyle::ShortLambdaStyle::SLS_None;
20590 
20591   verifyFormat("auto select = [this]() -> const Library::Object *\n"
20592                "{\n"
20593                "  return MyAssignment::SelectFromList(this);\n"
20594                "};\n",
20595                LLVMWithBeforeLambdaBody);
20596 
20597   verifyFormat("auto select = [this]() -> const Library::Object &\n"
20598                "{\n"
20599                "  return MyAssignment::SelectFromList(this);\n"
20600                "};\n",
20601                LLVMWithBeforeLambdaBody);
20602 
20603   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
20604                "{\n"
20605                "  return MyAssignment::SelectFromList(this);\n"
20606                "};\n",
20607                LLVMWithBeforeLambdaBody);
20608 
20609   verifyFormat("namespace test {\n"
20610                "class Test {\n"
20611                "public:\n"
20612                "  Test() = default;\n"
20613                "};\n"
20614                "} // namespace test",
20615                LLVMWithBeforeLambdaBody);
20616 
20617   // Lambdas with different indentation styles.
20618   Style = getLLVMStyleWithColumns(100);
20619   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20620             "  return promise.then(\n"
20621             "      [this, &someVariable, someObject = "
20622             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20623             "        return someObject.startAsyncAction().then(\n"
20624             "            [this, &someVariable](AsyncActionResult result) "
20625             "mutable { result.processMore(); });\n"
20626             "      });\n"
20627             "}\n",
20628             format("SomeResult doSomething(SomeObject promise) {\n"
20629                    "  return promise.then([this, &someVariable, someObject = "
20630                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20631                    "    return someObject.startAsyncAction().then([this, "
20632                    "&someVariable](AsyncActionResult result) mutable {\n"
20633                    "      result.processMore();\n"
20634                    "    });\n"
20635                    "  });\n"
20636                    "}\n",
20637                    Style));
20638   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20639   verifyFormat("test() {\n"
20640                "  ([]() -> {\n"
20641                "    int b = 32;\n"
20642                "    return 3;\n"
20643                "  }).foo();\n"
20644                "}",
20645                Style);
20646   verifyFormat("test() {\n"
20647                "  []() -> {\n"
20648                "    int b = 32;\n"
20649                "    return 3;\n"
20650                "  }\n"
20651                "}",
20652                Style);
20653   verifyFormat("std::sort(v.begin(), v.end(),\n"
20654                "          [](const auto &someLongArgumentName, const auto "
20655                "&someOtherLongArgumentName) {\n"
20656                "  return someLongArgumentName.someMemberVariable < "
20657                "someOtherLongArgumentName.someMemberVariable;\n"
20658                "});",
20659                Style);
20660   verifyFormat("test() {\n"
20661                "  (\n"
20662                "      []() -> {\n"
20663                "        int b = 32;\n"
20664                "        return 3;\n"
20665                "      },\n"
20666                "      foo, bar)\n"
20667                "      .foo();\n"
20668                "}",
20669                Style);
20670   verifyFormat("test() {\n"
20671                "  ([]() -> {\n"
20672                "    int b = 32;\n"
20673                "    return 3;\n"
20674                "  })\n"
20675                "      .foo()\n"
20676                "      .bar();\n"
20677                "}",
20678                Style);
20679   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20680             "  return promise.then(\n"
20681             "      [this, &someVariable, someObject = "
20682             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20683             "    return someObject.startAsyncAction().then(\n"
20684             "        [this, &someVariable](AsyncActionResult result) mutable { "
20685             "result.processMore(); });\n"
20686             "  });\n"
20687             "}\n",
20688             format("SomeResult doSomething(SomeObject promise) {\n"
20689                    "  return promise.then([this, &someVariable, someObject = "
20690                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20691                    "    return someObject.startAsyncAction().then([this, "
20692                    "&someVariable](AsyncActionResult result) mutable {\n"
20693                    "      result.processMore();\n"
20694                    "    });\n"
20695                    "  });\n"
20696                    "}\n",
20697                    Style));
20698   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20699             "  return promise.then([this, &someVariable] {\n"
20700             "    return someObject.startAsyncAction().then(\n"
20701             "        [this, &someVariable](AsyncActionResult result) mutable { "
20702             "result.processMore(); });\n"
20703             "  });\n"
20704             "}\n",
20705             format("SomeResult doSomething(SomeObject promise) {\n"
20706                    "  return promise.then([this, &someVariable] {\n"
20707                    "    return someObject.startAsyncAction().then([this, "
20708                    "&someVariable](AsyncActionResult result) mutable {\n"
20709                    "      result.processMore();\n"
20710                    "    });\n"
20711                    "  });\n"
20712                    "}\n",
20713                    Style));
20714   Style = getGoogleStyle();
20715   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20716   EXPECT_EQ("#define A                                       \\\n"
20717             "  [] {                                          \\\n"
20718             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
20719             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
20720             "      }",
20721             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
20722                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
20723                    Style));
20724   // TODO: The current formatting has a minor issue that's not worth fixing
20725   // right now whereby the closing brace is indented relative to the signature
20726   // instead of being aligned. This only happens with macros.
20727 }
20728 
20729 TEST_F(FormatTest, LambdaWithLineComments) {
20730   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20731   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20732   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20733   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20734       FormatStyle::ShortLambdaStyle::SLS_All;
20735 
20736   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
20737   verifyFormat("auto k = []() // comment\n"
20738                "{ return; }",
20739                LLVMWithBeforeLambdaBody);
20740   verifyFormat("auto k = []() /* comment */ { return; }",
20741                LLVMWithBeforeLambdaBody);
20742   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
20743                LLVMWithBeforeLambdaBody);
20744   verifyFormat("auto k = []() // X\n"
20745                "{ return; }",
20746                LLVMWithBeforeLambdaBody);
20747   verifyFormat(
20748       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
20749       "{ return; }",
20750       LLVMWithBeforeLambdaBody);
20751 }
20752 
20753 TEST_F(FormatTest, EmptyLinesInLambdas) {
20754   verifyFormat("auto lambda = []() {\n"
20755                "  x(); //\n"
20756                "};",
20757                "auto lambda = []() {\n"
20758                "\n"
20759                "  x(); //\n"
20760                "\n"
20761                "};");
20762 }
20763 
20764 TEST_F(FormatTest, FormatsBlocks) {
20765   FormatStyle ShortBlocks = getLLVMStyle();
20766   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
20767   verifyFormat("int (^Block)(int, int);", ShortBlocks);
20768   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
20769   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
20770   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
20771   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
20772   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
20773 
20774   verifyFormat("foo(^{ bar(); });", ShortBlocks);
20775   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
20776   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
20777 
20778   verifyFormat("[operation setCompletionBlock:^{\n"
20779                "  [self onOperationDone];\n"
20780                "}];");
20781   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
20782                "  [self onOperationDone];\n"
20783                "}]};");
20784   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
20785                "  f();\n"
20786                "}];");
20787   verifyFormat("int a = [operation block:^int(int *i) {\n"
20788                "  return 1;\n"
20789                "}];");
20790   verifyFormat("[myObject doSomethingWith:arg1\n"
20791                "                      aaa:^int(int *a) {\n"
20792                "                        return 1;\n"
20793                "                      }\n"
20794                "                      bbb:f(a * bbbbbbbb)];");
20795 
20796   verifyFormat("[operation setCompletionBlock:^{\n"
20797                "  [self.delegate newDataAvailable];\n"
20798                "}];",
20799                getLLVMStyleWithColumns(60));
20800   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
20801                "  NSString *path = [self sessionFilePath];\n"
20802                "  if (path) {\n"
20803                "    // ...\n"
20804                "  }\n"
20805                "});");
20806   verifyFormat("[[SessionService sharedService]\n"
20807                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20808                "      if (window) {\n"
20809                "        [self windowDidLoad:window];\n"
20810                "      } else {\n"
20811                "        [self errorLoadingWindow];\n"
20812                "      }\n"
20813                "    }];");
20814   verifyFormat("void (^largeBlock)(void) = ^{\n"
20815                "  // ...\n"
20816                "};\n",
20817                getLLVMStyleWithColumns(40));
20818   verifyFormat("[[SessionService sharedService]\n"
20819                "    loadWindowWithCompletionBlock: //\n"
20820                "        ^(SessionWindow *window) {\n"
20821                "          if (window) {\n"
20822                "            [self windowDidLoad:window];\n"
20823                "          } else {\n"
20824                "            [self errorLoadingWindow];\n"
20825                "          }\n"
20826                "        }];",
20827                getLLVMStyleWithColumns(60));
20828   verifyFormat("[myObject doSomethingWith:arg1\n"
20829                "    firstBlock:^(Foo *a) {\n"
20830                "      // ...\n"
20831                "      int i;\n"
20832                "    }\n"
20833                "    secondBlock:^(Bar *b) {\n"
20834                "      // ...\n"
20835                "      int i;\n"
20836                "    }\n"
20837                "    thirdBlock:^Foo(Bar *b) {\n"
20838                "      // ...\n"
20839                "      int i;\n"
20840                "    }];");
20841   verifyFormat("[myObject doSomethingWith:arg1\n"
20842                "               firstBlock:-1\n"
20843                "              secondBlock:^(Bar *b) {\n"
20844                "                // ...\n"
20845                "                int i;\n"
20846                "              }];");
20847 
20848   verifyFormat("f(^{\n"
20849                "  @autoreleasepool {\n"
20850                "    if (a) {\n"
20851                "      g();\n"
20852                "    }\n"
20853                "  }\n"
20854                "});");
20855   verifyFormat("Block b = ^int *(A *a, B *b) {}");
20856   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
20857                "};");
20858 
20859   FormatStyle FourIndent = getLLVMStyle();
20860   FourIndent.ObjCBlockIndentWidth = 4;
20861   verifyFormat("[operation setCompletionBlock:^{\n"
20862                "    [self onOperationDone];\n"
20863                "}];",
20864                FourIndent);
20865 }
20866 
20867 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
20868   FormatStyle ZeroColumn = getLLVMStyle();
20869   ZeroColumn.ColumnLimit = 0;
20870 
20871   verifyFormat("[[SessionService sharedService] "
20872                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20873                "  if (window) {\n"
20874                "    [self windowDidLoad:window];\n"
20875                "  } else {\n"
20876                "    [self errorLoadingWindow];\n"
20877                "  }\n"
20878                "}];",
20879                ZeroColumn);
20880   EXPECT_EQ("[[SessionService sharedService]\n"
20881             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20882             "      if (window) {\n"
20883             "        [self windowDidLoad:window];\n"
20884             "      } else {\n"
20885             "        [self errorLoadingWindow];\n"
20886             "      }\n"
20887             "    }];",
20888             format("[[SessionService sharedService]\n"
20889                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20890                    "                if (window) {\n"
20891                    "    [self windowDidLoad:window];\n"
20892                    "  } else {\n"
20893                    "    [self errorLoadingWindow];\n"
20894                    "  }\n"
20895                    "}];",
20896                    ZeroColumn));
20897   verifyFormat("[myObject doSomethingWith:arg1\n"
20898                "    firstBlock:^(Foo *a) {\n"
20899                "      // ...\n"
20900                "      int i;\n"
20901                "    }\n"
20902                "    secondBlock:^(Bar *b) {\n"
20903                "      // ...\n"
20904                "      int i;\n"
20905                "    }\n"
20906                "    thirdBlock:^Foo(Bar *b) {\n"
20907                "      // ...\n"
20908                "      int i;\n"
20909                "    }];",
20910                ZeroColumn);
20911   verifyFormat("f(^{\n"
20912                "  @autoreleasepool {\n"
20913                "    if (a) {\n"
20914                "      g();\n"
20915                "    }\n"
20916                "  }\n"
20917                "});",
20918                ZeroColumn);
20919   verifyFormat("void (^largeBlock)(void) = ^{\n"
20920                "  // ...\n"
20921                "};",
20922                ZeroColumn);
20923 
20924   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
20925   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
20926             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
20927   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
20928   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
20929             "  int i;\n"
20930             "};",
20931             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
20932 }
20933 
20934 TEST_F(FormatTest, SupportsCRLF) {
20935   EXPECT_EQ("int a;\r\n"
20936             "int b;\r\n"
20937             "int c;\r\n",
20938             format("int a;\r\n"
20939                    "  int b;\r\n"
20940                    "    int c;\r\n",
20941                    getLLVMStyle()));
20942   EXPECT_EQ("int a;\r\n"
20943             "int b;\r\n"
20944             "int c;\r\n",
20945             format("int a;\r\n"
20946                    "  int b;\n"
20947                    "    int c;\r\n",
20948                    getLLVMStyle()));
20949   EXPECT_EQ("int a;\n"
20950             "int b;\n"
20951             "int c;\n",
20952             format("int a;\r\n"
20953                    "  int b;\n"
20954                    "    int c;\n",
20955                    getLLVMStyle()));
20956   EXPECT_EQ("\"aaaaaaa \"\r\n"
20957             "\"bbbbbbb\";\r\n",
20958             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
20959   EXPECT_EQ("#define A \\\r\n"
20960             "  b;      \\\r\n"
20961             "  c;      \\\r\n"
20962             "  d;\r\n",
20963             format("#define A \\\r\n"
20964                    "  b; \\\r\n"
20965                    "  c; d; \r\n",
20966                    getGoogleStyle()));
20967 
20968   EXPECT_EQ("/*\r\n"
20969             "multi line block comments\r\n"
20970             "should not introduce\r\n"
20971             "an extra carriage return\r\n"
20972             "*/\r\n",
20973             format("/*\r\n"
20974                    "multi line block comments\r\n"
20975                    "should not introduce\r\n"
20976                    "an extra carriage return\r\n"
20977                    "*/\r\n"));
20978   EXPECT_EQ("/*\r\n"
20979             "\r\n"
20980             "*/",
20981             format("/*\r\n"
20982                    "    \r\r\r\n"
20983                    "*/"));
20984 
20985   FormatStyle style = getLLVMStyle();
20986 
20987   style.DeriveLineEnding = true;
20988   style.UseCRLF = false;
20989   EXPECT_EQ("union FooBarBazQux {\n"
20990             "  int foo;\n"
20991             "  int bar;\n"
20992             "  int baz;\n"
20993             "};",
20994             format("union FooBarBazQux {\r\n"
20995                    "  int foo;\n"
20996                    "  int bar;\r\n"
20997                    "  int baz;\n"
20998                    "};",
20999                    style));
21000   style.UseCRLF = true;
21001   EXPECT_EQ("union FooBarBazQux {\r\n"
21002             "  int foo;\r\n"
21003             "  int bar;\r\n"
21004             "  int baz;\r\n"
21005             "};",
21006             format("union FooBarBazQux {\r\n"
21007                    "  int foo;\n"
21008                    "  int bar;\r\n"
21009                    "  int baz;\n"
21010                    "};",
21011                    style));
21012 
21013   style.DeriveLineEnding = false;
21014   style.UseCRLF = false;
21015   EXPECT_EQ("union FooBarBazQux {\n"
21016             "  int foo;\n"
21017             "  int bar;\n"
21018             "  int baz;\n"
21019             "  int qux;\n"
21020             "};",
21021             format("union FooBarBazQux {\r\n"
21022                    "  int foo;\n"
21023                    "  int bar;\r\n"
21024                    "  int baz;\n"
21025                    "  int qux;\r\n"
21026                    "};",
21027                    style));
21028   style.UseCRLF = true;
21029   EXPECT_EQ("union FooBarBazQux {\r\n"
21030             "  int foo;\r\n"
21031             "  int bar;\r\n"
21032             "  int baz;\r\n"
21033             "  int qux;\r\n"
21034             "};",
21035             format("union FooBarBazQux {\r\n"
21036                    "  int foo;\n"
21037                    "  int bar;\r\n"
21038                    "  int baz;\n"
21039                    "  int qux;\n"
21040                    "};",
21041                    style));
21042 
21043   style.DeriveLineEnding = true;
21044   style.UseCRLF = false;
21045   EXPECT_EQ("union FooBarBazQux {\r\n"
21046             "  int foo;\r\n"
21047             "  int bar;\r\n"
21048             "  int baz;\r\n"
21049             "  int qux;\r\n"
21050             "};",
21051             format("union FooBarBazQux {\r\n"
21052                    "  int foo;\n"
21053                    "  int bar;\r\n"
21054                    "  int baz;\n"
21055                    "  int qux;\r\n"
21056                    "};",
21057                    style));
21058   style.UseCRLF = true;
21059   EXPECT_EQ("union FooBarBazQux {\n"
21060             "  int foo;\n"
21061             "  int bar;\n"
21062             "  int baz;\n"
21063             "  int qux;\n"
21064             "};",
21065             format("union FooBarBazQux {\r\n"
21066                    "  int foo;\n"
21067                    "  int bar;\r\n"
21068                    "  int baz;\n"
21069                    "  int qux;\n"
21070                    "};",
21071                    style));
21072 }
21073 
21074 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
21075   verifyFormat("MY_CLASS(C) {\n"
21076                "  int i;\n"
21077                "  int j;\n"
21078                "};");
21079 }
21080 
21081 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
21082   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
21083   TwoIndent.ContinuationIndentWidth = 2;
21084 
21085   EXPECT_EQ("int i =\n"
21086             "  longFunction(\n"
21087             "    arg);",
21088             format("int i = longFunction(arg);", TwoIndent));
21089 
21090   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
21091   SixIndent.ContinuationIndentWidth = 6;
21092 
21093   EXPECT_EQ("int i =\n"
21094             "      longFunction(\n"
21095             "            arg);",
21096             format("int i = longFunction(arg);", SixIndent));
21097 }
21098 
21099 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
21100   FormatStyle Style = getLLVMStyle();
21101   verifyFormat("int Foo::getter(\n"
21102                "    //\n"
21103                ") const {\n"
21104                "  return foo;\n"
21105                "}",
21106                Style);
21107   verifyFormat("void Foo::setter(\n"
21108                "    //\n"
21109                ") {\n"
21110                "  foo = 1;\n"
21111                "}",
21112                Style);
21113 }
21114 
21115 TEST_F(FormatTest, SpacesInAngles) {
21116   FormatStyle Spaces = getLLVMStyle();
21117   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21118 
21119   verifyFormat("vector< ::std::string > x1;", Spaces);
21120   verifyFormat("Foo< int, Bar > x2;", Spaces);
21121   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
21122 
21123   verifyFormat("static_cast< int >(arg);", Spaces);
21124   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
21125   verifyFormat("f< int, float >();", Spaces);
21126   verifyFormat("template <> g() {}", Spaces);
21127   verifyFormat("template < std::vector< int > > f() {}", Spaces);
21128   verifyFormat("std::function< void(int, int) > fct;", Spaces);
21129   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
21130                Spaces);
21131 
21132   Spaces.Standard = FormatStyle::LS_Cpp03;
21133   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21134   verifyFormat("A< A< int > >();", Spaces);
21135 
21136   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
21137   verifyFormat("A<A<int> >();", Spaces);
21138 
21139   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
21140   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
21141                Spaces);
21142   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
21143                Spaces);
21144 
21145   verifyFormat("A<A<int> >();", Spaces);
21146   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
21147   verifyFormat("A< A< int > >();", Spaces);
21148 
21149   Spaces.Standard = FormatStyle::LS_Cpp11;
21150   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21151   verifyFormat("A< A< int > >();", Spaces);
21152 
21153   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
21154   verifyFormat("vector<::std::string> x4;", Spaces);
21155   verifyFormat("vector<int> x5;", Spaces);
21156   verifyFormat("Foo<int, Bar> x6;", Spaces);
21157   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
21158 
21159   verifyFormat("A<A<int>>();", Spaces);
21160 
21161   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
21162   verifyFormat("vector<::std::string> x4;", Spaces);
21163   verifyFormat("vector< ::std::string > x4;", Spaces);
21164   verifyFormat("vector<int> x5;", Spaces);
21165   verifyFormat("vector< int > x5;", Spaces);
21166   verifyFormat("Foo<int, Bar> x6;", Spaces);
21167   verifyFormat("Foo< int, Bar > x6;", Spaces);
21168   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
21169   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
21170 
21171   verifyFormat("A<A<int>>();", Spaces);
21172   verifyFormat("A< A< int > >();", Spaces);
21173   verifyFormat("A<A<int > >();", Spaces);
21174   verifyFormat("A< A< int>>();", Spaces);
21175 }
21176 
21177 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
21178   FormatStyle Style = getLLVMStyle();
21179   Style.SpaceAfterTemplateKeyword = false;
21180   verifyFormat("template<int> void foo();", Style);
21181 }
21182 
21183 TEST_F(FormatTest, TripleAngleBrackets) {
21184   verifyFormat("f<<<1, 1>>>();");
21185   verifyFormat("f<<<1, 1, 1, s>>>();");
21186   verifyFormat("f<<<a, b, c, d>>>();");
21187   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
21188   verifyFormat("f<param><<<1, 1>>>();");
21189   verifyFormat("f<1><<<1, 1>>>();");
21190   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
21191   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21192                "aaaaaaaaaaa<<<\n    1, 1>>>();");
21193   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
21194                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
21195 }
21196 
21197 TEST_F(FormatTest, MergeLessLessAtEnd) {
21198   verifyFormat("<<");
21199   EXPECT_EQ("< < <", format("\\\n<<<"));
21200   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21201                "aaallvm::outs() <<");
21202   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21203                "aaaallvm::outs()\n    <<");
21204 }
21205 
21206 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
21207   std::string code = "#if A\n"
21208                      "#if B\n"
21209                      "a.\n"
21210                      "#endif\n"
21211                      "    a = 1;\n"
21212                      "#else\n"
21213                      "#endif\n"
21214                      "#if C\n"
21215                      "#else\n"
21216                      "#endif\n";
21217   EXPECT_EQ(code, format(code));
21218 }
21219 
21220 TEST_F(FormatTest, HandleConflictMarkers) {
21221   // Git/SVN conflict markers.
21222   EXPECT_EQ("int a;\n"
21223             "void f() {\n"
21224             "  callme(some(parameter1,\n"
21225             "<<<<<<< text by the vcs\n"
21226             "              parameter2),\n"
21227             "||||||| text by the vcs\n"
21228             "              parameter2),\n"
21229             "         parameter3,\n"
21230             "======= text by the vcs\n"
21231             "              parameter2, parameter3),\n"
21232             ">>>>>>> text by the vcs\n"
21233             "         otherparameter);\n",
21234             format("int a;\n"
21235                    "void f() {\n"
21236                    "  callme(some(parameter1,\n"
21237                    "<<<<<<< text by the vcs\n"
21238                    "  parameter2),\n"
21239                    "||||||| text by the vcs\n"
21240                    "  parameter2),\n"
21241                    "  parameter3,\n"
21242                    "======= text by the vcs\n"
21243                    "  parameter2,\n"
21244                    "  parameter3),\n"
21245                    ">>>>>>> text by the vcs\n"
21246                    "  otherparameter);\n"));
21247 
21248   // Perforce markers.
21249   EXPECT_EQ("void f() {\n"
21250             "  function(\n"
21251             ">>>> text by the vcs\n"
21252             "      parameter,\n"
21253             "==== text by the vcs\n"
21254             "      parameter,\n"
21255             "==== text by the vcs\n"
21256             "      parameter,\n"
21257             "<<<< text by the vcs\n"
21258             "      parameter);\n",
21259             format("void f() {\n"
21260                    "  function(\n"
21261                    ">>>> text by the vcs\n"
21262                    "  parameter,\n"
21263                    "==== text by the vcs\n"
21264                    "  parameter,\n"
21265                    "==== text by the vcs\n"
21266                    "  parameter,\n"
21267                    "<<<< text by the vcs\n"
21268                    "  parameter);\n"));
21269 
21270   EXPECT_EQ("<<<<<<<\n"
21271             "|||||||\n"
21272             "=======\n"
21273             ">>>>>>>",
21274             format("<<<<<<<\n"
21275                    "|||||||\n"
21276                    "=======\n"
21277                    ">>>>>>>"));
21278 
21279   EXPECT_EQ("<<<<<<<\n"
21280             "|||||||\n"
21281             "int i;\n"
21282             "=======\n"
21283             ">>>>>>>",
21284             format("<<<<<<<\n"
21285                    "|||||||\n"
21286                    "int i;\n"
21287                    "=======\n"
21288                    ">>>>>>>"));
21289 
21290   // FIXME: Handle parsing of macros around conflict markers correctly:
21291   EXPECT_EQ("#define Macro \\\n"
21292             "<<<<<<<\n"
21293             "Something \\\n"
21294             "|||||||\n"
21295             "Else \\\n"
21296             "=======\n"
21297             "Other \\\n"
21298             ">>>>>>>\n"
21299             "    End int i;\n",
21300             format("#define Macro \\\n"
21301                    "<<<<<<<\n"
21302                    "  Something \\\n"
21303                    "|||||||\n"
21304                    "  Else \\\n"
21305                    "=======\n"
21306                    "  Other \\\n"
21307                    ">>>>>>>\n"
21308                    "  End\n"
21309                    "int i;\n"));
21310 
21311   verifyFormat(R"(====
21312 #ifdef A
21313 a
21314 #else
21315 b
21316 #endif
21317 )");
21318 }
21319 
21320 TEST_F(FormatTest, DisableRegions) {
21321   EXPECT_EQ("int i;\n"
21322             "// clang-format off\n"
21323             "  int j;\n"
21324             "// clang-format on\n"
21325             "int k;",
21326             format(" int  i;\n"
21327                    "   // clang-format off\n"
21328                    "  int j;\n"
21329                    " // clang-format on\n"
21330                    "   int   k;"));
21331   EXPECT_EQ("int i;\n"
21332             "/* clang-format off */\n"
21333             "  int j;\n"
21334             "/* clang-format on */\n"
21335             "int k;",
21336             format(" int  i;\n"
21337                    "   /* clang-format off */\n"
21338                    "  int j;\n"
21339                    " /* clang-format on */\n"
21340                    "   int   k;"));
21341 
21342   // Don't reflow comments within disabled regions.
21343   EXPECT_EQ("// clang-format off\n"
21344             "// long long long long long long line\n"
21345             "/* clang-format on */\n"
21346             "/* long long long\n"
21347             " * long long long\n"
21348             " * line */\n"
21349             "int i;\n"
21350             "/* clang-format off */\n"
21351             "/* long long long long long long line */\n",
21352             format("// clang-format off\n"
21353                    "// long long long long long long line\n"
21354                    "/* clang-format on */\n"
21355                    "/* long long long long long long line */\n"
21356                    "int i;\n"
21357                    "/* clang-format off */\n"
21358                    "/* long long long long long long line */\n",
21359                    getLLVMStyleWithColumns(20)));
21360 }
21361 
21362 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
21363   format("? ) =");
21364   verifyNoCrash("#define a\\\n /**/}");
21365 }
21366 
21367 TEST_F(FormatTest, FormatsTableGenCode) {
21368   FormatStyle Style = getLLVMStyle();
21369   Style.Language = FormatStyle::LK_TableGen;
21370   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
21371 }
21372 
21373 TEST_F(FormatTest, ArrayOfTemplates) {
21374   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
21375             format("auto a = new unique_ptr<int > [ 10];"));
21376 
21377   FormatStyle Spaces = getLLVMStyle();
21378   Spaces.SpacesInSquareBrackets = true;
21379   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
21380             format("auto a = new unique_ptr<int > [10];", Spaces));
21381 }
21382 
21383 TEST_F(FormatTest, ArrayAsTemplateType) {
21384   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
21385             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
21386 
21387   FormatStyle Spaces = getLLVMStyle();
21388   Spaces.SpacesInSquareBrackets = true;
21389   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
21390             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
21391 }
21392 
21393 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
21394 
21395 TEST(FormatStyle, GetStyleWithEmptyFileName) {
21396   llvm::vfs::InMemoryFileSystem FS;
21397   auto Style1 = getStyle("file", "", "Google", "", &FS);
21398   ASSERT_TRUE((bool)Style1);
21399   ASSERT_EQ(*Style1, getGoogleStyle());
21400 }
21401 
21402 TEST(FormatStyle, GetStyleOfFile) {
21403   llvm::vfs::InMemoryFileSystem FS;
21404   // Test 1: format file in the same directory.
21405   ASSERT_TRUE(
21406       FS.addFile("/a/.clang-format", 0,
21407                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
21408   ASSERT_TRUE(
21409       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21410   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
21411   ASSERT_TRUE((bool)Style1);
21412   ASSERT_EQ(*Style1, getLLVMStyle());
21413 
21414   // Test 2.1: fallback to default.
21415   ASSERT_TRUE(
21416       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21417   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
21418   ASSERT_TRUE((bool)Style2);
21419   ASSERT_EQ(*Style2, getMozillaStyle());
21420 
21421   // Test 2.2: no format on 'none' fallback style.
21422   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21423   ASSERT_TRUE((bool)Style2);
21424   ASSERT_EQ(*Style2, getNoStyle());
21425 
21426   // Test 2.3: format if config is found with no based style while fallback is
21427   // 'none'.
21428   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
21429                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
21430   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21431   ASSERT_TRUE((bool)Style2);
21432   ASSERT_EQ(*Style2, getLLVMStyle());
21433 
21434   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
21435   Style2 = getStyle("{}", "a.h", "none", "", &FS);
21436   ASSERT_TRUE((bool)Style2);
21437   ASSERT_EQ(*Style2, getLLVMStyle());
21438 
21439   // Test 3: format file in parent directory.
21440   ASSERT_TRUE(
21441       FS.addFile("/c/.clang-format", 0,
21442                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21443   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
21444                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21445   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21446   ASSERT_TRUE((bool)Style3);
21447   ASSERT_EQ(*Style3, getGoogleStyle());
21448 
21449   // Test 4: error on invalid fallback style
21450   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
21451   ASSERT_FALSE((bool)Style4);
21452   llvm::consumeError(Style4.takeError());
21453 
21454   // Test 5: error on invalid yaml on command line
21455   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
21456   ASSERT_FALSE((bool)Style5);
21457   llvm::consumeError(Style5.takeError());
21458 
21459   // Test 6: error on invalid style
21460   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
21461   ASSERT_FALSE((bool)Style6);
21462   llvm::consumeError(Style6.takeError());
21463 
21464   // Test 7: found config file, error on parsing it
21465   ASSERT_TRUE(
21466       FS.addFile("/d/.clang-format", 0,
21467                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
21468                                                   "InvalidKey: InvalidValue")));
21469   ASSERT_TRUE(
21470       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21471   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
21472   ASSERT_FALSE((bool)Style7a);
21473   llvm::consumeError(Style7a.takeError());
21474 
21475   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
21476   ASSERT_TRUE((bool)Style7b);
21477 
21478   // Test 8: inferred per-language defaults apply.
21479   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
21480   ASSERT_TRUE((bool)StyleTd);
21481   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
21482 
21483   // Test 9.1: overwriting a file style, when parent no file exists with no
21484   // fallback style
21485   ASSERT_TRUE(FS.addFile(
21486       "/e/sub/.clang-format", 0,
21487       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
21488                                        "ColumnLimit: 20")));
21489   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
21490                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21491   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21492   ASSERT_TRUE(static_cast<bool>(Style9));
21493   ASSERT_EQ(*Style9, [] {
21494     auto Style = getNoStyle();
21495     Style.ColumnLimit = 20;
21496     return Style;
21497   }());
21498 
21499   // Test 9.2: with LLVM fallback style
21500   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
21501   ASSERT_TRUE(static_cast<bool>(Style9));
21502   ASSERT_EQ(*Style9, [] {
21503     auto Style = getLLVMStyle();
21504     Style.ColumnLimit = 20;
21505     return Style;
21506   }());
21507 
21508   // Test 9.3: with a parent file
21509   ASSERT_TRUE(
21510       FS.addFile("/e/.clang-format", 0,
21511                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
21512                                                   "UseTab: Always")));
21513   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21514   ASSERT_TRUE(static_cast<bool>(Style9));
21515   ASSERT_EQ(*Style9, [] {
21516     auto Style = getGoogleStyle();
21517     Style.ColumnLimit = 20;
21518     Style.UseTab = FormatStyle::UT_Always;
21519     return Style;
21520   }());
21521 
21522   // Test 9.4: propagate more than one level
21523   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
21524                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21525   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
21526                          llvm::MemoryBuffer::getMemBuffer(
21527                              "BasedOnStyle: InheritParentConfig\n"
21528                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
21529   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
21530 
21531   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
21532     auto Style = getGoogleStyle();
21533     Style.ColumnLimit = 20;
21534     Style.UseTab = FormatStyle::UT_Always;
21535     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21536     return Style;
21537   }();
21538 
21539   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21540   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21541   ASSERT_TRUE(static_cast<bool>(Style9));
21542   ASSERT_EQ(*Style9, SubSubStyle);
21543 
21544   // Test 9.5: use InheritParentConfig as style name
21545   Style9 =
21546       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
21547   ASSERT_TRUE(static_cast<bool>(Style9));
21548   ASSERT_EQ(*Style9, SubSubStyle);
21549 
21550   // Test 9.6: use command line style with inheritance
21551   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
21552                     "none", "", &FS);
21553   ASSERT_TRUE(static_cast<bool>(Style9));
21554   ASSERT_EQ(*Style9, SubSubStyle);
21555 
21556   // Test 9.7: use command line style with inheritance and own config
21557   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
21558                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
21559                     "/e/sub/code.cpp", "none", "", &FS);
21560   ASSERT_TRUE(static_cast<bool>(Style9));
21561   ASSERT_EQ(*Style9, SubSubStyle);
21562 
21563   // Test 9.8: use inheritance from a file without BasedOnStyle
21564   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
21565                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
21566   ASSERT_TRUE(
21567       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
21568                  llvm::MemoryBuffer::getMemBuffer(
21569                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
21570   // Make sure we do not use the fallback style
21571   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
21572   ASSERT_TRUE(static_cast<bool>(Style9));
21573   ASSERT_EQ(*Style9, [] {
21574     auto Style = getLLVMStyle();
21575     Style.ColumnLimit = 123;
21576     return Style;
21577   }());
21578 
21579   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
21580   ASSERT_TRUE(static_cast<bool>(Style9));
21581   ASSERT_EQ(*Style9, [] {
21582     auto Style = getLLVMStyle();
21583     Style.ColumnLimit = 123;
21584     Style.IndentWidth = 7;
21585     return Style;
21586   }());
21587 }
21588 
21589 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
21590   // Column limit is 20.
21591   std::string Code = "Type *a =\n"
21592                      "    new Type();\n"
21593                      "g(iiiii, 0, jjjjj,\n"
21594                      "  0, kkkkk, 0, mm);\n"
21595                      "int  bad     = format   ;";
21596   std::string Expected = "auto a = new Type();\n"
21597                          "g(iiiii, nullptr,\n"
21598                          "  jjjjj, nullptr,\n"
21599                          "  kkkkk, nullptr,\n"
21600                          "  mm);\n"
21601                          "int  bad     = format   ;";
21602   FileID ID = Context.createInMemoryFile("format.cpp", Code);
21603   tooling::Replacements Replaces = toReplacements(
21604       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
21605                             "auto "),
21606        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
21607                             "nullptr"),
21608        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
21609                             "nullptr"),
21610        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
21611                             "nullptr")});
21612 
21613   FormatStyle Style = getLLVMStyle();
21614   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
21615   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21616   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21617       << llvm::toString(FormattedReplaces.takeError()) << "\n";
21618   auto Result = applyAllReplacements(Code, *FormattedReplaces);
21619   EXPECT_TRUE(static_cast<bool>(Result));
21620   EXPECT_EQ(Expected, *Result);
21621 }
21622 
21623 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
21624   std::string Code = "#include \"a.h\"\n"
21625                      "#include \"c.h\"\n"
21626                      "\n"
21627                      "int main() {\n"
21628                      "  return 0;\n"
21629                      "}";
21630   std::string Expected = "#include \"a.h\"\n"
21631                          "#include \"b.h\"\n"
21632                          "#include \"c.h\"\n"
21633                          "\n"
21634                          "int main() {\n"
21635                          "  return 0;\n"
21636                          "}";
21637   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
21638   tooling::Replacements Replaces = toReplacements(
21639       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
21640                             "#include \"b.h\"\n")});
21641 
21642   FormatStyle Style = getLLVMStyle();
21643   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
21644   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21645   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21646       << llvm::toString(FormattedReplaces.takeError()) << "\n";
21647   auto Result = applyAllReplacements(Code, *FormattedReplaces);
21648   EXPECT_TRUE(static_cast<bool>(Result));
21649   EXPECT_EQ(Expected, *Result);
21650 }
21651 
21652 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
21653   EXPECT_EQ("using std::cin;\n"
21654             "using std::cout;",
21655             format("using std::cout;\n"
21656                    "using std::cin;",
21657                    getGoogleStyle()));
21658 }
21659 
21660 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
21661   FormatStyle Style = getLLVMStyle();
21662   Style.Standard = FormatStyle::LS_Cpp03;
21663   // cpp03 recognize this string as identifier u8 and literal character 'a'
21664   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
21665 }
21666 
21667 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
21668   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
21669   // all modes, including C++11, C++14 and C++17
21670   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
21671 }
21672 
21673 TEST_F(FormatTest, DoNotFormatLikelyXml) {
21674   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
21675   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
21676 }
21677 
21678 TEST_F(FormatTest, StructuredBindings) {
21679   // Structured bindings is a C++17 feature.
21680   // all modes, including C++11, C++14 and C++17
21681   verifyFormat("auto [a, b] = f();");
21682   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
21683   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
21684   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
21685   EXPECT_EQ("auto const volatile [a, b] = f();",
21686             format("auto  const   volatile[a, b] = f();"));
21687   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
21688   EXPECT_EQ("auto &[a, b, c] = f();",
21689             format("auto   &[  a  ,  b,c   ] = f();"));
21690   EXPECT_EQ("auto &&[a, b, c] = f();",
21691             format("auto   &&[  a  ,  b,c   ] = f();"));
21692   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
21693   EXPECT_EQ("auto const volatile &&[a, b] = f();",
21694             format("auto  const  volatile  &&[a, b] = f();"));
21695   EXPECT_EQ("auto const &&[a, b] = f();",
21696             format("auto  const   &&  [a, b] = f();"));
21697   EXPECT_EQ("const auto &[a, b] = f();",
21698             format("const  auto  &  [a, b] = f();"));
21699   EXPECT_EQ("const auto volatile &&[a, b] = f();",
21700             format("const  auto   volatile  &&[a, b] = f();"));
21701   EXPECT_EQ("volatile const auto &&[a, b] = f();",
21702             format("volatile  const  auto   &&[a, b] = f();"));
21703   EXPECT_EQ("const auto &&[a, b] = f();",
21704             format("const  auto  &&  [a, b] = f();"));
21705 
21706   // Make sure we don't mistake structured bindings for lambdas.
21707   FormatStyle PointerMiddle = getLLVMStyle();
21708   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
21709   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
21710   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
21711   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
21712   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
21713   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
21714   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
21715   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
21716   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
21717   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
21718   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
21719   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
21720   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
21721 
21722   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
21723             format("for (const auto   &&   [a, b] : some_range) {\n}"));
21724   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
21725             format("for (const auto   &   [a, b] : some_range) {\n}"));
21726   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
21727             format("for (const auto[a, b] : some_range) {\n}"));
21728   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
21729   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
21730   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
21731   EXPECT_EQ("auto const &[x, y](expr);",
21732             format("auto  const  &  [x,y]  (expr);"));
21733   EXPECT_EQ("auto const &&[x, y](expr);",
21734             format("auto  const  &&  [x,y]  (expr);"));
21735   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
21736   EXPECT_EQ("auto const &[x, y]{expr};",
21737             format("auto  const  &  [x,y]  {expr};"));
21738   EXPECT_EQ("auto const &&[x, y]{expr};",
21739             format("auto  const  &&  [x,y]  {expr};"));
21740 
21741   FormatStyle Spaces = getLLVMStyle();
21742   Spaces.SpacesInSquareBrackets = true;
21743   verifyFormat("auto [ a, b ] = f();", Spaces);
21744   verifyFormat("auto &&[ a, b ] = f();", Spaces);
21745   verifyFormat("auto &[ a, b ] = f();", Spaces);
21746   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
21747   verifyFormat("auto const &[ a, b ] = f();", Spaces);
21748 }
21749 
21750 TEST_F(FormatTest, FileAndCode) {
21751   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
21752   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
21753   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
21754   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
21755   EXPECT_EQ(FormatStyle::LK_ObjC,
21756             guessLanguage("foo.h", "@interface Foo\n@end\n"));
21757   EXPECT_EQ(
21758       FormatStyle::LK_ObjC,
21759       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
21760   EXPECT_EQ(FormatStyle::LK_ObjC,
21761             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
21762   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
21763   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
21764   EXPECT_EQ(FormatStyle::LK_ObjC,
21765             guessLanguage("foo", "@interface Foo\n@end\n"));
21766   EXPECT_EQ(FormatStyle::LK_ObjC,
21767             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
21768   EXPECT_EQ(
21769       FormatStyle::LK_ObjC,
21770       guessLanguage("foo.h",
21771                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
21772   EXPECT_EQ(
21773       FormatStyle::LK_Cpp,
21774       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
21775 }
21776 
21777 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
21778   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
21779   EXPECT_EQ(FormatStyle::LK_ObjC,
21780             guessLanguage("foo.h", "array[[calculator getIndex]];"));
21781   EXPECT_EQ(FormatStyle::LK_Cpp,
21782             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
21783   EXPECT_EQ(
21784       FormatStyle::LK_Cpp,
21785       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
21786   EXPECT_EQ(FormatStyle::LK_ObjC,
21787             guessLanguage("foo.h", "[[noreturn foo] bar];"));
21788   EXPECT_EQ(FormatStyle::LK_Cpp,
21789             guessLanguage("foo.h", "[[clang::fallthrough]];"));
21790   EXPECT_EQ(FormatStyle::LK_ObjC,
21791             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
21792   EXPECT_EQ(FormatStyle::LK_Cpp,
21793             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
21794   EXPECT_EQ(FormatStyle::LK_Cpp,
21795             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
21796   EXPECT_EQ(FormatStyle::LK_ObjC,
21797             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
21798   EXPECT_EQ(FormatStyle::LK_Cpp,
21799             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
21800   EXPECT_EQ(
21801       FormatStyle::LK_Cpp,
21802       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
21803   EXPECT_EQ(
21804       FormatStyle::LK_Cpp,
21805       guessLanguage("foo.h",
21806                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
21807   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
21808 }
21809 
21810 TEST_F(FormatTest, GuessLanguageWithCaret) {
21811   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
21812   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
21813   EXPECT_EQ(FormatStyle::LK_ObjC,
21814             guessLanguage("foo.h", "int(^)(char, float);"));
21815   EXPECT_EQ(FormatStyle::LK_ObjC,
21816             guessLanguage("foo.h", "int(^foo)(char, float);"));
21817   EXPECT_EQ(FormatStyle::LK_ObjC,
21818             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
21819   EXPECT_EQ(FormatStyle::LK_ObjC,
21820             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
21821   EXPECT_EQ(
21822       FormatStyle::LK_ObjC,
21823       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
21824 }
21825 
21826 TEST_F(FormatTest, GuessLanguageWithPragmas) {
21827   EXPECT_EQ(FormatStyle::LK_Cpp,
21828             guessLanguage("foo.h", "__pragma(warning(disable:))"));
21829   EXPECT_EQ(FormatStyle::LK_Cpp,
21830             guessLanguage("foo.h", "#pragma(warning(disable:))"));
21831   EXPECT_EQ(FormatStyle::LK_Cpp,
21832             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
21833 }
21834 
21835 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
21836   // ASM symbolic names are identifiers that must be surrounded by [] without
21837   // space in between:
21838   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
21839 
21840   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
21841   verifyFormat(R"(//
21842 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
21843 )");
21844 
21845   // A list of several ASM symbolic names.
21846   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
21847 
21848   // ASM symbolic names in inline ASM with inputs and outputs.
21849   verifyFormat(R"(//
21850 asm("cmoveq %1, %2, %[result]"
21851     : [result] "=r"(result)
21852     : "r"(test), "r"(new), "[result]"(old));
21853 )");
21854 
21855   // ASM symbolic names in inline ASM with no outputs.
21856   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
21857 }
21858 
21859 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
21860   EXPECT_EQ(FormatStyle::LK_Cpp,
21861             guessLanguage("foo.h", "void f() {\n"
21862                                    "  asm (\"mov %[e], %[d]\"\n"
21863                                    "     : [d] \"=rm\" (d)\n"
21864                                    "       [e] \"rm\" (*e));\n"
21865                                    "}"));
21866   EXPECT_EQ(FormatStyle::LK_Cpp,
21867             guessLanguage("foo.h", "void f() {\n"
21868                                    "  _asm (\"mov %[e], %[d]\"\n"
21869                                    "     : [d] \"=rm\" (d)\n"
21870                                    "       [e] \"rm\" (*e));\n"
21871                                    "}"));
21872   EXPECT_EQ(FormatStyle::LK_Cpp,
21873             guessLanguage("foo.h", "void f() {\n"
21874                                    "  __asm (\"mov %[e], %[d]\"\n"
21875                                    "     : [d] \"=rm\" (d)\n"
21876                                    "       [e] \"rm\" (*e));\n"
21877                                    "}"));
21878   EXPECT_EQ(FormatStyle::LK_Cpp,
21879             guessLanguage("foo.h", "void f() {\n"
21880                                    "  __asm__ (\"mov %[e], %[d]\"\n"
21881                                    "     : [d] \"=rm\" (d)\n"
21882                                    "       [e] \"rm\" (*e));\n"
21883                                    "}"));
21884   EXPECT_EQ(FormatStyle::LK_Cpp,
21885             guessLanguage("foo.h", "void f() {\n"
21886                                    "  asm (\"mov %[e], %[d]\"\n"
21887                                    "     : [d] \"=rm\" (d),\n"
21888                                    "       [e] \"rm\" (*e));\n"
21889                                    "}"));
21890   EXPECT_EQ(FormatStyle::LK_Cpp,
21891             guessLanguage("foo.h", "void f() {\n"
21892                                    "  asm volatile (\"mov %[e], %[d]\"\n"
21893                                    "     : [d] \"=rm\" (d)\n"
21894                                    "       [e] \"rm\" (*e));\n"
21895                                    "}"));
21896 }
21897 
21898 TEST_F(FormatTest, GuessLanguageWithChildLines) {
21899   EXPECT_EQ(FormatStyle::LK_Cpp,
21900             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
21901   EXPECT_EQ(FormatStyle::LK_ObjC,
21902             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
21903   EXPECT_EQ(
21904       FormatStyle::LK_Cpp,
21905       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
21906   EXPECT_EQ(
21907       FormatStyle::LK_ObjC,
21908       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
21909 }
21910 
21911 TEST_F(FormatTest, TypenameMacros) {
21912   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
21913 
21914   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
21915   FormatStyle Google = getGoogleStyleWithColumns(0);
21916   Google.TypenameMacros = TypenameMacros;
21917   verifyFormat("struct foo {\n"
21918                "  int bar;\n"
21919                "  TAILQ_ENTRY(a) bleh;\n"
21920                "};",
21921                Google);
21922 
21923   FormatStyle Macros = getLLVMStyle();
21924   Macros.TypenameMacros = TypenameMacros;
21925 
21926   verifyFormat("STACK_OF(int) a;", Macros);
21927   verifyFormat("STACK_OF(int) *a;", Macros);
21928   verifyFormat("STACK_OF(int const *) *a;", Macros);
21929   verifyFormat("STACK_OF(int *const) *a;", Macros);
21930   verifyFormat("STACK_OF(int, string) a;", Macros);
21931   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
21932   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
21933   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
21934   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
21935   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
21936   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
21937 
21938   Macros.PointerAlignment = FormatStyle::PAS_Left;
21939   verifyFormat("STACK_OF(int)* a;", Macros);
21940   verifyFormat("STACK_OF(int*)* a;", Macros);
21941   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
21942   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
21943   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
21944 }
21945 
21946 TEST_F(FormatTest, AtomicQualifier) {
21947   // Check that we treate _Atomic as a type and not a function call
21948   FormatStyle Google = getGoogleStyleWithColumns(0);
21949   verifyFormat("struct foo {\n"
21950                "  int a1;\n"
21951                "  _Atomic(a) a2;\n"
21952                "  _Atomic(_Atomic(int) *const) a3;\n"
21953                "};",
21954                Google);
21955   verifyFormat("_Atomic(uint64_t) a;");
21956   verifyFormat("_Atomic(uint64_t) *a;");
21957   verifyFormat("_Atomic(uint64_t const *) *a;");
21958   verifyFormat("_Atomic(uint64_t *const) *a;");
21959   verifyFormat("_Atomic(const uint64_t *) *a;");
21960   verifyFormat("_Atomic(uint64_t) a;");
21961   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
21962   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
21963   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
21964   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
21965 
21966   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
21967   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
21968   FormatStyle Style = getLLVMStyle();
21969   Style.PointerAlignment = FormatStyle::PAS_Left;
21970   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
21971   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
21972   verifyFormat("_Atomic(int)* a;", Style);
21973   verifyFormat("_Atomic(int*)* a;", Style);
21974   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
21975 
21976   Style.SpacesInCStyleCastParentheses = true;
21977   Style.SpacesInParentheses = false;
21978   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
21979   Style.SpacesInCStyleCastParentheses = false;
21980   Style.SpacesInParentheses = true;
21981   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
21982   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
21983 }
21984 
21985 TEST_F(FormatTest, AmbersandInLamda) {
21986   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
21987   FormatStyle AlignStyle = getLLVMStyle();
21988   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
21989   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
21990   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
21991   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
21992 }
21993 
21994 TEST_F(FormatTest, SpacesInConditionalStatement) {
21995   FormatStyle Spaces = getLLVMStyle();
21996   Spaces.IfMacros.clear();
21997   Spaces.IfMacros.push_back("MYIF");
21998   Spaces.SpacesInConditionalStatement = true;
21999   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
22000   verifyFormat("if ( !a )\n  return;", Spaces);
22001   verifyFormat("if ( a )\n  return;", Spaces);
22002   verifyFormat("if constexpr ( a )\n  return;", Spaces);
22003   verifyFormat("MYIF ( a )\n  return;", Spaces);
22004   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
22005   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
22006   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
22007   verifyFormat("while ( a )\n  return;", Spaces);
22008   verifyFormat("while ( (a && b) )\n  return;", Spaces);
22009   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
22010   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
22011   // Check that space on the left of "::" is inserted as expected at beginning
22012   // of condition.
22013   verifyFormat("while ( ::func() )\n  return;", Spaces);
22014 
22015   // Check impact of ControlStatementsExceptControlMacros is honored.
22016   Spaces.SpaceBeforeParens =
22017       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
22018   verifyFormat("MYIF( a )\n  return;", Spaces);
22019   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
22020   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
22021 }
22022 
22023 TEST_F(FormatTest, AlternativeOperators) {
22024   // Test case for ensuring alternate operators are not
22025   // combined with their right most neighbour.
22026   verifyFormat("int a and b;");
22027   verifyFormat("int a and_eq b;");
22028   verifyFormat("int a bitand b;");
22029   verifyFormat("int a bitor b;");
22030   verifyFormat("int a compl b;");
22031   verifyFormat("int a not b;");
22032   verifyFormat("int a not_eq b;");
22033   verifyFormat("int a or b;");
22034   verifyFormat("int a xor b;");
22035   verifyFormat("int a xor_eq b;");
22036   verifyFormat("return this not_eq bitand other;");
22037   verifyFormat("bool operator not_eq(const X bitand other)");
22038 
22039   verifyFormat("int a and 5;");
22040   verifyFormat("int a and_eq 5;");
22041   verifyFormat("int a bitand 5;");
22042   verifyFormat("int a bitor 5;");
22043   verifyFormat("int a compl 5;");
22044   verifyFormat("int a not 5;");
22045   verifyFormat("int a not_eq 5;");
22046   verifyFormat("int a or 5;");
22047   verifyFormat("int a xor 5;");
22048   verifyFormat("int a xor_eq 5;");
22049 
22050   verifyFormat("int a compl(5);");
22051   verifyFormat("int a not(5);");
22052 
22053   /* FIXME handle alternate tokens
22054    * https://en.cppreference.com/w/cpp/language/operator_alternative
22055   // alternative tokens
22056   verifyFormat("compl foo();");     //  ~foo();
22057   verifyFormat("foo() <%%>;");      // foo();
22058   verifyFormat("void foo() <%%>;"); // void foo(){}
22059   verifyFormat("int a <:1:>;");     // int a[1];[
22060   verifyFormat("%:define ABC abc"); // #define ABC abc
22061   verifyFormat("%:%:");             // ##
22062   */
22063 }
22064 
22065 TEST_F(FormatTest, STLWhileNotDefineChed) {
22066   verifyFormat("#if defined(while)\n"
22067                "#define while EMIT WARNING C4005\n"
22068                "#endif // while");
22069 }
22070 
22071 TEST_F(FormatTest, OperatorSpacing) {
22072   FormatStyle Style = getLLVMStyle();
22073   Style.PointerAlignment = FormatStyle::PAS_Right;
22074   verifyFormat("Foo::operator*();", Style);
22075   verifyFormat("Foo::operator void *();", Style);
22076   verifyFormat("Foo::operator void **();", Style);
22077   verifyFormat("Foo::operator void *&();", Style);
22078   verifyFormat("Foo::operator void *&&();", Style);
22079   verifyFormat("Foo::operator void const *();", Style);
22080   verifyFormat("Foo::operator void const **();", Style);
22081   verifyFormat("Foo::operator void const *&();", Style);
22082   verifyFormat("Foo::operator void const *&&();", Style);
22083   verifyFormat("Foo::operator()(void *);", Style);
22084   verifyFormat("Foo::operator*(void *);", Style);
22085   verifyFormat("Foo::operator*();", Style);
22086   verifyFormat("Foo::operator**();", Style);
22087   verifyFormat("Foo::operator&();", Style);
22088   verifyFormat("Foo::operator<int> *();", Style);
22089   verifyFormat("Foo::operator<Foo> *();", Style);
22090   verifyFormat("Foo::operator<int> **();", Style);
22091   verifyFormat("Foo::operator<Foo> **();", Style);
22092   verifyFormat("Foo::operator<int> &();", Style);
22093   verifyFormat("Foo::operator<Foo> &();", Style);
22094   verifyFormat("Foo::operator<int> &&();", Style);
22095   verifyFormat("Foo::operator<Foo> &&();", Style);
22096   verifyFormat("Foo::operator<int> *&();", Style);
22097   verifyFormat("Foo::operator<Foo> *&();", Style);
22098   verifyFormat("Foo::operator<int> *&&();", Style);
22099   verifyFormat("Foo::operator<Foo> *&&();", Style);
22100   verifyFormat("operator*(int (*)(), class Foo);", Style);
22101 
22102   verifyFormat("Foo::operator&();", Style);
22103   verifyFormat("Foo::operator void &();", Style);
22104   verifyFormat("Foo::operator void const &();", Style);
22105   verifyFormat("Foo::operator()(void &);", Style);
22106   verifyFormat("Foo::operator&(void &);", Style);
22107   verifyFormat("Foo::operator&();", Style);
22108   verifyFormat("operator&(int (&)(), class Foo);", Style);
22109   verifyFormat("operator&&(int (&)(), class Foo);", Style);
22110 
22111   verifyFormat("Foo::operator&&();", Style);
22112   verifyFormat("Foo::operator**();", Style);
22113   verifyFormat("Foo::operator void &&();", Style);
22114   verifyFormat("Foo::operator void const &&();", Style);
22115   verifyFormat("Foo::operator()(void &&);", Style);
22116   verifyFormat("Foo::operator&&(void &&);", Style);
22117   verifyFormat("Foo::operator&&();", Style);
22118   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22119   verifyFormat("operator const nsTArrayRight<E> &()", Style);
22120   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
22121                Style);
22122   verifyFormat("operator void **()", Style);
22123   verifyFormat("operator const FooRight<Object> &()", Style);
22124   verifyFormat("operator const FooRight<Object> *()", Style);
22125   verifyFormat("operator const FooRight<Object> **()", Style);
22126   verifyFormat("operator const FooRight<Object> *&()", Style);
22127   verifyFormat("operator const FooRight<Object> *&&()", Style);
22128 
22129   Style.PointerAlignment = FormatStyle::PAS_Left;
22130   verifyFormat("Foo::operator*();", Style);
22131   verifyFormat("Foo::operator**();", Style);
22132   verifyFormat("Foo::operator void*();", Style);
22133   verifyFormat("Foo::operator void**();", Style);
22134   verifyFormat("Foo::operator void*&();", Style);
22135   verifyFormat("Foo::operator void*&&();", Style);
22136   verifyFormat("Foo::operator void const*();", Style);
22137   verifyFormat("Foo::operator void const**();", Style);
22138   verifyFormat("Foo::operator void const*&();", Style);
22139   verifyFormat("Foo::operator void const*&&();", Style);
22140   verifyFormat("Foo::operator/*comment*/ void*();", Style);
22141   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
22142   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
22143   verifyFormat("Foo::operator()(void*);", Style);
22144   verifyFormat("Foo::operator*(void*);", Style);
22145   verifyFormat("Foo::operator*();", Style);
22146   verifyFormat("Foo::operator<int>*();", Style);
22147   verifyFormat("Foo::operator<Foo>*();", Style);
22148   verifyFormat("Foo::operator<int>**();", Style);
22149   verifyFormat("Foo::operator<Foo>**();", Style);
22150   verifyFormat("Foo::operator<Foo>*&();", Style);
22151   verifyFormat("Foo::operator<int>&();", Style);
22152   verifyFormat("Foo::operator<Foo>&();", Style);
22153   verifyFormat("Foo::operator<int>&&();", Style);
22154   verifyFormat("Foo::operator<Foo>&&();", Style);
22155   verifyFormat("Foo::operator<int>*&();", Style);
22156   verifyFormat("Foo::operator<Foo>*&();", Style);
22157   verifyFormat("operator*(int (*)(), class Foo);", Style);
22158 
22159   verifyFormat("Foo::operator&();", Style);
22160   verifyFormat("Foo::operator void&();", Style);
22161   verifyFormat("Foo::operator void const&();", Style);
22162   verifyFormat("Foo::operator/*comment*/ void&();", Style);
22163   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
22164   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
22165   verifyFormat("Foo::operator()(void&);", Style);
22166   verifyFormat("Foo::operator&(void&);", Style);
22167   verifyFormat("Foo::operator&();", Style);
22168   verifyFormat("operator&(int (&)(), class Foo);", Style);
22169   verifyFormat("operator&(int (&&)(), class Foo);", Style);
22170   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22171 
22172   verifyFormat("Foo::operator&&();", Style);
22173   verifyFormat("Foo::operator void&&();", Style);
22174   verifyFormat("Foo::operator void const&&();", Style);
22175   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
22176   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
22177   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
22178   verifyFormat("Foo::operator()(void&&);", Style);
22179   verifyFormat("Foo::operator&&(void&&);", Style);
22180   verifyFormat("Foo::operator&&();", Style);
22181   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22182   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
22183   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
22184                Style);
22185   verifyFormat("operator void**()", Style);
22186   verifyFormat("operator const FooLeft<Object>&()", Style);
22187   verifyFormat("operator const FooLeft<Object>*()", Style);
22188   verifyFormat("operator const FooLeft<Object>**()", Style);
22189   verifyFormat("operator const FooLeft<Object>*&()", Style);
22190   verifyFormat("operator const FooLeft<Object>*&&()", Style);
22191 
22192   // PR45107
22193   verifyFormat("operator Vector<String>&();", Style);
22194   verifyFormat("operator const Vector<String>&();", Style);
22195   verifyFormat("operator foo::Bar*();", Style);
22196   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
22197   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
22198                Style);
22199 
22200   Style.PointerAlignment = FormatStyle::PAS_Middle;
22201   verifyFormat("Foo::operator*();", Style);
22202   verifyFormat("Foo::operator void *();", Style);
22203   verifyFormat("Foo::operator()(void *);", Style);
22204   verifyFormat("Foo::operator*(void *);", Style);
22205   verifyFormat("Foo::operator*();", Style);
22206   verifyFormat("operator*(int (*)(), class Foo);", Style);
22207 
22208   verifyFormat("Foo::operator&();", Style);
22209   verifyFormat("Foo::operator void &();", Style);
22210   verifyFormat("Foo::operator void const &();", Style);
22211   verifyFormat("Foo::operator()(void &);", Style);
22212   verifyFormat("Foo::operator&(void &);", Style);
22213   verifyFormat("Foo::operator&();", Style);
22214   verifyFormat("operator&(int (&)(), class Foo);", Style);
22215 
22216   verifyFormat("Foo::operator&&();", Style);
22217   verifyFormat("Foo::operator void &&();", Style);
22218   verifyFormat("Foo::operator void const &&();", Style);
22219   verifyFormat("Foo::operator()(void &&);", Style);
22220   verifyFormat("Foo::operator&&(void &&);", Style);
22221   verifyFormat("Foo::operator&&();", Style);
22222   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22223 }
22224 
22225 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
22226   FormatStyle Style = getLLVMStyle();
22227   // PR46157
22228   verifyFormat("foo(operator+, -42);", Style);
22229   verifyFormat("foo(operator++, -42);", Style);
22230   verifyFormat("foo(operator--, -42);", Style);
22231   verifyFormat("foo(-42, operator--);", Style);
22232   verifyFormat("foo(-42, operator, );", Style);
22233   verifyFormat("foo(operator, , -42);", Style);
22234 }
22235 
22236 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
22237   FormatStyle Style = getLLVMStyle();
22238   Style.WhitespaceSensitiveMacros.push_back("FOO");
22239 
22240   // Don't use the helpers here, since 'mess up' will change the whitespace
22241   // and these are all whitespace sensitive by definition
22242   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
22243             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
22244   EXPECT_EQ(
22245       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
22246       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
22247   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
22248             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
22249   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
22250             "       Still=Intentional);",
22251             format("FOO(String-ized&Messy+But,: :\n"
22252                    "       Still=Intentional);",
22253                    Style));
22254   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
22255   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
22256             "       Still=Intentional);",
22257             format("FOO(String-ized=&Messy+But,: :\n"
22258                    "       Still=Intentional);",
22259                    Style));
22260 
22261   Style.ColumnLimit = 21;
22262   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
22263             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
22264 }
22265 
22266 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
22267   // These tests are not in NamespaceFixer because that doesn't
22268   // test its interaction with line wrapping
22269   FormatStyle Style = getLLVMStyle();
22270   Style.ColumnLimit = 80;
22271   verifyFormat("namespace {\n"
22272                "int i;\n"
22273                "int j;\n"
22274                "} // namespace",
22275                Style);
22276 
22277   verifyFormat("namespace AAA {\n"
22278                "int i;\n"
22279                "int j;\n"
22280                "} // namespace AAA",
22281                Style);
22282 
22283   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
22284             "int i;\n"
22285             "int j;\n"
22286             "} // namespace Averyveryveryverylongnamespace",
22287             format("namespace Averyveryveryverylongnamespace {\n"
22288                    "int i;\n"
22289                    "int j;\n"
22290                    "}",
22291                    Style));
22292 
22293   EXPECT_EQ(
22294       "namespace "
22295       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
22296       "    went::mad::now {\n"
22297       "int i;\n"
22298       "int j;\n"
22299       "} // namespace\n"
22300       "  // "
22301       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
22302       "went::mad::now",
22303       format("namespace "
22304              "would::it::save::you::a::lot::of::time::if_::i::"
22305              "just::gave::up::and_::went::mad::now {\n"
22306              "int i;\n"
22307              "int j;\n"
22308              "}",
22309              Style));
22310 
22311   // This used to duplicate the comment again and again on subsequent runs
22312   EXPECT_EQ(
22313       "namespace "
22314       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
22315       "    went::mad::now {\n"
22316       "int i;\n"
22317       "int j;\n"
22318       "} // namespace\n"
22319       "  // "
22320       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
22321       "went::mad::now",
22322       format("namespace "
22323              "would::it::save::you::a::lot::of::time::if_::i::"
22324              "just::gave::up::and_::went::mad::now {\n"
22325              "int i;\n"
22326              "int j;\n"
22327              "} // namespace\n"
22328              "  // "
22329              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
22330              "and_::went::mad::now",
22331              Style));
22332 }
22333 
22334 TEST_F(FormatTest, LikelyUnlikely) {
22335   FormatStyle Style = getLLVMStyle();
22336 
22337   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22338                "  return 29;\n"
22339                "}",
22340                Style);
22341 
22342   verifyFormat("if (argc > 5) [[likely]] {\n"
22343                "  return 29;\n"
22344                "}",
22345                Style);
22346 
22347   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22348                "  return 29;\n"
22349                "} else [[likely]] {\n"
22350                "  return 42;\n"
22351                "}\n",
22352                Style);
22353 
22354   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22355                "  return 29;\n"
22356                "} else if (argc > 10) [[likely]] {\n"
22357                "  return 99;\n"
22358                "} else {\n"
22359                "  return 42;\n"
22360                "}\n",
22361                Style);
22362 
22363   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
22364                "  return 29;\n"
22365                "}",
22366                Style);
22367 
22368   verifyFormat("if (argc > 5) [[unlikely]]\n"
22369                "  return 29;\n",
22370                Style);
22371   verifyFormat("if (argc > 5) [[likely]]\n"
22372                "  return 29;\n",
22373                Style);
22374 
22375   Style.AttributeMacros.push_back("UNLIKELY");
22376   Style.AttributeMacros.push_back("LIKELY");
22377   verifyFormat("if (argc > 5) UNLIKELY\n"
22378                "  return 29;\n",
22379                Style);
22380 
22381   verifyFormat("if (argc > 5) UNLIKELY {\n"
22382                "  return 29;\n"
22383                "}",
22384                Style);
22385   verifyFormat("if (argc > 5) UNLIKELY {\n"
22386                "  return 29;\n"
22387                "} else [[likely]] {\n"
22388                "  return 42;\n"
22389                "}\n",
22390                Style);
22391   verifyFormat("if (argc > 5) UNLIKELY {\n"
22392                "  return 29;\n"
22393                "} else LIKELY {\n"
22394                "  return 42;\n"
22395                "}\n",
22396                Style);
22397   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22398                "  return 29;\n"
22399                "} else LIKELY {\n"
22400                "  return 42;\n"
22401                "}\n",
22402                Style);
22403 }
22404 
22405 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
22406   verifyFormat("Constructor()\n"
22407                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
22408                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
22409                "aaaaaaaaaaaaaaaaaat))");
22410   verifyFormat("Constructor()\n"
22411                "    : aaaaaaaaaaaaa(aaaaaa), "
22412                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
22413 
22414   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
22415   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
22416   verifyFormat("Constructor()\n"
22417                "    : aaaaaa(aaaaaa),\n"
22418                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
22419                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
22420                StyleWithWhitespacePenalty);
22421   verifyFormat("Constructor()\n"
22422                "    : aaaaaaaaaaaaa(aaaaaa), "
22423                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
22424                StyleWithWhitespacePenalty);
22425 }
22426 
22427 TEST_F(FormatTest, LLVMDefaultStyle) {
22428   FormatStyle Style = getLLVMStyle();
22429   verifyFormat("extern \"C\" {\n"
22430                "int foo();\n"
22431                "}",
22432                Style);
22433 }
22434 TEST_F(FormatTest, GNUDefaultStyle) {
22435   FormatStyle Style = getGNUStyle();
22436   verifyFormat("extern \"C\"\n"
22437                "{\n"
22438                "  int foo ();\n"
22439                "}",
22440                Style);
22441 }
22442 TEST_F(FormatTest, MozillaDefaultStyle) {
22443   FormatStyle Style = getMozillaStyle();
22444   verifyFormat("extern \"C\"\n"
22445                "{\n"
22446                "  int foo();\n"
22447                "}",
22448                Style);
22449 }
22450 TEST_F(FormatTest, GoogleDefaultStyle) {
22451   FormatStyle Style = getGoogleStyle();
22452   verifyFormat("extern \"C\" {\n"
22453                "int foo();\n"
22454                "}",
22455                Style);
22456 }
22457 TEST_F(FormatTest, ChromiumDefaultStyle) {
22458   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
22459   verifyFormat("extern \"C\" {\n"
22460                "int foo();\n"
22461                "}",
22462                Style);
22463 }
22464 TEST_F(FormatTest, MicrosoftDefaultStyle) {
22465   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
22466   verifyFormat("extern \"C\"\n"
22467                "{\n"
22468                "    int foo();\n"
22469                "}",
22470                Style);
22471 }
22472 TEST_F(FormatTest, WebKitDefaultStyle) {
22473   FormatStyle Style = getWebKitStyle();
22474   verifyFormat("extern \"C\" {\n"
22475                "int foo();\n"
22476                "}",
22477                Style);
22478 }
22479 
22480 TEST_F(FormatTest, ConceptsAndRequires) {
22481   FormatStyle Style = getLLVMStyle();
22482   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
22483 
22484   verifyFormat("template <typename T>\n"
22485                "concept Hashable = requires(T a) {\n"
22486                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22487                "};",
22488                Style);
22489   verifyFormat("template <typename T>\n"
22490                "concept EqualityComparable = requires(T a, T b) {\n"
22491                "  { a == b } -> bool;\n"
22492                "};",
22493                Style);
22494   verifyFormat("template <typename T>\n"
22495                "concept EqualityComparable = requires(T a, T b) {\n"
22496                "  { a == b } -> bool;\n"
22497                "  { a != b } -> bool;\n"
22498                "};",
22499                Style);
22500   verifyFormat("template <typename T>\n"
22501                "concept EqualityComparable = requires(T a, T b) {\n"
22502                "  { a == b } -> bool;\n"
22503                "  { a != b } -> bool;\n"
22504                "};",
22505                Style);
22506 
22507   verifyFormat("template <typename It>\n"
22508                "requires Iterator<It>\n"
22509                "void sort(It begin, It end) {\n"
22510                "  //....\n"
22511                "}",
22512                Style);
22513 
22514   verifyFormat("template <typename T>\n"
22515                "concept Large = sizeof(T) > 10;",
22516                Style);
22517 
22518   verifyFormat("template <typename T, typename U>\n"
22519                "concept FooableWith = requires(T t, U u) {\n"
22520                "  typename T::foo_type;\n"
22521                "  { t.foo(u) } -> typename T::foo_type;\n"
22522                "  t++;\n"
22523                "};\n"
22524                "void doFoo(FooableWith<int> auto t) {\n"
22525                "  t.foo(3);\n"
22526                "}",
22527                Style);
22528   verifyFormat("template <typename T>\n"
22529                "concept Context = sizeof(T) == 1;",
22530                Style);
22531   verifyFormat("template <typename T>\n"
22532                "concept Context = is_specialization_of_v<context, T>;",
22533                Style);
22534   verifyFormat("template <typename T>\n"
22535                "concept Node = std::is_object_v<T>;",
22536                Style);
22537   verifyFormat("template <typename T>\n"
22538                "concept Tree = true;",
22539                Style);
22540 
22541   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
22542                "  //...\n"
22543                "}",
22544                Style);
22545 
22546   verifyFormat(
22547       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
22548       "  //...\n"
22549       "}",
22550       Style);
22551 
22552   verifyFormat(
22553       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
22554       "  //...\n"
22555       "}",
22556       Style);
22557 
22558   verifyFormat("template <typename T>\n"
22559                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
22560                "Concept2<I> {\n"
22561                "  //...\n"
22562                "}",
22563                Style);
22564 
22565   verifyFormat("template <typename T>\n"
22566                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
22567                "Concept2<I> {\n"
22568                "  //...\n"
22569                "}",
22570                Style);
22571 
22572   verifyFormat(
22573       "template <typename T>\n"
22574       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
22575       "  //...\n"
22576       "}",
22577       Style);
22578 
22579   verifyFormat(
22580       "template <typename T>\n"
22581       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
22582       "  //...\n"
22583       "}",
22584       Style);
22585 
22586   verifyFormat("template <typename It>\n"
22587                "requires Foo<It>() && Bar<It> {\n"
22588                "  //....\n"
22589                "}",
22590                Style);
22591 
22592   verifyFormat("template <typename It>\n"
22593                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
22594                "  //....\n"
22595                "}",
22596                Style);
22597 
22598   verifyFormat("template <typename It>\n"
22599                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
22600                "  //....\n"
22601                "}",
22602                Style);
22603 
22604   verifyFormat(
22605       "template <typename It>\n"
22606       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
22607       "  //....\n"
22608       "}",
22609       Style);
22610 
22611   Style.IndentRequires = true;
22612   verifyFormat("template <typename It>\n"
22613                "  requires Iterator<It>\n"
22614                "void sort(It begin, It end) {\n"
22615                "  //....\n"
22616                "}",
22617                Style);
22618   verifyFormat("template <std::size index_>\n"
22619                "  requires(index_ < sizeof...(Children_))\n"
22620                "Tree auto &child() {\n"
22621                "  // ...\n"
22622                "}",
22623                Style);
22624 
22625   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
22626   verifyFormat("template <typename T>\n"
22627                "concept Hashable = requires (T a) {\n"
22628                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22629                "};",
22630                Style);
22631 
22632   verifyFormat("template <class T = void>\n"
22633                "  requires EqualityComparable<T> || Same<T, void>\n"
22634                "struct equal_to;",
22635                Style);
22636 
22637   verifyFormat("template <class T>\n"
22638                "  requires requires {\n"
22639                "    T{};\n"
22640                "    T (int);\n"
22641                "  }\n",
22642                Style);
22643 
22644   Style.ColumnLimit = 78;
22645   verifyFormat("template <typename T>\n"
22646                "concept Context = Traits<typename T::traits_type> and\n"
22647                "    Interface<typename T::interface_type> and\n"
22648                "    Request<typename T::request_type> and\n"
22649                "    Response<typename T::response_type> and\n"
22650                "    ContextExtension<typename T::extension_type> and\n"
22651                "    ::std::is_copy_constructable<T> and "
22652                "::std::is_move_constructable<T> and\n"
22653                "    requires (T c) {\n"
22654                "  { c.response; } -> Response;\n"
22655                "} and requires (T c) {\n"
22656                "  { c.request; } -> Request;\n"
22657                "}\n",
22658                Style);
22659 
22660   verifyFormat("template <typename T>\n"
22661                "concept Context = Traits<typename T::traits_type> or\n"
22662                "    Interface<typename T::interface_type> or\n"
22663                "    Request<typename T::request_type> or\n"
22664                "    Response<typename T::response_type> or\n"
22665                "    ContextExtension<typename T::extension_type> or\n"
22666                "    ::std::is_copy_constructable<T> or "
22667                "::std::is_move_constructable<T> or\n"
22668                "    requires (T c) {\n"
22669                "  { c.response; } -> Response;\n"
22670                "} or requires (T c) {\n"
22671                "  { c.request; } -> Request;\n"
22672                "}\n",
22673                Style);
22674 
22675   verifyFormat("template <typename T>\n"
22676                "concept Context = Traits<typename T::traits_type> &&\n"
22677                "    Interface<typename T::interface_type> &&\n"
22678                "    Request<typename T::request_type> &&\n"
22679                "    Response<typename T::response_type> &&\n"
22680                "    ContextExtension<typename T::extension_type> &&\n"
22681                "    ::std::is_copy_constructable<T> && "
22682                "::std::is_move_constructable<T> &&\n"
22683                "    requires (T c) {\n"
22684                "  { c.response; } -> Response;\n"
22685                "} && requires (T c) {\n"
22686                "  { c.request; } -> Request;\n"
22687                "}\n",
22688                Style);
22689 
22690   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
22691                "Constraint2<T>;");
22692 
22693   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
22694   Style.BraceWrapping.AfterFunction = true;
22695   Style.BraceWrapping.AfterClass = true;
22696   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
22697   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
22698   verifyFormat("void Foo () requires (std::copyable<T>)\n"
22699                "{\n"
22700                "  return\n"
22701                "}\n",
22702                Style);
22703 
22704   verifyFormat("void Foo () requires std::copyable<T>\n"
22705                "{\n"
22706                "  return\n"
22707                "}\n",
22708                Style);
22709 
22710   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22711                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
22712                "struct constant;",
22713                Style);
22714 
22715   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22716                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
22717                "struct constant;",
22718                Style);
22719 
22720   verifyFormat("template <class T>\n"
22721                "class plane_with_very_very_very_long_name\n"
22722                "{\n"
22723                "  constexpr plane_with_very_very_very_long_name () requires "
22724                "std::copyable<T>\n"
22725                "      : plane_with_very_very_very_long_name (1)\n"
22726                "  {\n"
22727                "  }\n"
22728                "}\n",
22729                Style);
22730 
22731   verifyFormat("template <class T>\n"
22732                "class plane_with_long_name\n"
22733                "{\n"
22734                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
22735                "      : plane_with_long_name (1)\n"
22736                "  {\n"
22737                "  }\n"
22738                "}\n",
22739                Style);
22740 
22741   Style.BreakBeforeConceptDeclarations = false;
22742   verifyFormat("template <typename T> concept Tree = true;", Style);
22743 
22744   Style.IndentRequires = false;
22745   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22746                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
22747                "struct constant;",
22748                Style);
22749 }
22750 
22751 TEST_F(FormatTest, StatementAttributeLikeMacros) {
22752   FormatStyle Style = getLLVMStyle();
22753   StringRef Source = "void Foo::slot() {\n"
22754                      "  unsigned char MyChar = 'x';\n"
22755                      "  emit signal(MyChar);\n"
22756                      "  Q_EMIT signal(MyChar);\n"
22757                      "}";
22758 
22759   EXPECT_EQ(Source, format(Source, Style));
22760 
22761   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
22762   EXPECT_EQ("void Foo::slot() {\n"
22763             "  unsigned char MyChar = 'x';\n"
22764             "  emit          signal(MyChar);\n"
22765             "  Q_EMIT signal(MyChar);\n"
22766             "}",
22767             format(Source, Style));
22768 
22769   Style.StatementAttributeLikeMacros.push_back("emit");
22770   EXPECT_EQ(Source, format(Source, Style));
22771 
22772   Style.StatementAttributeLikeMacros = {};
22773   EXPECT_EQ("void Foo::slot() {\n"
22774             "  unsigned char MyChar = 'x';\n"
22775             "  emit          signal(MyChar);\n"
22776             "  Q_EMIT        signal(MyChar);\n"
22777             "}",
22778             format(Source, Style));
22779 }
22780 
22781 TEST_F(FormatTest, IndentAccessModifiers) {
22782   FormatStyle Style = getLLVMStyle();
22783   Style.IndentAccessModifiers = true;
22784   // Members are *two* levels below the record;
22785   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
22786   verifyFormat("class C {\n"
22787                "    int i;\n"
22788                "};\n",
22789                Style);
22790   verifyFormat("union C {\n"
22791                "    int i;\n"
22792                "    unsigned u;\n"
22793                "};\n",
22794                Style);
22795   // Access modifiers should be indented one level below the record.
22796   verifyFormat("class C {\n"
22797                "  public:\n"
22798                "    int i;\n"
22799                "};\n",
22800                Style);
22801   verifyFormat("struct S {\n"
22802                "  private:\n"
22803                "    class C {\n"
22804                "        int j;\n"
22805                "\n"
22806                "      public:\n"
22807                "        C();\n"
22808                "    };\n"
22809                "\n"
22810                "  public:\n"
22811                "    int i;\n"
22812                "};\n",
22813                Style);
22814   // Enumerations are not records and should be unaffected.
22815   Style.AllowShortEnumsOnASingleLine = false;
22816   verifyFormat("enum class E {\n"
22817                "  A,\n"
22818                "  B\n"
22819                "};\n",
22820                Style);
22821   // Test with a different indentation width;
22822   // also proves that the result is Style.AccessModifierOffset agnostic.
22823   Style.IndentWidth = 3;
22824   verifyFormat("class C {\n"
22825                "   public:\n"
22826                "      int i;\n"
22827                "};\n",
22828                Style);
22829 }
22830 
22831 TEST_F(FormatTest, LimitlessStringsAndComments) {
22832   auto Style = getLLVMStyleWithColumns(0);
22833   constexpr StringRef Code =
22834       "/**\n"
22835       " * This is a multiline comment with quite some long lines, at least for "
22836       "the LLVM Style.\n"
22837       " * We will redo this with strings and line comments. Just to  check if "
22838       "everything is working.\n"
22839       " */\n"
22840       "bool foo() {\n"
22841       "  /* Single line multi line comment. */\n"
22842       "  const std::string String = \"This is a multiline string with quite "
22843       "some long lines, at least for the LLVM Style.\"\n"
22844       "                             \"We already did it with multi line "
22845       "comments, and we will do it with line comments. Just to check if "
22846       "everything is working.\";\n"
22847       "  // This is a line comment (block) with quite some long lines, at "
22848       "least for the LLVM Style.\n"
22849       "  // We already did this with multi line comments and strings. Just to "
22850       "check if everything is working.\n"
22851       "  const std::string SmallString = \"Hello World\";\n"
22852       "  // Small line comment\n"
22853       "  return String.size() > SmallString.size();\n"
22854       "}";
22855   EXPECT_EQ(Code, format(Code, Style));
22856 }
22857 
22858 TEST_F(FormatTest, FormatDecayCopy) {
22859   // error cases from unit tests
22860   verifyFormat("foo(auto())");
22861   verifyFormat("foo(auto{})");
22862   verifyFormat("foo(auto({}))");
22863   verifyFormat("foo(auto{{}})");
22864 
22865   verifyFormat("foo(auto(1))");
22866   verifyFormat("foo(auto{1})");
22867   verifyFormat("foo(new auto(1))");
22868   verifyFormat("foo(new auto{1})");
22869   verifyFormat("decltype(auto(1)) x;");
22870   verifyFormat("decltype(auto{1}) x;");
22871   verifyFormat("auto(x);");
22872   verifyFormat("auto{x};");
22873   verifyFormat("new auto{x};");
22874   verifyFormat("auto{x} = y;");
22875   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
22876                                 // the user's own fault
22877   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
22878                                          // clearly the user's own fault
22879   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
22880 }
22881 
22882 TEST_F(FormatTest, Cpp20ModulesSupport) {
22883   FormatStyle Style = getLLVMStyle();
22884   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22885   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
22886 
22887   verifyFormat("export import foo;", Style);
22888   verifyFormat("export import foo:bar;", Style);
22889   verifyFormat("export import foo.bar;", Style);
22890   verifyFormat("export import foo.bar:baz;", Style);
22891   verifyFormat("export import :bar;", Style);
22892   verifyFormat("export module foo:bar;", Style);
22893   verifyFormat("export module foo;", Style);
22894   verifyFormat("export module foo.bar;", Style);
22895   verifyFormat("export module foo.bar:baz;", Style);
22896   verifyFormat("export import <string_view>;", Style);
22897 
22898   verifyFormat("export type_name var;", Style);
22899   verifyFormat("template <class T> export using A = B<T>;", Style);
22900   verifyFormat("export using A = B;", Style);
22901   verifyFormat("export int func() {\n"
22902                "  foo();\n"
22903                "}",
22904                Style);
22905   verifyFormat("export struct {\n"
22906                "  int foo;\n"
22907                "};",
22908                Style);
22909   verifyFormat("export {\n"
22910                "  int foo;\n"
22911                "};",
22912                Style);
22913   verifyFormat("export export char const *hello() { return \"hello\"; }");
22914 
22915   verifyFormat("import bar;", Style);
22916   verifyFormat("import foo.bar;", Style);
22917   verifyFormat("import foo:bar;", Style);
22918   verifyFormat("import :bar;", Style);
22919   verifyFormat("import <ctime>;", Style);
22920   verifyFormat("import \"header\";", Style);
22921 
22922   verifyFormat("module foo;", Style);
22923   verifyFormat("module foo:bar;", Style);
22924   verifyFormat("module foo.bar;", Style);
22925   verifyFormat("module;", Style);
22926 
22927   verifyFormat("export namespace hi {\n"
22928                "const char *sayhi();\n"
22929                "}",
22930                Style);
22931 
22932   verifyFormat("module :private;", Style);
22933   verifyFormat("import <foo/bar.h>;", Style);
22934   verifyFormat("import foo...bar;", Style);
22935   verifyFormat("import ..........;", Style);
22936   verifyFormat("module foo:private;", Style);
22937   verifyFormat("import a", Style);
22938   verifyFormat("module a", Style);
22939   verifyFormat("export import a", Style);
22940   verifyFormat("export module a", Style);
22941 
22942   verifyFormat("import", Style);
22943   verifyFormat("module", Style);
22944   verifyFormat("export", Style);
22945 }
22946 
22947 TEST_F(FormatTest, CoroutineForCoawait) {
22948   FormatStyle Style = getLLVMStyle();
22949   verifyFormat("for co_await (auto x : range())\n  ;");
22950   verifyFormat("for (auto i : arr) {\n"
22951                "}",
22952                Style);
22953   verifyFormat("for co_await (auto i : arr) {\n"
22954                "}",
22955                Style);
22956   verifyFormat("for co_await (auto i : foo(T{})) {\n"
22957                "}",
22958                Style);
22959 }
22960 
22961 TEST_F(FormatTest, CoroutineCoAwait) {
22962   verifyFormat("int x = co_await foo();");
22963   verifyFormat("int x = (co_await foo());");
22964   verifyFormat("co_await (42);");
22965   verifyFormat("void operator co_await(int);");
22966   verifyFormat("void operator co_await(a);");
22967   verifyFormat("co_await a;");
22968   verifyFormat("co_await missing_await_resume{};");
22969   verifyFormat("co_await a; // comment");
22970   verifyFormat("void test0() { co_await a; }");
22971   verifyFormat("co_await co_await co_await foo();");
22972   verifyFormat("co_await foo().bar();");
22973   verifyFormat("co_await [this]() -> Task { co_return x; }");
22974   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
22975                "foo(); }(x, y);");
22976 
22977   FormatStyle Style = getLLVMStyle();
22978   Style.ColumnLimit = 40;
22979   verifyFormat("co_await [this](int a, int b) -> Task {\n"
22980                "  co_return co_await foo();\n"
22981                "}(x, y);",
22982                Style);
22983   verifyFormat("co_await;");
22984 }
22985 
22986 TEST_F(FormatTest, CoroutineCoYield) {
22987   verifyFormat("int x = co_yield foo();");
22988   verifyFormat("int x = (co_yield foo());");
22989   verifyFormat("co_yield (42);");
22990   verifyFormat("co_yield {42};");
22991   verifyFormat("co_yield 42;");
22992   verifyFormat("co_yield n++;");
22993   verifyFormat("co_yield ++n;");
22994   verifyFormat("co_yield;");
22995 }
22996 
22997 TEST_F(FormatTest, CoroutineCoReturn) {
22998   verifyFormat("co_return (42);");
22999   verifyFormat("co_return;");
23000   verifyFormat("co_return {};");
23001   verifyFormat("co_return x;");
23002   verifyFormat("co_return co_await foo();");
23003   verifyFormat("co_return co_yield foo();");
23004 }
23005 
23006 TEST_F(FormatTest, EmptyShortBlock) {
23007   auto Style = getLLVMStyle();
23008   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
23009 
23010   verifyFormat("try {\n"
23011                "  doA();\n"
23012                "} catch (Exception &e) {\n"
23013                "  e.printStackTrace();\n"
23014                "}\n",
23015                Style);
23016 
23017   verifyFormat("try {\n"
23018                "  doA();\n"
23019                "} catch (Exception &e) {}\n",
23020                Style);
23021 }
23022 
23023 } // namespace
23024 } // namespace format
23025 } // namespace clang
23026