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   verifyFormat("typedef enum\n"
2539                "{\n"
2540                "  A,\n"
2541                "  B,\n"
2542                "  C\n"
2543                "} ShortEnum1, ShortEnum2;",
2544                Style);
2545 }
2546 
2547 TEST_F(FormatTest, ShortCaseLabels) {
2548   FormatStyle Style = getLLVMStyle();
2549   Style.AllowShortCaseLabelsOnASingleLine = true;
2550   verifyFormat("switch (a) {\n"
2551                "case 1: x = 1; break;\n"
2552                "case 2: return;\n"
2553                "case 3:\n"
2554                "case 4:\n"
2555                "case 5: return;\n"
2556                "case 6: // comment\n"
2557                "  return;\n"
2558                "case 7:\n"
2559                "  // comment\n"
2560                "  return;\n"
2561                "case 8:\n"
2562                "  x = 8; // comment\n"
2563                "  break;\n"
2564                "default: y = 1; break;\n"
2565                "}",
2566                Style);
2567   verifyFormat("switch (a) {\n"
2568                "case 0: return; // comment\n"
2569                "case 1: break;  // comment\n"
2570                "case 2: return;\n"
2571                "// comment\n"
2572                "case 3: return;\n"
2573                "// comment 1\n"
2574                "// comment 2\n"
2575                "// comment 3\n"
2576                "case 4: break; /* comment */\n"
2577                "case 5:\n"
2578                "  // comment\n"
2579                "  break;\n"
2580                "case 6: /* comment */ x = 1; break;\n"
2581                "case 7: x = /* comment */ 1; break;\n"
2582                "case 8:\n"
2583                "  x = 1; /* comment */\n"
2584                "  break;\n"
2585                "case 9:\n"
2586                "  break; // comment line 1\n"
2587                "         // comment line 2\n"
2588                "}",
2589                Style);
2590   EXPECT_EQ("switch (a) {\n"
2591             "case 1:\n"
2592             "  x = 8;\n"
2593             "  // fall through\n"
2594             "case 2: x = 8;\n"
2595             "// comment\n"
2596             "case 3:\n"
2597             "  return; /* comment line 1\n"
2598             "           * comment line 2 */\n"
2599             "case 4: i = 8;\n"
2600             "// something else\n"
2601             "#if FOO\n"
2602             "case 5: break;\n"
2603             "#endif\n"
2604             "}",
2605             format("switch (a) {\n"
2606                    "case 1: x = 8;\n"
2607                    "  // fall through\n"
2608                    "case 2:\n"
2609                    "  x = 8;\n"
2610                    "// comment\n"
2611                    "case 3:\n"
2612                    "  return; /* comment line 1\n"
2613                    "           * comment line 2 */\n"
2614                    "case 4:\n"
2615                    "  i = 8;\n"
2616                    "// something else\n"
2617                    "#if FOO\n"
2618                    "case 5: break;\n"
2619                    "#endif\n"
2620                    "}",
2621                    Style));
2622   EXPECT_EQ("switch (a) {\n"
2623             "case 0:\n"
2624             "  return; // long long long long long long long long long long "
2625             "long long comment\n"
2626             "          // line\n"
2627             "}",
2628             format("switch (a) {\n"
2629                    "case 0: return; // long long long long long long long long "
2630                    "long long long long comment line\n"
2631                    "}",
2632                    Style));
2633   EXPECT_EQ("switch (a) {\n"
2634             "case 0:\n"
2635             "  return; /* long long long long long long long long long long "
2636             "long long comment\n"
2637             "             line */\n"
2638             "}",
2639             format("switch (a) {\n"
2640                    "case 0: return; /* long long long long long long long long "
2641                    "long long long long comment line */\n"
2642                    "}",
2643                    Style));
2644   verifyFormat("switch (a) {\n"
2645                "#if FOO\n"
2646                "case 0: return 0;\n"
2647                "#endif\n"
2648                "}",
2649                Style);
2650   verifyFormat("switch (a) {\n"
2651                "case 1: {\n"
2652                "}\n"
2653                "case 2: {\n"
2654                "  return;\n"
2655                "}\n"
2656                "case 3: {\n"
2657                "  x = 1;\n"
2658                "  return;\n"
2659                "}\n"
2660                "case 4:\n"
2661                "  if (x)\n"
2662                "    return;\n"
2663                "}",
2664                Style);
2665   Style.ColumnLimit = 21;
2666   verifyFormat("switch (a) {\n"
2667                "case 1: x = 1; break;\n"
2668                "case 2: return;\n"
2669                "case 3:\n"
2670                "case 4:\n"
2671                "case 5: return;\n"
2672                "default:\n"
2673                "  y = 1;\n"
2674                "  break;\n"
2675                "}",
2676                Style);
2677   Style.ColumnLimit = 80;
2678   Style.AllowShortCaseLabelsOnASingleLine = false;
2679   Style.IndentCaseLabels = true;
2680   EXPECT_EQ("switch (n) {\n"
2681             "  default /*comments*/:\n"
2682             "    return true;\n"
2683             "  case 0:\n"
2684             "    return false;\n"
2685             "}",
2686             format("switch (n) {\n"
2687                    "default/*comments*/:\n"
2688                    "  return true;\n"
2689                    "case 0:\n"
2690                    "  return false;\n"
2691                    "}",
2692                    Style));
2693   Style.AllowShortCaseLabelsOnASingleLine = true;
2694   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2695   Style.BraceWrapping.AfterCaseLabel = true;
2696   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2697   EXPECT_EQ("switch (n)\n"
2698             "{\n"
2699             "  case 0:\n"
2700             "  {\n"
2701             "    return false;\n"
2702             "  }\n"
2703             "  default:\n"
2704             "  {\n"
2705             "    return true;\n"
2706             "  }\n"
2707             "}",
2708             format("switch (n) {\n"
2709                    "  case 0: {\n"
2710                    "    return false;\n"
2711                    "  }\n"
2712                    "  default:\n"
2713                    "  {\n"
2714                    "    return true;\n"
2715                    "  }\n"
2716                    "}",
2717                    Style));
2718 }
2719 
2720 TEST_F(FormatTest, FormatsLabels) {
2721   verifyFormat("void f() {\n"
2722                "  some_code();\n"
2723                "test_label:\n"
2724                "  some_other_code();\n"
2725                "  {\n"
2726                "    some_more_code();\n"
2727                "  another_label:\n"
2728                "    some_more_code();\n"
2729                "  }\n"
2730                "}");
2731   verifyFormat("{\n"
2732                "  some_code();\n"
2733                "test_label:\n"
2734                "  some_other_code();\n"
2735                "}");
2736   verifyFormat("{\n"
2737                "  some_code();\n"
2738                "test_label:;\n"
2739                "  int i = 0;\n"
2740                "}");
2741   FormatStyle Style = getLLVMStyle();
2742   Style.IndentGotoLabels = false;
2743   verifyFormat("void f() {\n"
2744                "  some_code();\n"
2745                "test_label:\n"
2746                "  some_other_code();\n"
2747                "  {\n"
2748                "    some_more_code();\n"
2749                "another_label:\n"
2750                "    some_more_code();\n"
2751                "  }\n"
2752                "}",
2753                Style);
2754   verifyFormat("{\n"
2755                "  some_code();\n"
2756                "test_label:\n"
2757                "  some_other_code();\n"
2758                "}",
2759                Style);
2760   verifyFormat("{\n"
2761                "  some_code();\n"
2762                "test_label:;\n"
2763                "  int i = 0;\n"
2764                "}");
2765 }
2766 
2767 TEST_F(FormatTest, MultiLineControlStatements) {
2768   FormatStyle Style = getLLVMStyleWithColumns(20);
2769   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2770   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2771   // Short lines should keep opening brace on same line.
2772   EXPECT_EQ("if (foo) {\n"
2773             "  bar();\n"
2774             "}",
2775             format("if(foo){bar();}", Style));
2776   EXPECT_EQ("if (foo) {\n"
2777             "  bar();\n"
2778             "} else {\n"
2779             "  baz();\n"
2780             "}",
2781             format("if(foo){bar();}else{baz();}", Style));
2782   EXPECT_EQ("if (foo && bar) {\n"
2783             "  baz();\n"
2784             "}",
2785             format("if(foo&&bar){baz();}", Style));
2786   EXPECT_EQ("if (foo) {\n"
2787             "  bar();\n"
2788             "} else if (baz) {\n"
2789             "  quux();\n"
2790             "}",
2791             format("if(foo){bar();}else if(baz){quux();}", Style));
2792   EXPECT_EQ(
2793       "if (foo) {\n"
2794       "  bar();\n"
2795       "} else if (baz) {\n"
2796       "  quux();\n"
2797       "} else {\n"
2798       "  foobar();\n"
2799       "}",
2800       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
2801   EXPECT_EQ("for (;;) {\n"
2802             "  foo();\n"
2803             "}",
2804             format("for(;;){foo();}"));
2805   EXPECT_EQ("while (1) {\n"
2806             "  foo();\n"
2807             "}",
2808             format("while(1){foo();}", Style));
2809   EXPECT_EQ("switch (foo) {\n"
2810             "case bar:\n"
2811             "  return;\n"
2812             "}",
2813             format("switch(foo){case bar:return;}", Style));
2814   EXPECT_EQ("try {\n"
2815             "  foo();\n"
2816             "} catch (...) {\n"
2817             "  bar();\n"
2818             "}",
2819             format("try{foo();}catch(...){bar();}", Style));
2820   EXPECT_EQ("do {\n"
2821             "  foo();\n"
2822             "} while (bar &&\n"
2823             "         baz);",
2824             format("do{foo();}while(bar&&baz);", Style));
2825   // Long lines should put opening brace on new line.
2826   EXPECT_EQ("if (foo && bar &&\n"
2827             "    baz)\n"
2828             "{\n"
2829             "  quux();\n"
2830             "}",
2831             format("if(foo&&bar&&baz){quux();}", Style));
2832   EXPECT_EQ("if (foo && bar &&\n"
2833             "    baz)\n"
2834             "{\n"
2835             "  quux();\n"
2836             "}",
2837             format("if (foo && bar &&\n"
2838                    "    baz) {\n"
2839                    "  quux();\n"
2840                    "}",
2841                    Style));
2842   EXPECT_EQ("if (foo) {\n"
2843             "  bar();\n"
2844             "} else if (baz ||\n"
2845             "           quux)\n"
2846             "{\n"
2847             "  foobar();\n"
2848             "}",
2849             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
2850   EXPECT_EQ(
2851       "if (foo) {\n"
2852       "  bar();\n"
2853       "} else if (baz ||\n"
2854       "           quux)\n"
2855       "{\n"
2856       "  foobar();\n"
2857       "} else {\n"
2858       "  barbaz();\n"
2859       "}",
2860       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2861              Style));
2862   EXPECT_EQ("for (int i = 0;\n"
2863             "     i < 10; ++i)\n"
2864             "{\n"
2865             "  foo();\n"
2866             "}",
2867             format("for(int i=0;i<10;++i){foo();}", Style));
2868   EXPECT_EQ("foreach (int i,\n"
2869             "         list)\n"
2870             "{\n"
2871             "  foo();\n"
2872             "}",
2873             format("foreach(int i, list){foo();}", Style));
2874   Style.ColumnLimit =
2875       40; // to concentrate at brace wrapping, not line wrap due to column limit
2876   EXPECT_EQ("foreach (int i, list) {\n"
2877             "  foo();\n"
2878             "}",
2879             format("foreach(int i, list){foo();}", Style));
2880   Style.ColumnLimit =
2881       20; // to concentrate at brace wrapping, not line wrap due to column limit
2882   EXPECT_EQ("while (foo || bar ||\n"
2883             "       baz)\n"
2884             "{\n"
2885             "  quux();\n"
2886             "}",
2887             format("while(foo||bar||baz){quux();}", Style));
2888   EXPECT_EQ("switch (\n"
2889             "    foo = barbaz)\n"
2890             "{\n"
2891             "case quux:\n"
2892             "  return;\n"
2893             "}",
2894             format("switch(foo=barbaz){case quux:return;}", Style));
2895   EXPECT_EQ("try {\n"
2896             "  foo();\n"
2897             "} catch (\n"
2898             "    Exception &bar)\n"
2899             "{\n"
2900             "  baz();\n"
2901             "}",
2902             format("try{foo();}catch(Exception&bar){baz();}", Style));
2903   Style.ColumnLimit =
2904       40; // to concentrate at brace wrapping, not line wrap due to column limit
2905   EXPECT_EQ("try {\n"
2906             "  foo();\n"
2907             "} catch (Exception &bar) {\n"
2908             "  baz();\n"
2909             "}",
2910             format("try{foo();}catch(Exception&bar){baz();}", Style));
2911   Style.ColumnLimit =
2912       20; // to concentrate at brace wrapping, not line wrap due to column limit
2913 
2914   Style.BraceWrapping.BeforeElse = true;
2915   EXPECT_EQ(
2916       "if (foo) {\n"
2917       "  bar();\n"
2918       "}\n"
2919       "else if (baz ||\n"
2920       "         quux)\n"
2921       "{\n"
2922       "  foobar();\n"
2923       "}\n"
2924       "else {\n"
2925       "  barbaz();\n"
2926       "}",
2927       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2928              Style));
2929 
2930   Style.BraceWrapping.BeforeCatch = true;
2931   EXPECT_EQ("try {\n"
2932             "  foo();\n"
2933             "}\n"
2934             "catch (...) {\n"
2935             "  baz();\n"
2936             "}",
2937             format("try{foo();}catch(...){baz();}", Style));
2938 
2939   Style.BraceWrapping.AfterFunction = true;
2940   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2941   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
2942   Style.ColumnLimit = 80;
2943   verifyFormat("void shortfunction() { bar(); }", Style);
2944 
2945   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
2946   verifyFormat("void shortfunction()\n"
2947                "{\n"
2948                "  bar();\n"
2949                "}",
2950                Style);
2951 }
2952 
2953 TEST_F(FormatTest, BeforeWhile) {
2954   FormatStyle Style = getLLVMStyle();
2955   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2956 
2957   verifyFormat("do {\n"
2958                "  foo();\n"
2959                "} while (1);",
2960                Style);
2961   Style.BraceWrapping.BeforeWhile = true;
2962   verifyFormat("do {\n"
2963                "  foo();\n"
2964                "}\n"
2965                "while (1);",
2966                Style);
2967 }
2968 
2969 //===----------------------------------------------------------------------===//
2970 // Tests for classes, namespaces, etc.
2971 //===----------------------------------------------------------------------===//
2972 
2973 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
2974   verifyFormat("class A {};");
2975 }
2976 
2977 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
2978   verifyFormat("class A {\n"
2979                "public:\n"
2980                "public: // comment\n"
2981                "protected:\n"
2982                "private:\n"
2983                "  void f() {}\n"
2984                "};");
2985   verifyFormat("export class A {\n"
2986                "public:\n"
2987                "public: // comment\n"
2988                "protected:\n"
2989                "private:\n"
2990                "  void f() {}\n"
2991                "};");
2992   verifyGoogleFormat("class A {\n"
2993                      " public:\n"
2994                      " protected:\n"
2995                      " private:\n"
2996                      "  void f() {}\n"
2997                      "};");
2998   verifyGoogleFormat("export class A {\n"
2999                      " public:\n"
3000                      " protected:\n"
3001                      " private:\n"
3002                      "  void f() {}\n"
3003                      "};");
3004   verifyFormat("class A {\n"
3005                "public slots:\n"
3006                "  void f1() {}\n"
3007                "public Q_SLOTS:\n"
3008                "  void f2() {}\n"
3009                "protected slots:\n"
3010                "  void f3() {}\n"
3011                "protected Q_SLOTS:\n"
3012                "  void f4() {}\n"
3013                "private slots:\n"
3014                "  void f5() {}\n"
3015                "private Q_SLOTS:\n"
3016                "  void f6() {}\n"
3017                "signals:\n"
3018                "  void g1();\n"
3019                "Q_SIGNALS:\n"
3020                "  void g2();\n"
3021                "};");
3022 
3023   // Don't interpret 'signals' the wrong way.
3024   verifyFormat("signals.set();");
3025   verifyFormat("for (Signals signals : f()) {\n}");
3026   verifyFormat("{\n"
3027                "  signals.set(); // This needs indentation.\n"
3028                "}");
3029   verifyFormat("void f() {\n"
3030                "label:\n"
3031                "  signals.baz();\n"
3032                "}");
3033 }
3034 
3035 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3036   EXPECT_EQ("class A {\n"
3037             "public:\n"
3038             "  void f();\n"
3039             "\n"
3040             "private:\n"
3041             "  void g() {}\n"
3042             "  // test\n"
3043             "protected:\n"
3044             "  int h;\n"
3045             "};",
3046             format("class A {\n"
3047                    "public:\n"
3048                    "void f();\n"
3049                    "private:\n"
3050                    "void g() {}\n"
3051                    "// test\n"
3052                    "protected:\n"
3053                    "int h;\n"
3054                    "};"));
3055   EXPECT_EQ("class A {\n"
3056             "protected:\n"
3057             "public:\n"
3058             "  void f();\n"
3059             "};",
3060             format("class A {\n"
3061                    "protected:\n"
3062                    "\n"
3063                    "public:\n"
3064                    "\n"
3065                    "  void f();\n"
3066                    "};"));
3067 
3068   // Even ensure proper spacing inside macros.
3069   EXPECT_EQ("#define B     \\\n"
3070             "  class A {   \\\n"
3071             "   protected: \\\n"
3072             "   public:    \\\n"
3073             "    void f(); \\\n"
3074             "  };",
3075             format("#define B     \\\n"
3076                    "  class A {   \\\n"
3077                    "   protected: \\\n"
3078                    "              \\\n"
3079                    "   public:    \\\n"
3080                    "              \\\n"
3081                    "    void f(); \\\n"
3082                    "  };",
3083                    getGoogleStyle()));
3084   // But don't remove empty lines after macros ending in access specifiers.
3085   EXPECT_EQ("#define A private:\n"
3086             "\n"
3087             "int i;",
3088             format("#define A         private:\n"
3089                    "\n"
3090                    "int              i;"));
3091 }
3092 
3093 TEST_F(FormatTest, FormatsClasses) {
3094   verifyFormat("class A : public B {};");
3095   verifyFormat("class A : public ::B {};");
3096 
3097   verifyFormat(
3098       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3099       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3100   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3101                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3102                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3103   verifyFormat(
3104       "class A : public B, public C, public D, public E, public F {};");
3105   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3106                "                     public C,\n"
3107                "                     public D,\n"
3108                "                     public E,\n"
3109                "                     public F,\n"
3110                "                     public G {};");
3111 
3112   verifyFormat("class\n"
3113                "    ReallyReallyLongClassName {\n"
3114                "  int i;\n"
3115                "};",
3116                getLLVMStyleWithColumns(32));
3117   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3118                "                           aaaaaaaaaaaaaaaa> {};");
3119   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3120                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3121                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3122   verifyFormat("template <class R, class C>\n"
3123                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3124                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3125   verifyFormat("class ::A::B {};");
3126 }
3127 
3128 TEST_F(FormatTest, BreakInheritanceStyle) {
3129   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3130   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3131       FormatStyle::BILS_BeforeComma;
3132   verifyFormat("class MyClass : public X {};",
3133                StyleWithInheritanceBreakBeforeComma);
3134   verifyFormat("class MyClass\n"
3135                "    : public X\n"
3136                "    , public Y {};",
3137                StyleWithInheritanceBreakBeforeComma);
3138   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3139                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3140                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3141                StyleWithInheritanceBreakBeforeComma);
3142   verifyFormat("struct aaaaaaaaaaaaa\n"
3143                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3144                "          aaaaaaaaaaaaaaaa> {};",
3145                StyleWithInheritanceBreakBeforeComma);
3146 
3147   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3148   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3149       FormatStyle::BILS_AfterColon;
3150   verifyFormat("class MyClass : public X {};",
3151                StyleWithInheritanceBreakAfterColon);
3152   verifyFormat("class MyClass : public X, public Y {};",
3153                StyleWithInheritanceBreakAfterColon);
3154   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3155                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3156                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3157                StyleWithInheritanceBreakAfterColon);
3158   verifyFormat("struct aaaaaaaaaaaaa :\n"
3159                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3160                "        aaaaaaaaaaaaaaaa> {};",
3161                StyleWithInheritanceBreakAfterColon);
3162 
3163   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3164   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3165       FormatStyle::BILS_AfterComma;
3166   verifyFormat("class MyClass : public X {};",
3167                StyleWithInheritanceBreakAfterComma);
3168   verifyFormat("class MyClass : public X,\n"
3169                "                public Y {};",
3170                StyleWithInheritanceBreakAfterComma);
3171   verifyFormat(
3172       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3173       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3174       "{};",
3175       StyleWithInheritanceBreakAfterComma);
3176   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3177                "                           aaaaaaaaaaaaaaaa> {};",
3178                StyleWithInheritanceBreakAfterComma);
3179   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3180                "    : public OnceBreak,\n"
3181                "      public AlwaysBreak,\n"
3182                "      EvenBasesFitInOneLine {};",
3183                StyleWithInheritanceBreakAfterComma);
3184 }
3185 
3186 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
3187   verifyFormat("class A {\n} a, b;");
3188   verifyFormat("struct A {\n} a, b;");
3189   verifyFormat("union A {\n} a;");
3190 }
3191 
3192 TEST_F(FormatTest, FormatsEnum) {
3193   verifyFormat("enum {\n"
3194                "  Zero,\n"
3195                "  One = 1,\n"
3196                "  Two = One + 1,\n"
3197                "  Three = (One + Two),\n"
3198                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3199                "  Five = (One, Two, Three, Four, 5)\n"
3200                "};");
3201   verifyGoogleFormat("enum {\n"
3202                      "  Zero,\n"
3203                      "  One = 1,\n"
3204                      "  Two = One + 1,\n"
3205                      "  Three = (One + Two),\n"
3206                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3207                      "  Five = (One, Two, Three, Four, 5)\n"
3208                      "};");
3209   verifyFormat("enum Enum {};");
3210   verifyFormat("enum {};");
3211   verifyFormat("enum X E {} d;");
3212   verifyFormat("enum __attribute__((...)) E {} d;");
3213   verifyFormat("enum __declspec__((...)) E {} d;");
3214   verifyFormat("enum {\n"
3215                "  Bar = Foo<int, int>::value\n"
3216                "};",
3217                getLLVMStyleWithColumns(30));
3218 
3219   verifyFormat("enum ShortEnum { A, B, C };");
3220   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3221 
3222   EXPECT_EQ("enum KeepEmptyLines {\n"
3223             "  ONE,\n"
3224             "\n"
3225             "  TWO,\n"
3226             "\n"
3227             "  THREE\n"
3228             "}",
3229             format("enum KeepEmptyLines {\n"
3230                    "  ONE,\n"
3231                    "\n"
3232                    "  TWO,\n"
3233                    "\n"
3234                    "\n"
3235                    "  THREE\n"
3236                    "}"));
3237   verifyFormat("enum E { // comment\n"
3238                "  ONE,\n"
3239                "  TWO\n"
3240                "};\n"
3241                "int i;");
3242 
3243   FormatStyle EightIndent = getLLVMStyle();
3244   EightIndent.IndentWidth = 8;
3245   verifyFormat("enum {\n"
3246                "        VOID,\n"
3247                "        CHAR,\n"
3248                "        SHORT,\n"
3249                "        INT,\n"
3250                "        LONG,\n"
3251                "        SIGNED,\n"
3252                "        UNSIGNED,\n"
3253                "        BOOL,\n"
3254                "        FLOAT,\n"
3255                "        DOUBLE,\n"
3256                "        COMPLEX\n"
3257                "};",
3258                EightIndent);
3259 
3260   // Not enums.
3261   verifyFormat("enum X f() {\n"
3262                "  a();\n"
3263                "  return 42;\n"
3264                "}");
3265   verifyFormat("enum X Type::f() {\n"
3266                "  a();\n"
3267                "  return 42;\n"
3268                "}");
3269   verifyFormat("enum ::X f() {\n"
3270                "  a();\n"
3271                "  return 42;\n"
3272                "}");
3273   verifyFormat("enum ns::X f() {\n"
3274                "  a();\n"
3275                "  return 42;\n"
3276                "}");
3277 }
3278 
3279 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3280   verifyFormat("enum Type {\n"
3281                "  One = 0; // These semicolons should be commas.\n"
3282                "  Two = 1;\n"
3283                "};");
3284   verifyFormat("namespace n {\n"
3285                "enum Type {\n"
3286                "  One,\n"
3287                "  Two, // missing };\n"
3288                "  int i;\n"
3289                "}\n"
3290                "void g() {}");
3291 }
3292 
3293 TEST_F(FormatTest, FormatsEnumStruct) {
3294   verifyFormat("enum struct {\n"
3295                "  Zero,\n"
3296                "  One = 1,\n"
3297                "  Two = One + 1,\n"
3298                "  Three = (One + Two),\n"
3299                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3300                "  Five = (One, Two, Three, Four, 5)\n"
3301                "};");
3302   verifyFormat("enum struct Enum {};");
3303   verifyFormat("enum struct {};");
3304   verifyFormat("enum struct X E {} d;");
3305   verifyFormat("enum struct __attribute__((...)) E {} d;");
3306   verifyFormat("enum struct __declspec__((...)) E {} d;");
3307   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3308 }
3309 
3310 TEST_F(FormatTest, FormatsEnumClass) {
3311   verifyFormat("enum class {\n"
3312                "  Zero,\n"
3313                "  One = 1,\n"
3314                "  Two = One + 1,\n"
3315                "  Three = (One + Two),\n"
3316                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3317                "  Five = (One, Two, Three, Four, 5)\n"
3318                "};");
3319   verifyFormat("enum class Enum {};");
3320   verifyFormat("enum class {};");
3321   verifyFormat("enum class X E {} d;");
3322   verifyFormat("enum class __attribute__((...)) E {} d;");
3323   verifyFormat("enum class __declspec__((...)) E {} d;");
3324   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3325 }
3326 
3327 TEST_F(FormatTest, FormatsEnumTypes) {
3328   verifyFormat("enum X : int {\n"
3329                "  A, // Force multiple lines.\n"
3330                "  B\n"
3331                "};");
3332   verifyFormat("enum X : int { A, B };");
3333   verifyFormat("enum X : std::uint32_t { A, B };");
3334 }
3335 
3336 TEST_F(FormatTest, FormatsTypedefEnum) {
3337   FormatStyle Style = getLLVMStyleWithColumns(40);
3338   verifyFormat("typedef enum {} EmptyEnum;");
3339   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3340   verifyFormat("typedef enum {\n"
3341                "  ZERO = 0,\n"
3342                "  ONE = 1,\n"
3343                "  TWO = 2,\n"
3344                "  THREE = 3\n"
3345                "} LongEnum;",
3346                Style);
3347   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3348   Style.BraceWrapping.AfterEnum = true;
3349   verifyFormat("typedef enum {} EmptyEnum;");
3350   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3351   verifyFormat("typedef enum\n"
3352                "{\n"
3353                "  ZERO = 0,\n"
3354                "  ONE = 1,\n"
3355                "  TWO = 2,\n"
3356                "  THREE = 3\n"
3357                "} LongEnum;",
3358                Style);
3359 }
3360 
3361 TEST_F(FormatTest, FormatsNSEnums) {
3362   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3363   verifyGoogleFormat(
3364       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3365   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3366                      "  // Information about someDecentlyLongValue.\n"
3367                      "  someDecentlyLongValue,\n"
3368                      "  // Information about anotherDecentlyLongValue.\n"
3369                      "  anotherDecentlyLongValue,\n"
3370                      "  // Information about aThirdDecentlyLongValue.\n"
3371                      "  aThirdDecentlyLongValue\n"
3372                      "};");
3373   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3374                      "  // Information about someDecentlyLongValue.\n"
3375                      "  someDecentlyLongValue,\n"
3376                      "  // Information about anotherDecentlyLongValue.\n"
3377                      "  anotherDecentlyLongValue,\n"
3378                      "  // Information about aThirdDecentlyLongValue.\n"
3379                      "  aThirdDecentlyLongValue\n"
3380                      "};");
3381   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3382                      "  a = 1,\n"
3383                      "  b = 2,\n"
3384                      "  c = 3,\n"
3385                      "};");
3386   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3387                      "  a = 1,\n"
3388                      "  b = 2,\n"
3389                      "  c = 3,\n"
3390                      "};");
3391   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3392                      "  a = 1,\n"
3393                      "  b = 2,\n"
3394                      "  c = 3,\n"
3395                      "};");
3396   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3397                      "  a = 1,\n"
3398                      "  b = 2,\n"
3399                      "  c = 3,\n"
3400                      "};");
3401 }
3402 
3403 TEST_F(FormatTest, FormatsBitfields) {
3404   verifyFormat("struct Bitfields {\n"
3405                "  unsigned sClass : 8;\n"
3406                "  unsigned ValueKind : 2;\n"
3407                "};");
3408   verifyFormat("struct A {\n"
3409                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3410                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3411                "};");
3412   verifyFormat("struct MyStruct {\n"
3413                "  uchar data;\n"
3414                "  uchar : 8;\n"
3415                "  uchar : 8;\n"
3416                "  uchar other;\n"
3417                "};");
3418   FormatStyle Style = getLLVMStyle();
3419   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3420   verifyFormat("struct Bitfields {\n"
3421                "  unsigned sClass:8;\n"
3422                "  unsigned ValueKind:2;\n"
3423                "  uchar other;\n"
3424                "};",
3425                Style);
3426   verifyFormat("struct A {\n"
3427                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3428                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3429                "};",
3430                Style);
3431   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3432   verifyFormat("struct Bitfields {\n"
3433                "  unsigned sClass :8;\n"
3434                "  unsigned ValueKind :2;\n"
3435                "  uchar other;\n"
3436                "};",
3437                Style);
3438   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3439   verifyFormat("struct Bitfields {\n"
3440                "  unsigned sClass: 8;\n"
3441                "  unsigned ValueKind: 2;\n"
3442                "  uchar other;\n"
3443                "};",
3444                Style);
3445 }
3446 
3447 TEST_F(FormatTest, FormatsNamespaces) {
3448   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3449   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3450 
3451   verifyFormat("namespace some_namespace {\n"
3452                "class A {};\n"
3453                "void f() { f(); }\n"
3454                "}",
3455                LLVMWithNoNamespaceFix);
3456   verifyFormat("namespace N::inline D {\n"
3457                "class A {};\n"
3458                "void f() { f(); }\n"
3459                "}",
3460                LLVMWithNoNamespaceFix);
3461   verifyFormat("namespace N::inline D::E {\n"
3462                "class A {};\n"
3463                "void f() { f(); }\n"
3464                "}",
3465                LLVMWithNoNamespaceFix);
3466   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3467                "class A {};\n"
3468                "void f() { f(); }\n"
3469                "}",
3470                LLVMWithNoNamespaceFix);
3471   verifyFormat("/* something */ namespace some_namespace {\n"
3472                "class A {};\n"
3473                "void f() { f(); }\n"
3474                "}",
3475                LLVMWithNoNamespaceFix);
3476   verifyFormat("namespace {\n"
3477                "class A {};\n"
3478                "void f() { f(); }\n"
3479                "}",
3480                LLVMWithNoNamespaceFix);
3481   verifyFormat("/* something */ namespace {\n"
3482                "class A {};\n"
3483                "void f() { f(); }\n"
3484                "}",
3485                LLVMWithNoNamespaceFix);
3486   verifyFormat("inline namespace X {\n"
3487                "class A {};\n"
3488                "void f() { f(); }\n"
3489                "}",
3490                LLVMWithNoNamespaceFix);
3491   verifyFormat("/* something */ inline namespace X {\n"
3492                "class A {};\n"
3493                "void f() { f(); }\n"
3494                "}",
3495                LLVMWithNoNamespaceFix);
3496   verifyFormat("export namespace X {\n"
3497                "class A {};\n"
3498                "void f() { f(); }\n"
3499                "}",
3500                LLVMWithNoNamespaceFix);
3501   verifyFormat("using namespace some_namespace;\n"
3502                "class A {};\n"
3503                "void f() { f(); }",
3504                LLVMWithNoNamespaceFix);
3505 
3506   // This code is more common than we thought; if we
3507   // layout this correctly the semicolon will go into
3508   // its own line, which is undesirable.
3509   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3510   verifyFormat("namespace {\n"
3511                "class A {};\n"
3512                "};",
3513                LLVMWithNoNamespaceFix);
3514 
3515   verifyFormat("namespace {\n"
3516                "int SomeVariable = 0; // comment\n"
3517                "} // namespace",
3518                LLVMWithNoNamespaceFix);
3519   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3520             "#define HEADER_GUARD\n"
3521             "namespace my_namespace {\n"
3522             "int i;\n"
3523             "} // my_namespace\n"
3524             "#endif // HEADER_GUARD",
3525             format("#ifndef HEADER_GUARD\n"
3526                    " #define HEADER_GUARD\n"
3527                    "   namespace my_namespace {\n"
3528                    "int i;\n"
3529                    "}    // my_namespace\n"
3530                    "#endif    // HEADER_GUARD",
3531                    LLVMWithNoNamespaceFix));
3532 
3533   EXPECT_EQ("namespace A::B {\n"
3534             "class C {};\n"
3535             "}",
3536             format("namespace A::B {\n"
3537                    "class C {};\n"
3538                    "}",
3539                    LLVMWithNoNamespaceFix));
3540 
3541   FormatStyle Style = getLLVMStyle();
3542   Style.NamespaceIndentation = FormatStyle::NI_All;
3543   EXPECT_EQ("namespace out {\n"
3544             "  int i;\n"
3545             "  namespace in {\n"
3546             "    int i;\n"
3547             "  } // namespace in\n"
3548             "} // namespace out",
3549             format("namespace out {\n"
3550                    "int i;\n"
3551                    "namespace in {\n"
3552                    "int i;\n"
3553                    "} // namespace in\n"
3554                    "} // namespace out",
3555                    Style));
3556 
3557   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3558   EXPECT_EQ("namespace out {\n"
3559             "int i;\n"
3560             "namespace in {\n"
3561             "  int i;\n"
3562             "} // namespace in\n"
3563             "} // namespace out",
3564             format("namespace out {\n"
3565                    "int i;\n"
3566                    "namespace in {\n"
3567                    "int i;\n"
3568                    "} // namespace in\n"
3569                    "} // namespace out",
3570                    Style));
3571 
3572   Style.NamespaceIndentation = FormatStyle::NI_None;
3573   verifyFormat("template <class T>\n"
3574                "concept a_concept = X<>;\n"
3575                "namespace B {\n"
3576                "struct b_struct {};\n"
3577                "} // namespace B\n",
3578                Style);
3579   verifyFormat("template <int I> constexpr void foo requires(I == 42) {}\n"
3580                "namespace ns {\n"
3581                "void foo() {}\n"
3582                "} // namespace ns\n",
3583                Style);
3584 }
3585 
3586 TEST_F(FormatTest, NamespaceMacros) {
3587   FormatStyle Style = getLLVMStyle();
3588   Style.NamespaceMacros.push_back("TESTSUITE");
3589 
3590   verifyFormat("TESTSUITE(A) {\n"
3591                "int foo();\n"
3592                "} // TESTSUITE(A)",
3593                Style);
3594 
3595   verifyFormat("TESTSUITE(A, B) {\n"
3596                "int foo();\n"
3597                "} // TESTSUITE(A)",
3598                Style);
3599 
3600   // Properly indent according to NamespaceIndentation style
3601   Style.NamespaceIndentation = FormatStyle::NI_All;
3602   verifyFormat("TESTSUITE(A) {\n"
3603                "  int foo();\n"
3604                "} // TESTSUITE(A)",
3605                Style);
3606   verifyFormat("TESTSUITE(A) {\n"
3607                "  namespace B {\n"
3608                "    int foo();\n"
3609                "  } // namespace B\n"
3610                "} // TESTSUITE(A)",
3611                Style);
3612   verifyFormat("namespace A {\n"
3613                "  TESTSUITE(B) {\n"
3614                "    int foo();\n"
3615                "  } // TESTSUITE(B)\n"
3616                "} // namespace A",
3617                Style);
3618 
3619   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3620   verifyFormat("TESTSUITE(A) {\n"
3621                "TESTSUITE(B) {\n"
3622                "  int foo();\n"
3623                "} // TESTSUITE(B)\n"
3624                "} // TESTSUITE(A)",
3625                Style);
3626   verifyFormat("TESTSUITE(A) {\n"
3627                "namespace B {\n"
3628                "  int foo();\n"
3629                "} // namespace B\n"
3630                "} // TESTSUITE(A)",
3631                Style);
3632   verifyFormat("namespace A {\n"
3633                "TESTSUITE(B) {\n"
3634                "  int foo();\n"
3635                "} // TESTSUITE(B)\n"
3636                "} // namespace A",
3637                Style);
3638 
3639   // Properly merge namespace-macros blocks in CompactNamespaces mode
3640   Style.NamespaceIndentation = FormatStyle::NI_None;
3641   Style.CompactNamespaces = true;
3642   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
3643                "}} // TESTSUITE(A::B)",
3644                Style);
3645 
3646   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3647             "}} // TESTSUITE(out::in)",
3648             format("TESTSUITE(out) {\n"
3649                    "TESTSUITE(in) {\n"
3650                    "} // TESTSUITE(in)\n"
3651                    "} // TESTSUITE(out)",
3652                    Style));
3653 
3654   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3655             "}} // TESTSUITE(out::in)",
3656             format("TESTSUITE(out) {\n"
3657                    "TESTSUITE(in) {\n"
3658                    "} // TESTSUITE(in)\n"
3659                    "} // TESTSUITE(out)",
3660                    Style));
3661 
3662   // Do not merge different namespaces/macros
3663   EXPECT_EQ("namespace out {\n"
3664             "TESTSUITE(in) {\n"
3665             "} // TESTSUITE(in)\n"
3666             "} // namespace out",
3667             format("namespace out {\n"
3668                    "TESTSUITE(in) {\n"
3669                    "} // TESTSUITE(in)\n"
3670                    "} // namespace out",
3671                    Style));
3672   EXPECT_EQ("TESTSUITE(out) {\n"
3673             "namespace in {\n"
3674             "} // namespace in\n"
3675             "} // TESTSUITE(out)",
3676             format("TESTSUITE(out) {\n"
3677                    "namespace in {\n"
3678                    "} // namespace in\n"
3679                    "} // TESTSUITE(out)",
3680                    Style));
3681   Style.NamespaceMacros.push_back("FOOBAR");
3682   EXPECT_EQ("TESTSUITE(out) {\n"
3683             "FOOBAR(in) {\n"
3684             "} // FOOBAR(in)\n"
3685             "} // TESTSUITE(out)",
3686             format("TESTSUITE(out) {\n"
3687                    "FOOBAR(in) {\n"
3688                    "} // FOOBAR(in)\n"
3689                    "} // TESTSUITE(out)",
3690                    Style));
3691 }
3692 
3693 TEST_F(FormatTest, FormatsCompactNamespaces) {
3694   FormatStyle Style = getLLVMStyle();
3695   Style.CompactNamespaces = true;
3696   Style.NamespaceMacros.push_back("TESTSUITE");
3697 
3698   verifyFormat("namespace A { namespace B {\n"
3699                "}} // namespace A::B",
3700                Style);
3701 
3702   EXPECT_EQ("namespace out { namespace in {\n"
3703             "}} // namespace out::in",
3704             format("namespace out {\n"
3705                    "namespace in {\n"
3706                    "} // namespace in\n"
3707                    "} // namespace out",
3708                    Style));
3709 
3710   // Only namespaces which have both consecutive opening and end get compacted
3711   EXPECT_EQ("namespace out {\n"
3712             "namespace in1 {\n"
3713             "} // namespace in1\n"
3714             "namespace in2 {\n"
3715             "} // namespace in2\n"
3716             "} // namespace out",
3717             format("namespace out {\n"
3718                    "namespace in1 {\n"
3719                    "} // namespace in1\n"
3720                    "namespace in2 {\n"
3721                    "} // namespace in2\n"
3722                    "} // namespace out",
3723                    Style));
3724 
3725   EXPECT_EQ("namespace out {\n"
3726             "int i;\n"
3727             "namespace in {\n"
3728             "int j;\n"
3729             "} // namespace in\n"
3730             "int k;\n"
3731             "} // namespace out",
3732             format("namespace out { int i;\n"
3733                    "namespace in { int j; } // namespace in\n"
3734                    "int k; } // namespace out",
3735                    Style));
3736 
3737   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
3738             "}}} // namespace A::B::C\n",
3739             format("namespace A { namespace B {\n"
3740                    "namespace C {\n"
3741                    "}} // namespace B::C\n"
3742                    "} // namespace A\n",
3743                    Style));
3744 
3745   Style.ColumnLimit = 40;
3746   EXPECT_EQ("namespace aaaaaaaaaa {\n"
3747             "namespace bbbbbbbbbb {\n"
3748             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
3749             format("namespace aaaaaaaaaa {\n"
3750                    "namespace bbbbbbbbbb {\n"
3751                    "} // namespace bbbbbbbbbb\n"
3752                    "} // namespace aaaaaaaaaa",
3753                    Style));
3754 
3755   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
3756             "namespace cccccc {\n"
3757             "}}} // namespace aaaaaa::bbbbbb::cccccc",
3758             format("namespace aaaaaa {\n"
3759                    "namespace bbbbbb {\n"
3760                    "namespace cccccc {\n"
3761                    "} // namespace cccccc\n"
3762                    "} // namespace bbbbbb\n"
3763                    "} // namespace aaaaaa",
3764                    Style));
3765   Style.ColumnLimit = 80;
3766 
3767   // Extra semicolon after 'inner' closing brace prevents merging
3768   EXPECT_EQ("namespace out { namespace in {\n"
3769             "}; } // namespace out::in",
3770             format("namespace out {\n"
3771                    "namespace in {\n"
3772                    "}; // namespace in\n"
3773                    "} // namespace out",
3774                    Style));
3775 
3776   // Extra semicolon after 'outer' closing brace is conserved
3777   EXPECT_EQ("namespace out { namespace in {\n"
3778             "}}; // namespace out::in",
3779             format("namespace out {\n"
3780                    "namespace in {\n"
3781                    "} // namespace in\n"
3782                    "}; // namespace out",
3783                    Style));
3784 
3785   Style.NamespaceIndentation = FormatStyle::NI_All;
3786   EXPECT_EQ("namespace out { namespace in {\n"
3787             "  int i;\n"
3788             "}} // namespace out::in",
3789             format("namespace out {\n"
3790                    "namespace in {\n"
3791                    "int i;\n"
3792                    "} // namespace in\n"
3793                    "} // namespace out",
3794                    Style));
3795   EXPECT_EQ("namespace out { namespace mid {\n"
3796             "  namespace in {\n"
3797             "    int j;\n"
3798             "  } // namespace in\n"
3799             "  int k;\n"
3800             "}} // namespace out::mid",
3801             format("namespace out { namespace mid {\n"
3802                    "namespace in { int j; } // namespace in\n"
3803                    "int k; }} // namespace out::mid",
3804                    Style));
3805 
3806   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3807   EXPECT_EQ("namespace out { namespace in {\n"
3808             "  int i;\n"
3809             "}} // namespace out::in",
3810             format("namespace out {\n"
3811                    "namespace in {\n"
3812                    "int i;\n"
3813                    "} // namespace in\n"
3814                    "} // namespace out",
3815                    Style));
3816   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
3817             "  int i;\n"
3818             "}}} // namespace out::mid::in",
3819             format("namespace out {\n"
3820                    "namespace mid {\n"
3821                    "namespace in {\n"
3822                    "int i;\n"
3823                    "} // namespace in\n"
3824                    "} // namespace mid\n"
3825                    "} // namespace out",
3826                    Style));
3827 }
3828 
3829 TEST_F(FormatTest, FormatsExternC) {
3830   verifyFormat("extern \"C\" {\nint a;");
3831   verifyFormat("extern \"C\" {}");
3832   verifyFormat("extern \"C\" {\n"
3833                "int foo();\n"
3834                "}");
3835   verifyFormat("extern \"C\" int foo() {}");
3836   verifyFormat("extern \"C\" int foo();");
3837   verifyFormat("extern \"C\" int foo() {\n"
3838                "  int i = 42;\n"
3839                "  return i;\n"
3840                "}");
3841 
3842   FormatStyle Style = getLLVMStyle();
3843   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3844   Style.BraceWrapping.AfterFunction = true;
3845   verifyFormat("extern \"C\" int foo() {}", Style);
3846   verifyFormat("extern \"C\" int foo();", Style);
3847   verifyFormat("extern \"C\" int foo()\n"
3848                "{\n"
3849                "  int i = 42;\n"
3850                "  return i;\n"
3851                "}",
3852                Style);
3853 
3854   Style.BraceWrapping.AfterExternBlock = true;
3855   Style.BraceWrapping.SplitEmptyRecord = false;
3856   verifyFormat("extern \"C\"\n"
3857                "{}",
3858                Style);
3859   verifyFormat("extern \"C\"\n"
3860                "{\n"
3861                "  int foo();\n"
3862                "}",
3863                Style);
3864 }
3865 
3866 TEST_F(FormatTest, IndentExternBlockStyle) {
3867   FormatStyle Style = getLLVMStyle();
3868   Style.IndentWidth = 2;
3869 
3870   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3871   verifyFormat("extern \"C\" { /*9*/\n"
3872                "}",
3873                Style);
3874   verifyFormat("extern \"C\" {\n"
3875                "  int foo10();\n"
3876                "}",
3877                Style);
3878 
3879   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
3880   verifyFormat("extern \"C\" { /*11*/\n"
3881                "}",
3882                Style);
3883   verifyFormat("extern \"C\" {\n"
3884                "int foo12();\n"
3885                "}",
3886                Style);
3887 
3888   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3889   Style.BraceWrapping.AfterExternBlock = true;
3890   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3891   verifyFormat("extern \"C\"\n"
3892                "{ /*13*/\n"
3893                "}",
3894                Style);
3895   verifyFormat("extern \"C\"\n{\n"
3896                "  int foo14();\n"
3897                "}",
3898                Style);
3899 
3900   Style.BraceWrapping.AfterExternBlock = false;
3901   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
3902   verifyFormat("extern \"C\" { /*15*/\n"
3903                "}",
3904                Style);
3905   verifyFormat("extern \"C\" {\n"
3906                "int foo16();\n"
3907                "}",
3908                Style);
3909 
3910   Style.BraceWrapping.AfterExternBlock = true;
3911   verifyFormat("extern \"C\"\n"
3912                "{ /*13*/\n"
3913                "}",
3914                Style);
3915   verifyFormat("extern \"C\"\n"
3916                "{\n"
3917                "int foo14();\n"
3918                "}",
3919                Style);
3920 
3921   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3922   verifyFormat("extern \"C\"\n"
3923                "{ /*13*/\n"
3924                "}",
3925                Style);
3926   verifyFormat("extern \"C\"\n"
3927                "{\n"
3928                "  int foo14();\n"
3929                "}",
3930                Style);
3931 }
3932 
3933 TEST_F(FormatTest, FormatsInlineASM) {
3934   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
3935   verifyFormat("asm(\"nop\" ::: \"memory\");");
3936   verifyFormat(
3937       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
3938       "    \"cpuid\\n\\t\"\n"
3939       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
3940       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
3941       "    : \"a\"(value));");
3942   EXPECT_EQ(
3943       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
3944       "  __asm {\n"
3945       "        mov     edx,[that] // vtable in edx\n"
3946       "        mov     eax,methodIndex\n"
3947       "        call    [edx][eax*4] // stdcall\n"
3948       "  }\n"
3949       "}",
3950       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
3951              "    __asm {\n"
3952              "        mov     edx,[that] // vtable in edx\n"
3953              "        mov     eax,methodIndex\n"
3954              "        call    [edx][eax*4] // stdcall\n"
3955              "    }\n"
3956              "}"));
3957   EXPECT_EQ("_asm {\n"
3958             "  xor eax, eax;\n"
3959             "  cpuid;\n"
3960             "}",
3961             format("_asm {\n"
3962                    "  xor eax, eax;\n"
3963                    "  cpuid;\n"
3964                    "}"));
3965   verifyFormat("void function() {\n"
3966                "  // comment\n"
3967                "  asm(\"\");\n"
3968                "}");
3969   EXPECT_EQ("__asm {\n"
3970             "}\n"
3971             "int i;",
3972             format("__asm   {\n"
3973                    "}\n"
3974                    "int   i;"));
3975 }
3976 
3977 TEST_F(FormatTest, FormatTryCatch) {
3978   verifyFormat("try {\n"
3979                "  throw a * b;\n"
3980                "} catch (int a) {\n"
3981                "  // Do nothing.\n"
3982                "} catch (...) {\n"
3983                "  exit(42);\n"
3984                "}");
3985 
3986   // Function-level try statements.
3987   verifyFormat("int f() try { return 4; } catch (...) {\n"
3988                "  return 5;\n"
3989                "}");
3990   verifyFormat("class A {\n"
3991                "  int a;\n"
3992                "  A() try : a(0) {\n"
3993                "  } catch (...) {\n"
3994                "    throw;\n"
3995                "  }\n"
3996                "};\n");
3997   verifyFormat("class A {\n"
3998                "  int a;\n"
3999                "  A() try : a(0), b{1} {\n"
4000                "  } catch (...) {\n"
4001                "    throw;\n"
4002                "  }\n"
4003                "};\n");
4004   verifyFormat("class A {\n"
4005                "  int a;\n"
4006                "  A() try : a(0), b{1}, c{2} {\n"
4007                "  } catch (...) {\n"
4008                "    throw;\n"
4009                "  }\n"
4010                "};\n");
4011   verifyFormat("class A {\n"
4012                "  int a;\n"
4013                "  A() try : a(0), b{1}, c{2} {\n"
4014                "    { // New scope.\n"
4015                "    }\n"
4016                "  } catch (...) {\n"
4017                "    throw;\n"
4018                "  }\n"
4019                "};\n");
4020 
4021   // Incomplete try-catch blocks.
4022   verifyIncompleteFormat("try {} catch (");
4023 }
4024 
4025 TEST_F(FormatTest, FormatTryAsAVariable) {
4026   verifyFormat("int try;");
4027   verifyFormat("int try, size;");
4028   verifyFormat("try = foo();");
4029   verifyFormat("if (try < size) {\n  return true;\n}");
4030 
4031   verifyFormat("int catch;");
4032   verifyFormat("int catch, size;");
4033   verifyFormat("catch = foo();");
4034   verifyFormat("if (catch < size) {\n  return true;\n}");
4035 
4036   FormatStyle Style = getLLVMStyle();
4037   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4038   Style.BraceWrapping.AfterFunction = true;
4039   Style.BraceWrapping.BeforeCatch = true;
4040   verifyFormat("try {\n"
4041                "  int bar = 1;\n"
4042                "}\n"
4043                "catch (...) {\n"
4044                "  int bar = 1;\n"
4045                "}",
4046                Style);
4047   verifyFormat("#if NO_EX\n"
4048                "try\n"
4049                "#endif\n"
4050                "{\n"
4051                "}\n"
4052                "#if NO_EX\n"
4053                "catch (...) {\n"
4054                "}",
4055                Style);
4056   verifyFormat("try /* abc */ {\n"
4057                "  int bar = 1;\n"
4058                "}\n"
4059                "catch (...) {\n"
4060                "  int bar = 1;\n"
4061                "}",
4062                Style);
4063   verifyFormat("try\n"
4064                "// abc\n"
4065                "{\n"
4066                "  int bar = 1;\n"
4067                "}\n"
4068                "catch (...) {\n"
4069                "  int bar = 1;\n"
4070                "}",
4071                Style);
4072 }
4073 
4074 TEST_F(FormatTest, FormatSEHTryCatch) {
4075   verifyFormat("__try {\n"
4076                "  int a = b * c;\n"
4077                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4078                "  // Do nothing.\n"
4079                "}");
4080 
4081   verifyFormat("__try {\n"
4082                "  int a = b * c;\n"
4083                "} __finally {\n"
4084                "  // Do nothing.\n"
4085                "}");
4086 
4087   verifyFormat("DEBUG({\n"
4088                "  __try {\n"
4089                "  } __finally {\n"
4090                "  }\n"
4091                "});\n");
4092 }
4093 
4094 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4095   verifyFormat("try {\n"
4096                "  f();\n"
4097                "} catch {\n"
4098                "  g();\n"
4099                "}");
4100   verifyFormat("try {\n"
4101                "  f();\n"
4102                "} catch (A a) MACRO(x) {\n"
4103                "  g();\n"
4104                "} catch (B b) MACRO(x) {\n"
4105                "  g();\n"
4106                "}");
4107 }
4108 
4109 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4110   FormatStyle Style = getLLVMStyle();
4111   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4112                           FormatStyle::BS_WebKit}) {
4113     Style.BreakBeforeBraces = BraceStyle;
4114     verifyFormat("try {\n"
4115                  "  // something\n"
4116                  "} catch (...) {\n"
4117                  "  // something\n"
4118                  "}",
4119                  Style);
4120   }
4121   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4122   verifyFormat("try {\n"
4123                "  // something\n"
4124                "}\n"
4125                "catch (...) {\n"
4126                "  // something\n"
4127                "}",
4128                Style);
4129   verifyFormat("__try {\n"
4130                "  // something\n"
4131                "}\n"
4132                "__finally {\n"
4133                "  // something\n"
4134                "}",
4135                Style);
4136   verifyFormat("@try {\n"
4137                "  // something\n"
4138                "}\n"
4139                "@finally {\n"
4140                "  // something\n"
4141                "}",
4142                Style);
4143   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4144   verifyFormat("try\n"
4145                "{\n"
4146                "  // something\n"
4147                "}\n"
4148                "catch (...)\n"
4149                "{\n"
4150                "  // something\n"
4151                "}",
4152                Style);
4153   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4154   verifyFormat("try\n"
4155                "  {\n"
4156                "  // something white\n"
4157                "  }\n"
4158                "catch (...)\n"
4159                "  {\n"
4160                "  // something white\n"
4161                "  }",
4162                Style);
4163   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4164   verifyFormat("try\n"
4165                "  {\n"
4166                "    // something\n"
4167                "  }\n"
4168                "catch (...)\n"
4169                "  {\n"
4170                "    // something\n"
4171                "  }",
4172                Style);
4173   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4174   Style.BraceWrapping.BeforeCatch = true;
4175   verifyFormat("try {\n"
4176                "  // something\n"
4177                "}\n"
4178                "catch (...) {\n"
4179                "  // something\n"
4180                "}",
4181                Style);
4182 }
4183 
4184 TEST_F(FormatTest, StaticInitializers) {
4185   verifyFormat("static SomeClass SC = {1, 'a'};");
4186 
4187   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4188                "    100000000, "
4189                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4190 
4191   // Here, everything other than the "}" would fit on a line.
4192   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4193                "    10000000000000000000000000};");
4194   EXPECT_EQ("S s = {a,\n"
4195             "\n"
4196             "       b};",
4197             format("S s = {\n"
4198                    "  a,\n"
4199                    "\n"
4200                    "  b\n"
4201                    "};"));
4202 
4203   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4204   // line. However, the formatting looks a bit off and this probably doesn't
4205   // happen often in practice.
4206   verifyFormat("static int Variable[1] = {\n"
4207                "    {1000000000000000000000000000000000000}};",
4208                getLLVMStyleWithColumns(40));
4209 }
4210 
4211 TEST_F(FormatTest, DesignatedInitializers) {
4212   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4213   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4214                "                    .bbbbbbbbbb = 2,\n"
4215                "                    .cccccccccc = 3,\n"
4216                "                    .dddddddddd = 4,\n"
4217                "                    .eeeeeeeeee = 5};");
4218   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4219                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4220                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4221                "    .ccccccccccccccccccccccccccc = 3,\n"
4222                "    .ddddddddddddddddddddddddddd = 4,\n"
4223                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4224 
4225   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4226 
4227   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4228   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4229                "                    [2] = bbbbbbbbbb,\n"
4230                "                    [3] = cccccccccc,\n"
4231                "                    [4] = dddddddddd,\n"
4232                "                    [5] = eeeeeeeeee};");
4233   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4234                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4235                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4236                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4237                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4238                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4239 }
4240 
4241 TEST_F(FormatTest, NestedStaticInitializers) {
4242   verifyFormat("static A x = {{{}}};\n");
4243   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4244                "               {init1, init2, init3, init4}}};",
4245                getLLVMStyleWithColumns(50));
4246 
4247   verifyFormat("somes 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                getLLVMStyleWithColumns(60));
4252   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4253                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4254                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4255                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4256   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4257                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4258                "rect.fTop}};");
4259 
4260   verifyFormat(
4261       "SomeArrayOfSomeType a = {\n"
4262       "    {{1, 2, 3},\n"
4263       "     {1, 2, 3},\n"
4264       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4265       "      333333333333333333333333333333},\n"
4266       "     {1, 2, 3},\n"
4267       "     {1, 2, 3}}};");
4268   verifyFormat(
4269       "SomeArrayOfSomeType a = {\n"
4270       "    {{1, 2, 3}},\n"
4271       "    {{1, 2, 3}},\n"
4272       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4273       "      333333333333333333333333333333}},\n"
4274       "    {{1, 2, 3}},\n"
4275       "    {{1, 2, 3}}};");
4276 
4277   verifyFormat("struct {\n"
4278                "  unsigned bit;\n"
4279                "  const char *const name;\n"
4280                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4281                "                 {kOsWin, \"Windows\"},\n"
4282                "                 {kOsLinux, \"Linux\"},\n"
4283                "                 {kOsCrOS, \"Chrome OS\"}};");
4284   verifyFormat("struct {\n"
4285                "  unsigned bit;\n"
4286                "  const char *const name;\n"
4287                "} kBitsToOs[] = {\n"
4288                "    {kOsMac, \"Mac\"},\n"
4289                "    {kOsWin, \"Windows\"},\n"
4290                "    {kOsLinux, \"Linux\"},\n"
4291                "    {kOsCrOS, \"Chrome OS\"},\n"
4292                "};");
4293 }
4294 
4295 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4296   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4297                "                      \\\n"
4298                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4299 }
4300 
4301 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4302   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4303                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4304 
4305   // Do break defaulted and deleted functions.
4306   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4307                "    default;",
4308                getLLVMStyleWithColumns(40));
4309   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4310                "    delete;",
4311                getLLVMStyleWithColumns(40));
4312 }
4313 
4314 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4315   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4316                getLLVMStyleWithColumns(40));
4317   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4318                getLLVMStyleWithColumns(40));
4319   EXPECT_EQ("#define Q                              \\\n"
4320             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4321             "  \"aaaaaaaa.cpp\"",
4322             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4323                    getLLVMStyleWithColumns(40)));
4324 }
4325 
4326 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4327   EXPECT_EQ("# 123 \"A string literal\"",
4328             format("   #     123    \"A string literal\""));
4329 }
4330 
4331 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4332   EXPECT_EQ("#;", format("#;"));
4333   verifyFormat("#\n;\n;\n;");
4334 }
4335 
4336 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4337   EXPECT_EQ("#line 42 \"test\"\n",
4338             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4339   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4340                                     getLLVMStyleWithColumns(12)));
4341 }
4342 
4343 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4344   EXPECT_EQ("#line 42 \"test\"",
4345             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4346   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4347 }
4348 
4349 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4350   verifyFormat("#define A \\x20");
4351   verifyFormat("#define A \\ x20");
4352   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4353   verifyFormat("#define A ''");
4354   verifyFormat("#define A ''qqq");
4355   verifyFormat("#define A `qqq");
4356   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4357   EXPECT_EQ("const char *c = STRINGIFY(\n"
4358             "\\na : b);",
4359             format("const char * c = STRINGIFY(\n"
4360                    "\\na : b);"));
4361 
4362   verifyFormat("a\r\\");
4363   verifyFormat("a\v\\");
4364   verifyFormat("a\f\\");
4365 }
4366 
4367 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4368   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4369   style.IndentWidth = 4;
4370   style.PPIndentWidth = 1;
4371 
4372   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4373   verifyFormat("#ifdef __linux__\n"
4374                "void foo() {\n"
4375                "    int x = 0;\n"
4376                "}\n"
4377                "#define FOO\n"
4378                "#endif\n"
4379                "void bar() {\n"
4380                "    int y = 0;\n"
4381                "}\n",
4382                style);
4383 
4384   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4385   verifyFormat("#ifdef __linux__\n"
4386                "void foo() {\n"
4387                "    int x = 0;\n"
4388                "}\n"
4389                "# define FOO foo\n"
4390                "#endif\n"
4391                "void bar() {\n"
4392                "    int y = 0;\n"
4393                "}\n",
4394                style);
4395 
4396   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4397   verifyFormat("#ifdef __linux__\n"
4398                "void foo() {\n"
4399                "    int x = 0;\n"
4400                "}\n"
4401                " #define FOO foo\n"
4402                "#endif\n"
4403                "void bar() {\n"
4404                "    int y = 0;\n"
4405                "}\n",
4406                style);
4407 }
4408 
4409 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4410   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4411   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4412   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4413   // FIXME: We never break before the macro name.
4414   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4415 
4416   verifyFormat("#define A A\n#define A A");
4417   verifyFormat("#define A(X) A\n#define A A");
4418 
4419   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4420   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4421 }
4422 
4423 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4424   EXPECT_EQ("// somecomment\n"
4425             "#include \"a.h\"\n"
4426             "#define A(  \\\n"
4427             "    A, B)\n"
4428             "#include \"b.h\"\n"
4429             "// somecomment\n",
4430             format("  // somecomment\n"
4431                    "  #include \"a.h\"\n"
4432                    "#define A(A,\\\n"
4433                    "    B)\n"
4434                    "    #include \"b.h\"\n"
4435                    " // somecomment\n",
4436                    getLLVMStyleWithColumns(13)));
4437 }
4438 
4439 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4440 
4441 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4442   EXPECT_EQ("#define A    \\\n"
4443             "  c;         \\\n"
4444             "  e;\n"
4445             "f;",
4446             format("#define A c; e;\n"
4447                    "f;",
4448                    getLLVMStyleWithColumns(14)));
4449 }
4450 
4451 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4452 
4453 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4454   EXPECT_EQ("int x,\n"
4455             "#define A\n"
4456             "    y;",
4457             format("int x,\n#define A\ny;"));
4458 }
4459 
4460 TEST_F(FormatTest, HashInMacroDefinition) {
4461   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4462   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
4463   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
4464   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
4465   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
4466   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
4467   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
4468   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
4469   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4470   verifyFormat("#define A  \\\n"
4471                "  {        \\\n"
4472                "    f(#c); \\\n"
4473                "  }",
4474                getLLVMStyleWithColumns(11));
4475 
4476   verifyFormat("#define A(X)         \\\n"
4477                "  void function##X()",
4478                getLLVMStyleWithColumns(22));
4479 
4480   verifyFormat("#define A(a, b, c)   \\\n"
4481                "  void a##b##c()",
4482                getLLVMStyleWithColumns(22));
4483 
4484   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4485 }
4486 
4487 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4488   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4489   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4490 
4491   FormatStyle Style = getLLVMStyle();
4492   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4493   verifyFormat("#define true ((foo)1)", Style);
4494   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4495   verifyFormat("#define false((foo)0)", Style);
4496 }
4497 
4498 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4499   EXPECT_EQ("#define A b;", format("#define A \\\n"
4500                                    "          \\\n"
4501                                    "  b;",
4502                                    getLLVMStyleWithColumns(25)));
4503   EXPECT_EQ("#define A \\\n"
4504             "          \\\n"
4505             "  a;      \\\n"
4506             "  b;",
4507             format("#define A \\\n"
4508                    "          \\\n"
4509                    "  a;      \\\n"
4510                    "  b;",
4511                    getLLVMStyleWithColumns(11)));
4512   EXPECT_EQ("#define A \\\n"
4513             "  a;      \\\n"
4514             "          \\\n"
4515             "  b;",
4516             format("#define A \\\n"
4517                    "  a;      \\\n"
4518                    "          \\\n"
4519                    "  b;",
4520                    getLLVMStyleWithColumns(11)));
4521 }
4522 
4523 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
4524   verifyIncompleteFormat("#define A :");
4525   verifyFormat("#define SOMECASES  \\\n"
4526                "  case 1:          \\\n"
4527                "  case 2\n",
4528                getLLVMStyleWithColumns(20));
4529   verifyFormat("#define MACRO(a) \\\n"
4530                "  if (a)         \\\n"
4531                "    f();         \\\n"
4532                "  else           \\\n"
4533                "    g()",
4534                getLLVMStyleWithColumns(18));
4535   verifyFormat("#define A template <typename T>");
4536   verifyIncompleteFormat("#define STR(x) #x\n"
4537                          "f(STR(this_is_a_string_literal{));");
4538   verifyFormat("#pragma omp threadprivate( \\\n"
4539                "    y)), // expected-warning",
4540                getLLVMStyleWithColumns(28));
4541   verifyFormat("#d, = };");
4542   verifyFormat("#if \"a");
4543   verifyIncompleteFormat("({\n"
4544                          "#define b     \\\n"
4545                          "  }           \\\n"
4546                          "  a\n"
4547                          "a",
4548                          getLLVMStyleWithColumns(15));
4549   verifyFormat("#define A     \\\n"
4550                "  {           \\\n"
4551                "    {\n"
4552                "#define B     \\\n"
4553                "  }           \\\n"
4554                "  }",
4555                getLLVMStyleWithColumns(15));
4556   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
4557   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
4558   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
4559   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
4560 }
4561 
4562 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
4563   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
4564   EXPECT_EQ("class A : public QObject {\n"
4565             "  Q_OBJECT\n"
4566             "\n"
4567             "  A() {}\n"
4568             "};",
4569             format("class A  :  public QObject {\n"
4570                    "     Q_OBJECT\n"
4571                    "\n"
4572                    "  A() {\n}\n"
4573                    "}  ;"));
4574   EXPECT_EQ("MACRO\n"
4575             "/*static*/ int i;",
4576             format("MACRO\n"
4577                    " /*static*/ int   i;"));
4578   EXPECT_EQ("SOME_MACRO\n"
4579             "namespace {\n"
4580             "void f();\n"
4581             "} // namespace",
4582             format("SOME_MACRO\n"
4583                    "  namespace    {\n"
4584                    "void   f(  );\n"
4585                    "} // namespace"));
4586   // Only if the identifier contains at least 5 characters.
4587   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
4588   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
4589   // Only if everything is upper case.
4590   EXPECT_EQ("class A : public QObject {\n"
4591             "  Q_Object A() {}\n"
4592             "};",
4593             format("class A  :  public QObject {\n"
4594                    "     Q_Object\n"
4595                    "  A() {\n}\n"
4596                    "}  ;"));
4597 
4598   // Only if the next line can actually start an unwrapped line.
4599   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
4600             format("SOME_WEIRD_LOG_MACRO\n"
4601                    "<< SomeThing;"));
4602 
4603   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
4604                "(n, buffers))\n",
4605                getChromiumStyle(FormatStyle::LK_Cpp));
4606 
4607   // See PR41483
4608   EXPECT_EQ("/**/ FOO(a)\n"
4609             "FOO(b)",
4610             format("/**/ FOO(a)\n"
4611                    "FOO(b)"));
4612 }
4613 
4614 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
4615   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4616             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4617             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4618             "class X {};\n"
4619             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4620             "int *createScopDetectionPass() { return 0; }",
4621             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4622                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4623                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4624                    "  class X {};\n"
4625                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4626                    "  int *createScopDetectionPass() { return 0; }"));
4627   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
4628   // braces, so that inner block is indented one level more.
4629   EXPECT_EQ("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             format("int q() {\n"
4635                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4636                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4637                    "  IPC_END_MESSAGE_MAP()\n"
4638                    "}"));
4639 
4640   // Same inside macros.
4641   EXPECT_EQ("#define LIST(L) \\\n"
4642             "  L(A)          \\\n"
4643             "  L(B)          \\\n"
4644             "  L(C)",
4645             format("#define LIST(L) \\\n"
4646                    "  L(A) \\\n"
4647                    "  L(B) \\\n"
4648                    "  L(C)",
4649                    getGoogleStyle()));
4650 
4651   // These must not be recognized as macros.
4652   EXPECT_EQ("int q() {\n"
4653             "  f(x);\n"
4654             "  f(x) {}\n"
4655             "  f(x)->g();\n"
4656             "  f(x)->*g();\n"
4657             "  f(x).g();\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) &= x;\n"
4665             "  f(x) |= x;\n"
4666             "  f(x) ^= x;\n"
4667             "  f(x) >>= x;\n"
4668             "  f(x) <<= x;\n"
4669             "  f(x)[y].z();\n"
4670             "  LOG(INFO) << x;\n"
4671             "  ifstream(x) >> x;\n"
4672             "}\n",
4673             format("int q() {\n"
4674                    "  f(x)\n;\n"
4675                    "  f(x)\n {}\n"
4676                    "  f(x)\n->g();\n"
4677                    "  f(x)\n->*g();\n"
4678                    "  f(x)\n.g();\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 &= x;\n"
4686                    "  f(x)\n |= x;\n"
4687                    "  f(x)\n ^= x;\n"
4688                    "  f(x)\n >>= x;\n"
4689                    "  f(x)\n <<= x;\n"
4690                    "  f(x)\n[y].z();\n"
4691                    "  LOG(INFO)\n << x;\n"
4692                    "  ifstream(x)\n >> x;\n"
4693                    "}\n"));
4694   EXPECT_EQ("int q() {\n"
4695             "  F(x)\n"
4696             "  if (1) {\n"
4697             "  }\n"
4698             "  F(x)\n"
4699             "  while (1) {\n"
4700             "  }\n"
4701             "  F(x)\n"
4702             "  G(x);\n"
4703             "  F(x)\n"
4704             "  try {\n"
4705             "    Q();\n"
4706             "  } catch (...) {\n"
4707             "  }\n"
4708             "}\n",
4709             format("int q() {\n"
4710                    "F(x)\n"
4711                    "if (1) {}\n"
4712                    "F(x)\n"
4713                    "while (1) {}\n"
4714                    "F(x)\n"
4715                    "G(x);\n"
4716                    "F(x)\n"
4717                    "try { Q(); } catch (...) {}\n"
4718                    "}\n"));
4719   EXPECT_EQ("class A {\n"
4720             "  A() : t(0) {}\n"
4721             "  A(int i) noexcept() : {}\n"
4722             "  A(X x)\n" // FIXME: function-level try blocks are broken.
4723             "  try : t(0) {\n"
4724             "  } catch (...) {\n"
4725             "  }\n"
4726             "};",
4727             format("class A {\n"
4728                    "  A()\n : t(0) {}\n"
4729                    "  A(int i)\n noexcept() : {}\n"
4730                    "  A(X x)\n"
4731                    "  try : t(0) {} catch (...) {}\n"
4732                    "};"));
4733   FormatStyle Style = getLLVMStyle();
4734   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4735   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
4736   Style.BraceWrapping.AfterFunction = true;
4737   EXPECT_EQ("void f()\n"
4738             "try\n"
4739             "{\n"
4740             "}",
4741             format("void f() try {\n"
4742                    "}",
4743                    Style));
4744   EXPECT_EQ("class SomeClass {\n"
4745             "public:\n"
4746             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4747             "};",
4748             format("class SomeClass {\n"
4749                    "public:\n"
4750                    "  SomeClass()\n"
4751                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4752                    "};"));
4753   EXPECT_EQ("class SomeClass {\n"
4754             "public:\n"
4755             "  SomeClass()\n"
4756             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4757             "};",
4758             format("class SomeClass {\n"
4759                    "public:\n"
4760                    "  SomeClass()\n"
4761                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4762                    "};",
4763                    getLLVMStyleWithColumns(40)));
4764 
4765   verifyFormat("MACRO(>)");
4766 
4767   // Some macros contain an implicit semicolon.
4768   Style = getLLVMStyle();
4769   Style.StatementMacros.push_back("FOO");
4770   verifyFormat("FOO(a) int b = 0;");
4771   verifyFormat("FOO(a)\n"
4772                "int b = 0;",
4773                Style);
4774   verifyFormat("FOO(a);\n"
4775                "int b = 0;",
4776                Style);
4777   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
4778                "int b = 0;",
4779                Style);
4780   verifyFormat("FOO()\n"
4781                "int b = 0;",
4782                Style);
4783   verifyFormat("FOO\n"
4784                "int b = 0;",
4785                Style);
4786   verifyFormat("void f() {\n"
4787                "  FOO(a)\n"
4788                "  return a;\n"
4789                "}",
4790                Style);
4791   verifyFormat("FOO(a)\n"
4792                "FOO(b)",
4793                Style);
4794   verifyFormat("int a = 0;\n"
4795                "FOO(b)\n"
4796                "int c = 0;",
4797                Style);
4798   verifyFormat("int a = 0;\n"
4799                "int x = FOO(a)\n"
4800                "int b = 0;",
4801                Style);
4802   verifyFormat("void foo(int a) { FOO(a) }\n"
4803                "uint32_t bar() {}",
4804                Style);
4805 }
4806 
4807 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
4808   verifyFormat("#define A \\\n"
4809                "  f({     \\\n"
4810                "    g();  \\\n"
4811                "  });",
4812                getLLVMStyleWithColumns(11));
4813 }
4814 
4815 TEST_F(FormatTest, IndentPreprocessorDirectives) {
4816   FormatStyle Style = getLLVMStyleWithColumns(40);
4817   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
4818   verifyFormat("#ifdef _WIN32\n"
4819                "#define A 0\n"
4820                "#ifdef VAR2\n"
4821                "#define B 1\n"
4822                "#include <someheader.h>\n"
4823                "#define MACRO                          \\\n"
4824                "  some_very_long_func_aaaaaaaaaa();\n"
4825                "#endif\n"
4826                "#else\n"
4827                "#define A 1\n"
4828                "#endif",
4829                Style);
4830   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4831   verifyFormat("#ifdef _WIN32\n"
4832                "#  define A 0\n"
4833                "#  ifdef VAR2\n"
4834                "#    define B 1\n"
4835                "#    include <someheader.h>\n"
4836                "#    define MACRO                      \\\n"
4837                "      some_very_long_func_aaaaaaaaaa();\n"
4838                "#  endif\n"
4839                "#else\n"
4840                "#  define A 1\n"
4841                "#endif",
4842                Style);
4843   verifyFormat("#if A\n"
4844                "#  define MACRO                        \\\n"
4845                "    void a(int x) {                    \\\n"
4846                "      b();                             \\\n"
4847                "      c();                             \\\n"
4848                "      d();                             \\\n"
4849                "      e();                             \\\n"
4850                "      f();                             \\\n"
4851                "    }\n"
4852                "#endif",
4853                Style);
4854   // Comments before include guard.
4855   verifyFormat("// file comment\n"
4856                "// file comment\n"
4857                "#ifndef HEADER_H\n"
4858                "#define HEADER_H\n"
4859                "code();\n"
4860                "#endif",
4861                Style);
4862   // Test with include guards.
4863   verifyFormat("#ifndef HEADER_H\n"
4864                "#define HEADER_H\n"
4865                "code();\n"
4866                "#endif",
4867                Style);
4868   // Include guards must have a #define with the same variable immediately
4869   // after #ifndef.
4870   verifyFormat("#ifndef NOT_GUARD\n"
4871                "#  define FOO\n"
4872                "code();\n"
4873                "#endif",
4874                Style);
4875 
4876   // Include guards must cover the entire file.
4877   verifyFormat("code();\n"
4878                "code();\n"
4879                "#ifndef NOT_GUARD\n"
4880                "#  define NOT_GUARD\n"
4881                "code();\n"
4882                "#endif",
4883                Style);
4884   verifyFormat("#ifndef NOT_GUARD\n"
4885                "#  define NOT_GUARD\n"
4886                "code();\n"
4887                "#endif\n"
4888                "code();",
4889                Style);
4890   // Test with trailing blank lines.
4891   verifyFormat("#ifndef HEADER_H\n"
4892                "#define HEADER_H\n"
4893                "code();\n"
4894                "#endif\n",
4895                Style);
4896   // Include guards don't have #else.
4897   verifyFormat("#ifndef NOT_GUARD\n"
4898                "#  define NOT_GUARD\n"
4899                "code();\n"
4900                "#else\n"
4901                "#endif",
4902                Style);
4903   verifyFormat("#ifndef NOT_GUARD\n"
4904                "#  define NOT_GUARD\n"
4905                "code();\n"
4906                "#elif FOO\n"
4907                "#endif",
4908                Style);
4909   // Non-identifier #define after potential include guard.
4910   verifyFormat("#ifndef FOO\n"
4911                "#  define 1\n"
4912                "#endif\n",
4913                Style);
4914   // #if closes past last non-preprocessor line.
4915   verifyFormat("#ifndef FOO\n"
4916                "#define FOO\n"
4917                "#if 1\n"
4918                "int i;\n"
4919                "#  define A 0\n"
4920                "#endif\n"
4921                "#endif\n",
4922                Style);
4923   // Don't crash if there is an #elif directive without a condition.
4924   verifyFormat("#if 1\n"
4925                "int x;\n"
4926                "#elif\n"
4927                "int y;\n"
4928                "#else\n"
4929                "int z;\n"
4930                "#endif",
4931                Style);
4932   // FIXME: This doesn't handle the case where there's code between the
4933   // #ifndef and #define but all other conditions hold. This is because when
4934   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
4935   // previous code line yet, so we can't detect it.
4936   EXPECT_EQ("#ifndef NOT_GUARD\n"
4937             "code();\n"
4938             "#define NOT_GUARD\n"
4939             "code();\n"
4940             "#endif",
4941             format("#ifndef NOT_GUARD\n"
4942                    "code();\n"
4943                    "#  define NOT_GUARD\n"
4944                    "code();\n"
4945                    "#endif",
4946                    Style));
4947   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
4948   // be outside an include guard. Examples are #pragma once and
4949   // #pragma GCC diagnostic, or anything else that does not change the meaning
4950   // of the file if it's included multiple times.
4951   EXPECT_EQ("#ifdef WIN32\n"
4952             "#  pragma once\n"
4953             "#endif\n"
4954             "#ifndef HEADER_H\n"
4955             "#  define HEADER_H\n"
4956             "code();\n"
4957             "#endif",
4958             format("#ifdef WIN32\n"
4959                    "#  pragma once\n"
4960                    "#endif\n"
4961                    "#ifndef HEADER_H\n"
4962                    "#define HEADER_H\n"
4963                    "code();\n"
4964                    "#endif",
4965                    Style));
4966   // FIXME: This does not detect when there is a single non-preprocessor line
4967   // in front of an include-guard-like structure where other conditions hold
4968   // because ScopedLineState hides the line.
4969   EXPECT_EQ("code();\n"
4970             "#ifndef HEADER_H\n"
4971             "#define HEADER_H\n"
4972             "code();\n"
4973             "#endif",
4974             format("code();\n"
4975                    "#ifndef HEADER_H\n"
4976                    "#  define HEADER_H\n"
4977                    "code();\n"
4978                    "#endif",
4979                    Style));
4980   // Keep comments aligned with #, otherwise indent comments normally. These
4981   // tests cannot use verifyFormat because messUp manipulates leading
4982   // whitespace.
4983   {
4984     const char *Expected = ""
4985                            "void f() {\n"
4986                            "#if 1\n"
4987                            "// Preprocessor aligned.\n"
4988                            "#  define A 0\n"
4989                            "  // Code. Separated by blank line.\n"
4990                            "\n"
4991                            "#  define B 0\n"
4992                            "  // Code. Not aligned with #\n"
4993                            "#  define C 0\n"
4994                            "#endif";
4995     const char *ToFormat = ""
4996                            "void f() {\n"
4997                            "#if 1\n"
4998                            "// Preprocessor aligned.\n"
4999                            "#  define A 0\n"
5000                            "// Code. Separated by blank line.\n"
5001                            "\n"
5002                            "#  define B 0\n"
5003                            "   // Code. Not aligned with #\n"
5004                            "#  define C 0\n"
5005                            "#endif";
5006     EXPECT_EQ(Expected, format(ToFormat, Style));
5007     EXPECT_EQ(Expected, format(Expected, Style));
5008   }
5009   // Keep block quotes aligned.
5010   {
5011     const char *Expected = ""
5012                            "void f() {\n"
5013                            "#if 1\n"
5014                            "/* Preprocessor aligned. */\n"
5015                            "#  define A 0\n"
5016                            "  /* Code. Separated by blank line. */\n"
5017                            "\n"
5018                            "#  define B 0\n"
5019                            "  /* Code. Not aligned with # */\n"
5020                            "#  define C 0\n"
5021                            "#endif";
5022     const char *ToFormat = ""
5023                            "void f() {\n"
5024                            "#if 1\n"
5025                            "/* Preprocessor aligned. */\n"
5026                            "#  define A 0\n"
5027                            "/* Code. Separated by blank line. */\n"
5028                            "\n"
5029                            "#  define B 0\n"
5030                            "   /* Code. Not aligned with # */\n"
5031                            "#  define C 0\n"
5032                            "#endif";
5033     EXPECT_EQ(Expected, format(ToFormat, Style));
5034     EXPECT_EQ(Expected, format(Expected, Style));
5035   }
5036   // Keep comments aligned with un-indented directives.
5037   {
5038     const char *Expected = ""
5039                            "void f() {\n"
5040                            "// Preprocessor aligned.\n"
5041                            "#define A 0\n"
5042                            "  // Code. Separated by blank line.\n"
5043                            "\n"
5044                            "#define B 0\n"
5045                            "  // Code. Not aligned with #\n"
5046                            "#define C 0\n";
5047     const char *ToFormat = ""
5048                            "void f() {\n"
5049                            "// Preprocessor aligned.\n"
5050                            "#define A 0\n"
5051                            "// Code. Separated by blank line.\n"
5052                            "\n"
5053                            "#define B 0\n"
5054                            "   // Code. Not aligned with #\n"
5055                            "#define C 0\n";
5056     EXPECT_EQ(Expected, format(ToFormat, Style));
5057     EXPECT_EQ(Expected, format(Expected, Style));
5058   }
5059   // Test AfterHash with tabs.
5060   {
5061     FormatStyle Tabbed = Style;
5062     Tabbed.UseTab = FormatStyle::UT_Always;
5063     Tabbed.IndentWidth = 8;
5064     Tabbed.TabWidth = 8;
5065     verifyFormat("#ifdef _WIN32\n"
5066                  "#\tdefine A 0\n"
5067                  "#\tifdef VAR2\n"
5068                  "#\t\tdefine B 1\n"
5069                  "#\t\tinclude <someheader.h>\n"
5070                  "#\t\tdefine MACRO          \\\n"
5071                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5072                  "#\tendif\n"
5073                  "#else\n"
5074                  "#\tdefine A 1\n"
5075                  "#endif",
5076                  Tabbed);
5077   }
5078 
5079   // Regression test: Multiline-macro inside include guards.
5080   verifyFormat("#ifndef HEADER_H\n"
5081                "#define HEADER_H\n"
5082                "#define A()        \\\n"
5083                "  int i;           \\\n"
5084                "  int j;\n"
5085                "#endif // HEADER_H",
5086                getLLVMStyleWithColumns(20));
5087 
5088   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5089   // Basic before hash indent tests
5090   verifyFormat("#ifdef _WIN32\n"
5091                "  #define A 0\n"
5092                "  #ifdef VAR2\n"
5093                "    #define B 1\n"
5094                "    #include <someheader.h>\n"
5095                "    #define MACRO                      \\\n"
5096                "      some_very_long_func_aaaaaaaaaa();\n"
5097                "  #endif\n"
5098                "#else\n"
5099                "  #define A 1\n"
5100                "#endif",
5101                Style);
5102   verifyFormat("#if A\n"
5103                "  #define MACRO                        \\\n"
5104                "    void a(int x) {                    \\\n"
5105                "      b();                             \\\n"
5106                "      c();                             \\\n"
5107                "      d();                             \\\n"
5108                "      e();                             \\\n"
5109                "      f();                             \\\n"
5110                "    }\n"
5111                "#endif",
5112                Style);
5113   // Keep comments aligned with indented directives. These
5114   // tests cannot use verifyFormat because messUp manipulates leading
5115   // whitespace.
5116   {
5117     const char *Expected = "void f() {\n"
5118                            "// Aligned to preprocessor.\n"
5119                            "#if 1\n"
5120                            "  // Aligned to code.\n"
5121                            "  int a;\n"
5122                            "  #if 1\n"
5123                            "    // Aligned to preprocessor.\n"
5124                            "    #define A 0\n"
5125                            "  // Aligned to code.\n"
5126                            "  int b;\n"
5127                            "  #endif\n"
5128                            "#endif\n"
5129                            "}";
5130     const char *ToFormat = "void f() {\n"
5131                            "// Aligned to preprocessor.\n"
5132                            "#if 1\n"
5133                            "// Aligned to code.\n"
5134                            "int a;\n"
5135                            "#if 1\n"
5136                            "// Aligned to preprocessor.\n"
5137                            "#define A 0\n"
5138                            "// Aligned to code.\n"
5139                            "int b;\n"
5140                            "#endif\n"
5141                            "#endif\n"
5142                            "}";
5143     EXPECT_EQ(Expected, format(ToFormat, Style));
5144     EXPECT_EQ(Expected, format(Expected, Style));
5145   }
5146   {
5147     const char *Expected = "void f() {\n"
5148                            "/* Aligned to preprocessor. */\n"
5149                            "#if 1\n"
5150                            "  /* Aligned to code. */\n"
5151                            "  int a;\n"
5152                            "  #if 1\n"
5153                            "    /* Aligned to preprocessor. */\n"
5154                            "    #define A 0\n"
5155                            "  /* Aligned to code. */\n"
5156                            "  int b;\n"
5157                            "  #endif\n"
5158                            "#endif\n"
5159                            "}";
5160     const char *ToFormat = "void f() {\n"
5161                            "/* Aligned to preprocessor. */\n"
5162                            "#if 1\n"
5163                            "/* Aligned to code. */\n"
5164                            "int a;\n"
5165                            "#if 1\n"
5166                            "/* Aligned to preprocessor. */\n"
5167                            "#define A 0\n"
5168                            "/* Aligned to code. */\n"
5169                            "int b;\n"
5170                            "#endif\n"
5171                            "#endif\n"
5172                            "}";
5173     EXPECT_EQ(Expected, format(ToFormat, Style));
5174     EXPECT_EQ(Expected, format(Expected, Style));
5175   }
5176 
5177   // Test single comment before preprocessor
5178   verifyFormat("// Comment\n"
5179                "\n"
5180                "#if 1\n"
5181                "#endif",
5182                Style);
5183 }
5184 
5185 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5186   verifyFormat("{\n  { a #c; }\n}");
5187 }
5188 
5189 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5190   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5191             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5192   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5193             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5194 }
5195 
5196 TEST_F(FormatTest, EscapedNewlines) {
5197   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5198   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5199             format("#define A \\\nint i;\\\n  int j;", Narrow));
5200   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5201   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5202   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5203   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5204 
5205   FormatStyle AlignLeft = getLLVMStyle();
5206   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5207   EXPECT_EQ("#define MACRO(x) \\\n"
5208             "private:         \\\n"
5209             "  int x(int a);\n",
5210             format("#define MACRO(x) \\\n"
5211                    "private:         \\\n"
5212                    "  int x(int a);\n",
5213                    AlignLeft));
5214 
5215   // CRLF line endings
5216   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5217             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5218   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5219   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5220   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5221   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5222   EXPECT_EQ("#define MACRO(x) \\\r\n"
5223             "private:         \\\r\n"
5224             "  int x(int a);\r\n",
5225             format("#define MACRO(x) \\\r\n"
5226                    "private:         \\\r\n"
5227                    "  int x(int a);\r\n",
5228                    AlignLeft));
5229 
5230   FormatStyle DontAlign = getLLVMStyle();
5231   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5232   DontAlign.MaxEmptyLinesToKeep = 3;
5233   // FIXME: can't use verifyFormat here because the newline before
5234   // "public:" is not inserted the first time it's reformatted
5235   EXPECT_EQ("#define A \\\n"
5236             "  class Foo { \\\n"
5237             "    void bar(); \\\n"
5238             "\\\n"
5239             "\\\n"
5240             "\\\n"
5241             "  public: \\\n"
5242             "    void baz(); \\\n"
5243             "  };",
5244             format("#define A \\\n"
5245                    "  class Foo { \\\n"
5246                    "    void bar(); \\\n"
5247                    "\\\n"
5248                    "\\\n"
5249                    "\\\n"
5250                    "  public: \\\n"
5251                    "    void baz(); \\\n"
5252                    "  };",
5253                    DontAlign));
5254 }
5255 
5256 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5257   verifyFormat("#define A \\\n"
5258                "  int v(  \\\n"
5259                "      a); \\\n"
5260                "  int i;",
5261                getLLVMStyleWithColumns(11));
5262 }
5263 
5264 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5265   EXPECT_EQ(
5266       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5267       "                      \\\n"
5268       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5269       "\n"
5270       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5271       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5272       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5273              "\\\n"
5274              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5275              "  \n"
5276              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5277              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5278 }
5279 
5280 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5281   EXPECT_EQ("int\n"
5282             "#define A\n"
5283             "    a;",
5284             format("int\n#define A\na;"));
5285   verifyFormat("functionCallTo(\n"
5286                "    someOtherFunction(\n"
5287                "        withSomeParameters, whichInSequence,\n"
5288                "        areLongerThanALine(andAnotherCall,\n"
5289                "#define A B\n"
5290                "                           withMoreParamters,\n"
5291                "                           whichStronglyInfluenceTheLayout),\n"
5292                "        andMoreParameters),\n"
5293                "    trailing);",
5294                getLLVMStyleWithColumns(69));
5295   verifyFormat("Foo::Foo()\n"
5296                "#ifdef BAR\n"
5297                "    : baz(0)\n"
5298                "#endif\n"
5299                "{\n"
5300                "}");
5301   verifyFormat("void f() {\n"
5302                "  if (true)\n"
5303                "#ifdef A\n"
5304                "    f(42);\n"
5305                "  x();\n"
5306                "#else\n"
5307                "    g();\n"
5308                "  x();\n"
5309                "#endif\n"
5310                "}");
5311   verifyFormat("void f(param1, param2,\n"
5312                "       param3,\n"
5313                "#ifdef A\n"
5314                "       param4(param5,\n"
5315                "#ifdef A1\n"
5316                "              param6,\n"
5317                "#ifdef A2\n"
5318                "              param7),\n"
5319                "#else\n"
5320                "              param8),\n"
5321                "       param9,\n"
5322                "#endif\n"
5323                "       param10,\n"
5324                "#endif\n"
5325                "       param11)\n"
5326                "#else\n"
5327                "       param12)\n"
5328                "#endif\n"
5329                "{\n"
5330                "  x();\n"
5331                "}",
5332                getLLVMStyleWithColumns(28));
5333   verifyFormat("#if 1\n"
5334                "int i;");
5335   verifyFormat("#if 1\n"
5336                "#endif\n"
5337                "#if 1\n"
5338                "#else\n"
5339                "#endif\n");
5340   verifyFormat("DEBUG({\n"
5341                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5342                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5343                "});\n"
5344                "#if a\n"
5345                "#else\n"
5346                "#endif");
5347 
5348   verifyIncompleteFormat("void f(\n"
5349                          "#if A\n"
5350                          ");\n"
5351                          "#else\n"
5352                          "#endif");
5353 }
5354 
5355 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5356   verifyFormat("#endif\n"
5357                "#if B");
5358 }
5359 
5360 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5361   FormatStyle SingleLine = getLLVMStyle();
5362   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5363   verifyFormat("#if 0\n"
5364                "#elif 1\n"
5365                "#endif\n"
5366                "void foo() {\n"
5367                "  if (test) foo2();\n"
5368                "}",
5369                SingleLine);
5370 }
5371 
5372 TEST_F(FormatTest, LayoutBlockInsideParens) {
5373   verifyFormat("functionCall({ int i; });");
5374   verifyFormat("functionCall({\n"
5375                "  int i;\n"
5376                "  int j;\n"
5377                "});");
5378   verifyFormat("functionCall(\n"
5379                "    {\n"
5380                "      int i;\n"
5381                "      int j;\n"
5382                "    },\n"
5383                "    aaaa, bbbb, cccc);");
5384   verifyFormat("functionA(functionB({\n"
5385                "            int i;\n"
5386                "            int j;\n"
5387                "          }),\n"
5388                "          aaaa, bbbb, cccc);");
5389   verifyFormat("functionCall(\n"
5390                "    {\n"
5391                "      int i;\n"
5392                "      int j;\n"
5393                "    },\n"
5394                "    aaaa, bbbb, // comment\n"
5395                "    cccc);");
5396   verifyFormat("functionA(functionB({\n"
5397                "            int i;\n"
5398                "            int j;\n"
5399                "          }),\n"
5400                "          aaaa, bbbb, // comment\n"
5401                "          cccc);");
5402   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5403   verifyFormat("functionCall(aaaa, bbbb, {\n"
5404                "  int i;\n"
5405                "  int j;\n"
5406                "});");
5407   verifyFormat(
5408       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5409       "    {\n"
5410       "      int i; // break\n"
5411       "    },\n"
5412       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5413       "                                     ccccccccccccccccc));");
5414   verifyFormat("DEBUG({\n"
5415                "  if (a)\n"
5416                "    f();\n"
5417                "});");
5418 }
5419 
5420 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5421   EXPECT_EQ("SOME_MACRO { int i; }\n"
5422             "int i;",
5423             format("  SOME_MACRO  {int i;}  int i;"));
5424 }
5425 
5426 TEST_F(FormatTest, LayoutNestedBlocks) {
5427   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5428                "  struct s {\n"
5429                "    int i;\n"
5430                "  };\n"
5431                "  s kBitsToOs[] = {{10}};\n"
5432                "  for (int i = 0; i < 10; ++i)\n"
5433                "    return;\n"
5434                "}");
5435   verifyFormat("call(parameter, {\n"
5436                "  something();\n"
5437                "  // Comment using all columns.\n"
5438                "  somethingelse();\n"
5439                "});",
5440                getLLVMStyleWithColumns(40));
5441   verifyFormat("DEBUG( //\n"
5442                "    { f(); }, a);");
5443   verifyFormat("DEBUG( //\n"
5444                "    {\n"
5445                "      f(); //\n"
5446                "    },\n"
5447                "    a);");
5448 
5449   EXPECT_EQ("call(parameter, {\n"
5450             "  something();\n"
5451             "  // Comment too\n"
5452             "  // looooooooooong.\n"
5453             "  somethingElse();\n"
5454             "});",
5455             format("call(parameter, {\n"
5456                    "  something();\n"
5457                    "  // Comment too looooooooooong.\n"
5458                    "  somethingElse();\n"
5459                    "});",
5460                    getLLVMStyleWithColumns(29)));
5461   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5462   EXPECT_EQ("DEBUG({ // comment\n"
5463             "  int i;\n"
5464             "});",
5465             format("DEBUG({ // comment\n"
5466                    "int  i;\n"
5467                    "});"));
5468   EXPECT_EQ("DEBUG({\n"
5469             "  int i;\n"
5470             "\n"
5471             "  // comment\n"
5472             "  int j;\n"
5473             "});",
5474             format("DEBUG({\n"
5475                    "  int  i;\n"
5476                    "\n"
5477                    "  // comment\n"
5478                    "  int  j;\n"
5479                    "});"));
5480 
5481   verifyFormat("DEBUG({\n"
5482                "  if (a)\n"
5483                "    return;\n"
5484                "});");
5485   verifyGoogleFormat("DEBUG({\n"
5486                      "  if (a) return;\n"
5487                      "});");
5488   FormatStyle Style = getGoogleStyle();
5489   Style.ColumnLimit = 45;
5490   verifyFormat("Debug(\n"
5491                "    aaaaa,\n"
5492                "    {\n"
5493                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5494                "    },\n"
5495                "    a);",
5496                Style);
5497 
5498   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5499 
5500   verifyNoCrash("^{v^{a}}");
5501 }
5502 
5503 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
5504   EXPECT_EQ("#define MACRO()                     \\\n"
5505             "  Debug(aaa, /* force line break */ \\\n"
5506             "        {                           \\\n"
5507             "          int i;                    \\\n"
5508             "          int j;                    \\\n"
5509             "        })",
5510             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
5511                    "          {  int   i;  int  j;   })",
5512                    getGoogleStyle()));
5513 
5514   EXPECT_EQ("#define A                                       \\\n"
5515             "  [] {                                          \\\n"
5516             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
5517             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
5518             "  }",
5519             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5520                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
5521                    getGoogleStyle()));
5522 }
5523 
5524 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
5525   EXPECT_EQ("{}", format("{}"));
5526   verifyFormat("enum E {};");
5527   verifyFormat("enum E {}");
5528   FormatStyle Style = getLLVMStyle();
5529   Style.SpaceInEmptyBlock = true;
5530   EXPECT_EQ("void f() { }", format("void f() {}", Style));
5531   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
5532   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
5533   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5534   Style.BraceWrapping.BeforeElse = false;
5535   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5536   verifyFormat("if (a)\n"
5537                "{\n"
5538                "} else if (b)\n"
5539                "{\n"
5540                "} else\n"
5541                "{ }",
5542                Style);
5543   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
5544   verifyFormat("if (a) {\n"
5545                "} else if (b) {\n"
5546                "} else {\n"
5547                "}",
5548                Style);
5549   Style.BraceWrapping.BeforeElse = true;
5550   verifyFormat("if (a) { }\n"
5551                "else if (b) { }\n"
5552                "else { }",
5553                Style);
5554 }
5555 
5556 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
5557   FormatStyle Style = getLLVMStyle();
5558   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
5559   Style.MacroBlockEnd = "^[A-Z_]+_END$";
5560   verifyFormat("FOO_BEGIN\n"
5561                "  FOO_ENTRY\n"
5562                "FOO_END",
5563                Style);
5564   verifyFormat("FOO_BEGIN\n"
5565                "  NESTED_FOO_BEGIN\n"
5566                "    NESTED_FOO_ENTRY\n"
5567                "  NESTED_FOO_END\n"
5568                "FOO_END",
5569                Style);
5570   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
5571                "  int x;\n"
5572                "  x = 1;\n"
5573                "FOO_END(Baz)",
5574                Style);
5575 }
5576 
5577 //===----------------------------------------------------------------------===//
5578 // Line break tests.
5579 //===----------------------------------------------------------------------===//
5580 
5581 TEST_F(FormatTest, PreventConfusingIndents) {
5582   verifyFormat(
5583       "void f() {\n"
5584       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
5585       "                         parameter, parameter, parameter)),\n"
5586       "                     SecondLongCall(parameter));\n"
5587       "}");
5588   verifyFormat(
5589       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5590       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5591       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5592       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
5593   verifyFormat(
5594       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5595       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
5596       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5597       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
5598   verifyFormat(
5599       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5600       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
5601       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
5602       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
5603   verifyFormat("int a = bbbb && ccc &&\n"
5604                "        fffff(\n"
5605                "#define A Just forcing a new line\n"
5606                "            ddd);");
5607 }
5608 
5609 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
5610   verifyFormat(
5611       "bool aaaaaaa =\n"
5612       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
5613       "    bbbbbbbb();");
5614   verifyFormat(
5615       "bool aaaaaaa =\n"
5616       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
5617       "    bbbbbbbb();");
5618 
5619   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5620                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
5621                "    ccccccccc == ddddddddddd;");
5622   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5623                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
5624                "    ccccccccc == ddddddddddd;");
5625   verifyFormat(
5626       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
5627       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
5628       "    ccccccccc == ddddddddddd;");
5629 
5630   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5631                "                 aaaaaa) &&\n"
5632                "         bbbbbb && cccccc;");
5633   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5634                "                 aaaaaa) >>\n"
5635                "         bbbbbb;");
5636   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
5637                "    SourceMgr.getSpellingColumnNumber(\n"
5638                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
5639                "    1);");
5640 
5641   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5642                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
5643                "    cccccc) {\n}");
5644   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5645                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5646                "              cccccc) {\n}");
5647   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5648                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5649                "              cccccc) {\n}");
5650   verifyFormat("b = a &&\n"
5651                "    // Comment\n"
5652                "    b.c && d;");
5653 
5654   // If the LHS of a comparison is not a binary expression itself, the
5655   // additional linebreak confuses many people.
5656   verifyFormat(
5657       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5658       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
5659       "}");
5660   verifyFormat(
5661       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5662       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5663       "}");
5664   verifyFormat(
5665       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
5666       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5667       "}");
5668   verifyFormat(
5669       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5670       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
5671       "}");
5672   // Even explicit parentheses stress the precedence enough to make the
5673   // additional break unnecessary.
5674   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5675                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5676                "}");
5677   // This cases is borderline, but with the indentation it is still readable.
5678   verifyFormat(
5679       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5680       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5681       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
5682       "}",
5683       getLLVMStyleWithColumns(75));
5684 
5685   // If the LHS is a binary expression, we should still use the additional break
5686   // as otherwise the formatting hides the operator precedence.
5687   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5688                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5689                "    5) {\n"
5690                "}");
5691   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5692                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
5693                "    5) {\n"
5694                "}");
5695 
5696   FormatStyle OnePerLine = getLLVMStyle();
5697   OnePerLine.BinPackParameters = false;
5698   verifyFormat(
5699       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5700       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5701       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
5702       OnePerLine);
5703 
5704   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
5705                "                .aaa(aaaaaaaaaaaaa) *\n"
5706                "            aaaaaaa +\n"
5707                "        aaaaaaa;",
5708                getLLVMStyleWithColumns(40));
5709 }
5710 
5711 TEST_F(FormatTest, ExpressionIndentation) {
5712   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5713                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5714                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5715                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5716                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
5717                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
5718                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5719                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
5720                "                 ccccccccccccccccccccccccccccccccccccccccc;");
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 (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5730                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5731                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5732                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5733   verifyFormat("if () {\n"
5734                "} else if (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 CONSTEXPR (aaaaa && bbbbb > // break\n"
5743                "                                  ccccc) {\n"
5744                "}");
5745   verifyFormat("if () {\n"
5746                "} else if (aaaaa &&\n"
5747                "           bbbbb > // break\n"
5748                "               ccccc &&\n"
5749                "           ddddd) {\n"
5750                "}");
5751 
5752   // Presence of a trailing comment used to change indentation of b.
5753   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
5754                "       b;\n"
5755                "return aaaaaaaaaaaaaaaaaaa +\n"
5756                "       b; //",
5757                getLLVMStyleWithColumns(30));
5758 }
5759 
5760 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
5761   // Not sure what the best system is here. Like this, the LHS can be found
5762   // immediately above an operator (everything with the same or a higher
5763   // indent). The RHS is aligned right of the operator and so compasses
5764   // everything until something with the same indent as the operator is found.
5765   // FIXME: Is this a good system?
5766   FormatStyle Style = getLLVMStyle();
5767   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5768   verifyFormat(
5769       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5770       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5771       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5772       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5773       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5774       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5775       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5776       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5777       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
5778       Style);
5779   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5780                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5781                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5782                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5783                Style);
5784   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5785                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5786                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5787                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5788                Style);
5789   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5790                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5791                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5792                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5793                Style);
5794   verifyFormat("if () {\n"
5795                "} else if (aaaaa\n"
5796                "           && bbbbb // break\n"
5797                "                  > ccccc) {\n"
5798                "}",
5799                Style);
5800   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5801                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5802                Style);
5803   verifyFormat("return (a)\n"
5804                "       // comment\n"
5805                "       + b;",
5806                Style);
5807   verifyFormat(
5808       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5809       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5810       "             + cc;",
5811       Style);
5812 
5813   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5814                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5815                Style);
5816 
5817   // Forced by comments.
5818   verifyFormat(
5819       "unsigned ContentSize =\n"
5820       "    sizeof(int16_t)   // DWARF ARange version number\n"
5821       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5822       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5823       "    + sizeof(int8_t); // Segment Size (in bytes)");
5824 
5825   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5826                "       == boost::fusion::at_c<1>(iiii).second;",
5827                Style);
5828 
5829   Style.ColumnLimit = 60;
5830   verifyFormat("zzzzzzzzzz\n"
5831                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5832                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5833                Style);
5834 
5835   Style.ColumnLimit = 80;
5836   Style.IndentWidth = 4;
5837   Style.TabWidth = 4;
5838   Style.UseTab = FormatStyle::UT_Always;
5839   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5840   Style.AlignOperands = FormatStyle::OAS_DontAlign;
5841   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
5842             "\t&& (someOtherLongishConditionPart1\n"
5843             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
5844             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
5845                    "(someOtherLongishConditionPart1 || "
5846                    "someOtherEvenLongerNestedConditionPart2);",
5847                    Style));
5848 }
5849 
5850 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
5851   FormatStyle Style = getLLVMStyle();
5852   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5853   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
5854 
5855   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5856                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5857                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5858                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5859                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5860                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5861                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5862                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5863                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
5864                Style);
5865   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5866                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5867                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5868                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5869                Style);
5870   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5871                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5872                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5873                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5874                Style);
5875   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5876                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5877                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5878                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5879                Style);
5880   verifyFormat("if () {\n"
5881                "} else if (aaaaa\n"
5882                "           && bbbbb // break\n"
5883                "                  > ccccc) {\n"
5884                "}",
5885                Style);
5886   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5887                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5888                Style);
5889   verifyFormat("return (a)\n"
5890                "     // comment\n"
5891                "     + b;",
5892                Style);
5893   verifyFormat(
5894       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5895       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5896       "           + cc;",
5897       Style);
5898   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
5899                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
5900                "                        : 3333333333333333;",
5901                Style);
5902   verifyFormat(
5903       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
5904       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
5905       "                                             : eeeeeeeeeeeeeeeeee)\n"
5906       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
5907       "                        : 3333333333333333;",
5908       Style);
5909   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5910                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5911                Style);
5912 
5913   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5914                "    == boost::fusion::at_c<1>(iiii).second;",
5915                Style);
5916 
5917   Style.ColumnLimit = 60;
5918   verifyFormat("zzzzzzzzzzzzz\n"
5919                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5920                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5921                Style);
5922 
5923   // Forced by comments.
5924   Style.ColumnLimit = 80;
5925   verifyFormat(
5926       "unsigned ContentSize\n"
5927       "    = sizeof(int16_t) // DWARF ARange version number\n"
5928       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5929       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5930       "    + sizeof(int8_t); // Segment Size (in bytes)",
5931       Style);
5932 
5933   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5934   verifyFormat(
5935       "unsigned ContentSize =\n"
5936       "    sizeof(int16_t)   // DWARF ARange version number\n"
5937       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5938       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5939       "    + sizeof(int8_t); // Segment Size (in bytes)",
5940       Style);
5941 
5942   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
5943   verifyFormat(
5944       "unsigned ContentSize =\n"
5945       "    sizeof(int16_t)   // DWARF ARange version number\n"
5946       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5947       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5948       "    + sizeof(int8_t); // Segment Size (in bytes)",
5949       Style);
5950 }
5951 
5952 TEST_F(FormatTest, EnforcedOperatorWraps) {
5953   // Here we'd like to wrap after the || operators, but a comment is forcing an
5954   // earlier wrap.
5955   verifyFormat("bool x = aaaaa //\n"
5956                "         || bbbbb\n"
5957                "         //\n"
5958                "         || cccc;");
5959 }
5960 
5961 TEST_F(FormatTest, NoOperandAlignment) {
5962   FormatStyle Style = getLLVMStyle();
5963   Style.AlignOperands = FormatStyle::OAS_DontAlign;
5964   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
5965                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5966                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5967                Style);
5968   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5969   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5970                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5971                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5972                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5973                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5974                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5975                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5976                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5977                "        > ccccccccccccccccccccccccccccccccccccccccc;",
5978                Style);
5979 
5980   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5981                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5982                "    + cc;",
5983                Style);
5984   verifyFormat("int a = aa\n"
5985                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5986                "        * cccccccccccccccccccccccccccccccccccc;\n",
5987                Style);
5988 
5989   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5990   verifyFormat("return (a > b\n"
5991                "    // comment1\n"
5992                "    // comment2\n"
5993                "    || c);",
5994                Style);
5995 }
5996 
5997 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
5998   FormatStyle Style = getLLVMStyle();
5999   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6000   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6001                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6002                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6003                Style);
6004 }
6005 
6006 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6007   FormatStyle Style = getLLVMStyleWithColumns(40);
6008   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6009   Style.BinPackArguments = false;
6010   verifyFormat("void test() {\n"
6011                "  someFunction(\n"
6012                "      this + argument + is + quite\n"
6013                "      + long + so + it + gets + wrapped\n"
6014                "      + but + remains + bin - packed);\n"
6015                "}",
6016                Style);
6017   verifyFormat("void test() {\n"
6018                "  someFunction(arg1,\n"
6019                "               this + argument + is\n"
6020                "                   + quite + long + so\n"
6021                "                   + it + gets + wrapped\n"
6022                "                   + but + remains + bin\n"
6023                "                   - packed,\n"
6024                "               arg3);\n"
6025                "}",
6026                Style);
6027   verifyFormat("void test() {\n"
6028                "  someFunction(\n"
6029                "      arg1,\n"
6030                "      this + argument + has\n"
6031                "          + anotherFunc(nested,\n"
6032                "                        calls + whose\n"
6033                "                            + arguments\n"
6034                "                            + are + also\n"
6035                "                            + wrapped,\n"
6036                "                        in + addition)\n"
6037                "          + to + being + bin - packed,\n"
6038                "      arg3);\n"
6039                "}",
6040                Style);
6041 
6042   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6043   verifyFormat("void test() {\n"
6044                "  someFunction(\n"
6045                "      arg1,\n"
6046                "      this + argument + has +\n"
6047                "          anotherFunc(nested,\n"
6048                "                      calls + whose +\n"
6049                "                          arguments +\n"
6050                "                          are + also +\n"
6051                "                          wrapped,\n"
6052                "                      in + addition) +\n"
6053                "          to + being + bin - packed,\n"
6054                "      arg3);\n"
6055                "}",
6056                Style);
6057 }
6058 
6059 TEST_F(FormatTest, ConstructorInitializers) {
6060   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6061   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6062                getLLVMStyleWithColumns(45));
6063   verifyFormat("Constructor()\n"
6064                "    : Inttializer(FitsOnTheLine) {}",
6065                getLLVMStyleWithColumns(44));
6066   verifyFormat("Constructor()\n"
6067                "    : Inttializer(FitsOnTheLine) {}",
6068                getLLVMStyleWithColumns(43));
6069 
6070   verifyFormat("template <typename T>\n"
6071                "Constructor() : Initializer(FitsOnTheLine) {}",
6072                getLLVMStyleWithColumns(45));
6073 
6074   verifyFormat(
6075       "SomeClass::Constructor()\n"
6076       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6077 
6078   verifyFormat(
6079       "SomeClass::Constructor()\n"
6080       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6081       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6082   verifyFormat(
6083       "SomeClass::Constructor()\n"
6084       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6085       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6086   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6087                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6088                "    : aaaaaaaaaa(aaaaaa) {}");
6089 
6090   verifyFormat("Constructor()\n"
6091                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6092                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6093                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6094                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6095 
6096   verifyFormat("Constructor()\n"
6097                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6098                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6099 
6100   verifyFormat("Constructor(int Parameter = 0)\n"
6101                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6102                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6103   verifyFormat("Constructor()\n"
6104                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6105                "}",
6106                getLLVMStyleWithColumns(60));
6107   verifyFormat("Constructor()\n"
6108                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6109                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6110 
6111   // Here a line could be saved by splitting the second initializer onto two
6112   // lines, but that is not desirable.
6113   verifyFormat("Constructor()\n"
6114                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6115                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6116                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6117 
6118   FormatStyle OnePerLine = getLLVMStyle();
6119   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6120   verifyFormat("MyClass::MyClass()\n"
6121                "    : a(a),\n"
6122                "      b(b),\n"
6123                "      c(c) {}",
6124                OnePerLine);
6125   verifyFormat("MyClass::MyClass()\n"
6126                "    : a(a), // comment\n"
6127                "      b(b),\n"
6128                "      c(c) {}",
6129                OnePerLine);
6130   verifyFormat("MyClass::MyClass(int a)\n"
6131                "    : b(a),      // comment\n"
6132                "      c(a + 1) { // lined up\n"
6133                "}",
6134                OnePerLine);
6135   verifyFormat("Constructor()\n"
6136                "    : a(b, b, b) {}",
6137                OnePerLine);
6138   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6139   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6140   verifyFormat("SomeClass::Constructor()\n"
6141                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6142                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6143                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6144                OnePerLine);
6145   verifyFormat("SomeClass::Constructor()\n"
6146                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6147                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6148                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6149                OnePerLine);
6150   verifyFormat("MyClass::MyClass(int var)\n"
6151                "    : some_var_(var),            // 4 space indent\n"
6152                "      some_other_var_(var + 1) { // lined up\n"
6153                "}",
6154                OnePerLine);
6155   verifyFormat("Constructor()\n"
6156                "    : aaaaa(aaaaaa),\n"
6157                "      aaaaa(aaaaaa),\n"
6158                "      aaaaa(aaaaaa),\n"
6159                "      aaaaa(aaaaaa),\n"
6160                "      aaaaa(aaaaaa) {}",
6161                OnePerLine);
6162   verifyFormat("Constructor()\n"
6163                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6164                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6165                OnePerLine);
6166   OnePerLine.BinPackParameters = false;
6167   verifyFormat(
6168       "Constructor()\n"
6169       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6170       "          aaaaaaaaaaa().aaa(),\n"
6171       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6172       OnePerLine);
6173   OnePerLine.ColumnLimit = 60;
6174   verifyFormat("Constructor()\n"
6175                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6176                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6177                OnePerLine);
6178 
6179   EXPECT_EQ("Constructor()\n"
6180             "    : // Comment forcing unwanted break.\n"
6181             "      aaaa(aaaa) {}",
6182             format("Constructor() :\n"
6183                    "    // Comment forcing unwanted break.\n"
6184                    "    aaaa(aaaa) {}"));
6185 }
6186 
6187 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6188   FormatStyle Style = getLLVMStyleWithColumns(60);
6189   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6190   Style.BinPackParameters = false;
6191 
6192   for (int i = 0; i < 4; ++i) {
6193     // Test all combinations of parameters that should not have an effect.
6194     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6195     Style.AllowAllArgumentsOnNextLine = i & 2;
6196 
6197     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6198     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6199     verifyFormat("Constructor()\n"
6200                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6201                  Style);
6202     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6203 
6204     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6205     verifyFormat("Constructor()\n"
6206                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6207                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6208                  Style);
6209     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6210 
6211     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6212     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6213     verifyFormat("Constructor()\n"
6214                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6215                  Style);
6216 
6217     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6218     verifyFormat("Constructor()\n"
6219                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6220                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6221                  Style);
6222 
6223     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6224     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6225     verifyFormat("Constructor() :\n"
6226                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6227                  Style);
6228 
6229     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6230     verifyFormat("Constructor() :\n"
6231                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6232                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6233                  Style);
6234   }
6235 
6236   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6237   // AllowAllConstructorInitializersOnNextLine in all
6238   // BreakConstructorInitializers modes
6239   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6240   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6241   verifyFormat("SomeClassWithALongName::Constructor(\n"
6242                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6243                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6244                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6245                Style);
6246 
6247   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6248   verifyFormat("SomeClassWithALongName::Constructor(\n"
6249                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6250                "    int bbbbbbbbbbbbb,\n"
6251                "    int cccccccccccccccc)\n"
6252                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6253                Style);
6254 
6255   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6256   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6257   verifyFormat("SomeClassWithALongName::Constructor(\n"
6258                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6259                "    int bbbbbbbbbbbbb)\n"
6260                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6261                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6262                Style);
6263 
6264   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6265 
6266   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6267   verifyFormat("SomeClassWithALongName::Constructor(\n"
6268                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6269                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6270                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6271                Style);
6272 
6273   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6274   verifyFormat("SomeClassWithALongName::Constructor(\n"
6275                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6276                "    int bbbbbbbbbbbbb,\n"
6277                "    int cccccccccccccccc)\n"
6278                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6279                Style);
6280 
6281   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6282   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6283   verifyFormat("SomeClassWithALongName::Constructor(\n"
6284                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6285                "    int bbbbbbbbbbbbb)\n"
6286                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6287                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6288                Style);
6289 
6290   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6291   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6292   verifyFormat("SomeClassWithALongName::Constructor(\n"
6293                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6294                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6295                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6296                Style);
6297 
6298   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6299   verifyFormat("SomeClassWithALongName::Constructor(\n"
6300                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6301                "    int bbbbbbbbbbbbb,\n"
6302                "    int cccccccccccccccc) :\n"
6303                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6304                Style);
6305 
6306   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6307   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6308   verifyFormat("SomeClassWithALongName::Constructor(\n"
6309                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6310                "    int bbbbbbbbbbbbb) :\n"
6311                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6312                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6313                Style);
6314 }
6315 
6316 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6317   FormatStyle Style = getLLVMStyleWithColumns(60);
6318   Style.BinPackArguments = false;
6319   for (int i = 0; i < 4; ++i) {
6320     // Test all combinations of parameters that should not have an effect.
6321     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6322     Style.PackConstructorInitializers =
6323         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6324 
6325     Style.AllowAllArgumentsOnNextLine = true;
6326     verifyFormat("void foo() {\n"
6327                  "  FunctionCallWithReallyLongName(\n"
6328                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6329                  "}",
6330                  Style);
6331     Style.AllowAllArgumentsOnNextLine = false;
6332     verifyFormat("void foo() {\n"
6333                  "  FunctionCallWithReallyLongName(\n"
6334                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6335                  "      bbbbbbbbbbbb);\n"
6336                  "}",
6337                  Style);
6338 
6339     Style.AllowAllArgumentsOnNextLine = true;
6340     verifyFormat("void foo() {\n"
6341                  "  auto VariableWithReallyLongName = {\n"
6342                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6343                  "}",
6344                  Style);
6345     Style.AllowAllArgumentsOnNextLine = false;
6346     verifyFormat("void foo() {\n"
6347                  "  auto VariableWithReallyLongName = {\n"
6348                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6349                  "      bbbbbbbbbbbb};\n"
6350                  "}",
6351                  Style);
6352   }
6353 
6354   // This parameter should not affect declarations.
6355   Style.BinPackParameters = false;
6356   Style.AllowAllArgumentsOnNextLine = false;
6357   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6358   verifyFormat("void FunctionCallWithReallyLongName(\n"
6359                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6360                Style);
6361   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6362   verifyFormat("void FunctionCallWithReallyLongName(\n"
6363                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6364                "    int bbbbbbbbbbbb);",
6365                Style);
6366 }
6367 
6368 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6369   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6370   // and BAS_Align.
6371   FormatStyle Style = getLLVMStyleWithColumns(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 = getGoogleStyleWithColumns(47);
6873   verifyFormat("void someLongFunction(\n"
6874                "    int someLoooooooooooooongParameter) const {\n}",
6875                getLLVMStyleWithColumns(47));
6876   verifyFormat("LoooooongReturnType\n"
6877                "someLoooooooongFunction() const {}",
6878                getLLVMStyleWithColumns(47));
6879   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
6880                "    const {}",
6881                Style);
6882   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6883                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
6884   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6885                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
6886   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6887                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
6888   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
6889                "                   aaaaaaaaaaa aaaaa) const override;");
6890   verifyGoogleFormat(
6891       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6892       "    const override;");
6893 
6894   // Even if the first parameter has to be wrapped.
6895   verifyFormat("void someLongFunction(\n"
6896                "    int someLongParameter) const {}",
6897                getLLVMStyleWithColumns(46));
6898   verifyFormat("void someLongFunction(\n"
6899                "    int someLongParameter) const {}",
6900                Style);
6901   verifyFormat("void someLongFunction(\n"
6902                "    int someLongParameter) override {}",
6903                Style);
6904   verifyFormat("void someLongFunction(\n"
6905                "    int someLongParameter) OVERRIDE {}",
6906                Style);
6907   verifyFormat("void someLongFunction(\n"
6908                "    int someLongParameter) final {}",
6909                Style);
6910   verifyFormat("void someLongFunction(\n"
6911                "    int someLongParameter) FINAL {}",
6912                Style);
6913   verifyFormat("void someLongFunction(\n"
6914                "    int parameter) const override {}",
6915                Style);
6916 
6917   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
6918   verifyFormat("void someLongFunction(\n"
6919                "    int someLongParameter) const\n"
6920                "{\n"
6921                "}",
6922                Style);
6923 
6924   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
6925   verifyFormat("void someLongFunction(\n"
6926                "    int someLongParameter) const\n"
6927                "  {\n"
6928                "  }",
6929                Style);
6930 
6931   // Unless these are unknown annotations.
6932   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
6933                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6934                "    LONG_AND_UGLY_ANNOTATION;");
6935 
6936   // Breaking before function-like trailing annotations is fine to keep them
6937   // close to their arguments.
6938   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6939                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
6940   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
6941                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
6942   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
6943                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
6944   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
6945                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
6946   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
6947 
6948   verifyFormat(
6949       "void aaaaaaaaaaaaaaaaaa()\n"
6950       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
6951       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
6952   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6953                "    __attribute__((unused));");
6954   verifyGoogleFormat(
6955       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6956       "    GUARDED_BY(aaaaaaaaaaaa);");
6957   verifyGoogleFormat(
6958       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6959       "    GUARDED_BY(aaaaaaaaaaaa);");
6960   verifyGoogleFormat(
6961       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6962       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6963   verifyGoogleFormat(
6964       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6965       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
6966 }
6967 
6968 TEST_F(FormatTest, FunctionAnnotations) {
6969   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6970                "int OldFunction(const string &parameter) {}");
6971   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6972                "string OldFunction(const string &parameter) {}");
6973   verifyFormat("template <typename T>\n"
6974                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6975                "string OldFunction(const string &parameter) {}");
6976 
6977   // Not function annotations.
6978   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6979                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
6980   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
6981                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
6982   verifyFormat("MACRO(abc).function() // wrap\n"
6983                "    << abc;");
6984   verifyFormat("MACRO(abc)->function() // wrap\n"
6985                "    << abc;");
6986   verifyFormat("MACRO(abc)::function() // wrap\n"
6987                "    << abc;");
6988 }
6989 
6990 TEST_F(FormatTest, BreaksDesireably) {
6991   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6992                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6993                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
6994   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6995                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
6996                "}");
6997 
6998   verifyFormat(
6999       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7000       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7001 
7002   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7003                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7004                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7005 
7006   verifyFormat(
7007       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7008       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7009       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7010       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7011       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7012 
7013   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7014                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7015 
7016   verifyFormat(
7017       "void f() {\n"
7018       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7019       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7020       "}");
7021   verifyFormat(
7022       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7023       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7024   verifyFormat(
7025       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7026       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7027   verifyFormat(
7028       "aaaaaa(aaa,\n"
7029       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7030       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7031       "       aaaa);");
7032   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7033                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7034                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7035 
7036   // Indent consistently independent of call expression and unary operator.
7037   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7038                "    dddddddddddddddddddddddddddddd));");
7039   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7040                "    dddddddddddddddddddddddddddddd));");
7041   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7042                "    dddddddddddddddddddddddddddddd));");
7043 
7044   // This test case breaks on an incorrect memoization, i.e. an optimization not
7045   // taking into account the StopAt value.
7046   verifyFormat(
7047       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7048       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7049       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7050       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7051 
7052   verifyFormat("{\n  {\n    {\n"
7053                "      Annotation.SpaceRequiredBefore =\n"
7054                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7055                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7056                "    }\n  }\n}");
7057 
7058   // Break on an outer level if there was a break on an inner level.
7059   EXPECT_EQ("f(g(h(a, // comment\n"
7060             "      b, c),\n"
7061             "    d, e),\n"
7062             "  x, y);",
7063             format("f(g(h(a, // comment\n"
7064                    "    b, c), d, e), x, y);"));
7065 
7066   // Prefer breaking similar line breaks.
7067   verifyFormat(
7068       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7069       "                             NSTrackingMouseEnteredAndExited |\n"
7070       "                             NSTrackingActiveAlways;");
7071 }
7072 
7073 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7074   FormatStyle NoBinPacking = getGoogleStyle();
7075   NoBinPacking.BinPackParameters = false;
7076   NoBinPacking.BinPackArguments = true;
7077   verifyFormat("void f() {\n"
7078                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7079                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7080                "}",
7081                NoBinPacking);
7082   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7083                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7084                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7085                NoBinPacking);
7086 
7087   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7088   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7089                "                        vector<int> bbbbbbbbbbbbbbb);",
7090                NoBinPacking);
7091   // FIXME: This behavior difference is probably not wanted. However, currently
7092   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7093   // template arguments from BreakBeforeParameter being set because of the
7094   // one-per-line formatting.
7095   verifyFormat(
7096       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7097       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7098       NoBinPacking);
7099   verifyFormat(
7100       "void fffffffffff(\n"
7101       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7102       "        aaaaaaaaaa);");
7103 }
7104 
7105 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7106   FormatStyle NoBinPacking = getGoogleStyle();
7107   NoBinPacking.BinPackParameters = false;
7108   NoBinPacking.BinPackArguments = false;
7109   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7110                "  aaaaaaaaaaaaaaaaaaaa,\n"
7111                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7112                NoBinPacking);
7113   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7114                "        aaaaaaaaaaaaa,\n"
7115                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7116                NoBinPacking);
7117   verifyFormat(
7118       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7119       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7120       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7121       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7122       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7123       NoBinPacking);
7124   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7125                "    .aaaaaaaaaaaaaaaaaa();",
7126                NoBinPacking);
7127   verifyFormat("void f() {\n"
7128                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7129                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7130                "}",
7131                NoBinPacking);
7132 
7133   verifyFormat(
7134       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7135       "             aaaaaaaaaaaa,\n"
7136       "             aaaaaaaaaaaa);",
7137       NoBinPacking);
7138   verifyFormat(
7139       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7140       "                               ddddddddddddddddddddddddddddd),\n"
7141       "             test);",
7142       NoBinPacking);
7143 
7144   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7145                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7146                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7147                "    aaaaaaaaaaaaaaaaaa;",
7148                NoBinPacking);
7149   verifyFormat("a(\"a\"\n"
7150                "  \"a\",\n"
7151                "  a);");
7152 
7153   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7154   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7155                "                aaaaaaaaa,\n"
7156                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7157                NoBinPacking);
7158   verifyFormat(
7159       "void f() {\n"
7160       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7161       "      .aaaaaaa();\n"
7162       "}",
7163       NoBinPacking);
7164   verifyFormat(
7165       "template <class SomeType, class SomeOtherType>\n"
7166       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7167       NoBinPacking);
7168 }
7169 
7170 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7171   FormatStyle Style = getLLVMStyleWithColumns(15);
7172   Style.ExperimentalAutoDetectBinPacking = true;
7173   EXPECT_EQ("aaa(aaaa,\n"
7174             "    aaaa,\n"
7175             "    aaaa);\n"
7176             "aaa(aaaa,\n"
7177             "    aaaa,\n"
7178             "    aaaa);",
7179             format("aaa(aaaa,\n" // one-per-line
7180                    "  aaaa,\n"
7181                    "    aaaa  );\n"
7182                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7183                    Style));
7184   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7185             "    aaaa);\n"
7186             "aaa(aaaa, aaaa,\n"
7187             "    aaaa);",
7188             format("aaa(aaaa,  aaaa,\n" // bin-packed
7189                    "    aaaa  );\n"
7190                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7191                    Style));
7192 }
7193 
7194 TEST_F(FormatTest, FormatsBuilderPattern) {
7195   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7196                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7197                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7198                "    .StartsWith(\".init\", ORDER_INIT)\n"
7199                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7200                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7201                "    .Default(ORDER_TEXT);\n");
7202 
7203   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7204                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7205   verifyFormat("aaaaaaa->aaaaaaa\n"
7206                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7207                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7208                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7209   verifyFormat(
7210       "aaaaaaa->aaaaaaa\n"
7211       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7212       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7213   verifyFormat(
7214       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7215       "    aaaaaaaaaaaaaa);");
7216   verifyFormat(
7217       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7218       "    aaaaaa->aaaaaaaaaaaa()\n"
7219       "        ->aaaaaaaaaaaaaaaa(\n"
7220       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7221       "        ->aaaaaaaaaaaaaaaaa();");
7222   verifyGoogleFormat(
7223       "void f() {\n"
7224       "  someo->Add((new util::filetools::Handler(dir))\n"
7225       "                 ->OnEvent1(NewPermanentCallback(\n"
7226       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7227       "                 ->OnEvent2(NewPermanentCallback(\n"
7228       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7229       "                 ->OnEvent3(NewPermanentCallback(\n"
7230       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7231       "                 ->OnEvent5(NewPermanentCallback(\n"
7232       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7233       "                 ->OnEvent6(NewPermanentCallback(\n"
7234       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7235       "}");
7236 
7237   verifyFormat(
7238       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7239   verifyFormat("aaaaaaaaaaaaaaa()\n"
7240                "    .aaaaaaaaaaaaaaa()\n"
7241                "    .aaaaaaaaaaaaaaa()\n"
7242                "    .aaaaaaaaaaaaaaa()\n"
7243                "    .aaaaaaaaaaaaaaa();");
7244   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7245                "    .aaaaaaaaaaaaaaa()\n"
7246                "    .aaaaaaaaaaaaaaa()\n"
7247                "    .aaaaaaaaaaaaaaa();");
7248   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7249                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7250                "    .aaaaaaaaaaaaaaa();");
7251   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7252                "    ->aaaaaaaaaaaaaae(0)\n"
7253                "    ->aaaaaaaaaaaaaaa();");
7254 
7255   // Don't linewrap after very short segments.
7256   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7257                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7258                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7259   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7260                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7261                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7262   verifyFormat("aaa()\n"
7263                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7264                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7265                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7266 
7267   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7268                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7269                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7270   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7271                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7272                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7273 
7274   // Prefer not to break after empty parentheses.
7275   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7276                "    First->LastNewlineOffset);");
7277 
7278   // Prefer not to create "hanging" indents.
7279   verifyFormat(
7280       "return !soooooooooooooome_map\n"
7281       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7282       "            .second;");
7283   verifyFormat(
7284       "return aaaaaaaaaaaaaaaa\n"
7285       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7286       "    .aaaa(aaaaaaaaaaaaaa);");
7287   // No hanging indent here.
7288   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7289                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7290   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7291                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7292   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7293                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7294                getLLVMStyleWithColumns(60));
7295   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7296                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7297                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7298                getLLVMStyleWithColumns(59));
7299   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7300                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7301                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7302 
7303   // Dont break if only closing statements before member call
7304   verifyFormat("test() {\n"
7305                "  ([]() -> {\n"
7306                "    int b = 32;\n"
7307                "    return 3;\n"
7308                "  }).foo();\n"
7309                "}");
7310   verifyFormat("test() {\n"
7311                "  (\n"
7312                "      []() -> {\n"
7313                "        int b = 32;\n"
7314                "        return 3;\n"
7315                "      },\n"
7316                "      foo, bar)\n"
7317                "      .foo();\n"
7318                "}");
7319   verifyFormat("test() {\n"
7320                "  ([]() -> {\n"
7321                "    int b = 32;\n"
7322                "    return 3;\n"
7323                "  })\n"
7324                "      .foo()\n"
7325                "      .bar();\n"
7326                "}");
7327   verifyFormat("test() {\n"
7328                "  ([]() -> {\n"
7329                "    int b = 32;\n"
7330                "    return 3;\n"
7331                "  })\n"
7332                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7333                "           \"bbbb\");\n"
7334                "}",
7335                getLLVMStyleWithColumns(30));
7336 }
7337 
7338 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7339   verifyFormat(
7340       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7341       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7342   verifyFormat(
7343       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7344       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7345 
7346   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7347                "    ccccccccccccccccccccccccc) {\n}");
7348   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7349                "    ccccccccccccccccccccccccc) {\n}");
7350 
7351   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7352                "    ccccccccccccccccccccccccc) {\n}");
7353   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7354                "    ccccccccccccccccccccccccc) {\n}");
7355 
7356   verifyFormat(
7357       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7358       "    ccccccccccccccccccccccccc) {\n}");
7359   verifyFormat(
7360       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7361       "    ccccccccccccccccccccccccc) {\n}");
7362 
7363   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7364                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7365                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7366                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7367   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7368                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7369                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7370                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7371 
7372   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7373                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7374                "    aaaaaaaaaaaaaaa != aa) {\n}");
7375   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7376                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7377                "    aaaaaaaaaaaaaaa != aa) {\n}");
7378 }
7379 
7380 TEST_F(FormatTest, BreaksAfterAssignments) {
7381   verifyFormat(
7382       "unsigned Cost =\n"
7383       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7384       "                        SI->getPointerAddressSpaceee());\n");
7385   verifyFormat(
7386       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7387       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7388 
7389   verifyFormat(
7390       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7391       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7392   verifyFormat("unsigned OriginalStartColumn =\n"
7393                "    SourceMgr.getSpellingColumnNumber(\n"
7394                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7395                "    1;");
7396 }
7397 
7398 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7399   FormatStyle Style = getLLVMStyle();
7400   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7401                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7402                Style);
7403 
7404   Style.PenaltyBreakAssignment = 20;
7405   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7406                "                                 cccccccccccccccccccccccccc;",
7407                Style);
7408 }
7409 
7410 TEST_F(FormatTest, AlignsAfterAssignments) {
7411   verifyFormat(
7412       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7413       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7414   verifyFormat(
7415       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7416       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7417   verifyFormat(
7418       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7419       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7420   verifyFormat(
7421       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7422       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7423   verifyFormat(
7424       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7425       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7426       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7427 }
7428 
7429 TEST_F(FormatTest, AlignsAfterReturn) {
7430   verifyFormat(
7431       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7432       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7433   verifyFormat(
7434       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7435       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7436   verifyFormat(
7437       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7438       "       aaaaaaaaaaaaaaaaaaaaaa();");
7439   verifyFormat(
7440       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7441       "        aaaaaaaaaaaaaaaaaaaaaa());");
7442   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7443                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7444   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7445                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7446                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7447   verifyFormat("return\n"
7448                "    // true if code is one of a or b.\n"
7449                "    code == a || code == b;");
7450 }
7451 
7452 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7453   verifyFormat(
7454       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7455       "                                                aaaaaaaaa aaaaaaa) {}");
7456   verifyFormat(
7457       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7458       "                                               aaaaaaaaaaa aaaaaaaaa);");
7459   verifyFormat(
7460       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7461       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7462   FormatStyle Style = getLLVMStyle();
7463   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7464   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7465                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7466                Style);
7467   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7468                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
7469                Style);
7470   verifyFormat("SomeLongVariableName->someFunction(\n"
7471                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
7472                Style);
7473   verifyFormat(
7474       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7475       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7476       Style);
7477   verifyFormat(
7478       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7479       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7480       Style);
7481   verifyFormat(
7482       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7483       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7484       Style);
7485 
7486   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
7487                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
7488                "        b));",
7489                Style);
7490 
7491   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7492   Style.BinPackArguments = false;
7493   Style.BinPackParameters = false;
7494   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7495                "    aaaaaaaaaaa aaaaaaaa,\n"
7496                "    aaaaaaaaa aaaaaaa,\n"
7497                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7498                Style);
7499   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7500                "    aaaaaaaaaaa aaaaaaaaa,\n"
7501                "    aaaaaaaaaaa aaaaaaaaa,\n"
7502                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7503                Style);
7504   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
7505                "    aaaaaaaaaaaaaaa,\n"
7506                "    aaaaaaaaaaaaaaaaaaaaa,\n"
7507                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7508                Style);
7509   verifyFormat(
7510       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
7511       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7512       Style);
7513   verifyFormat(
7514       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
7515       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7516       Style);
7517   verifyFormat(
7518       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7519       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7520       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
7521       "    aaaaaaaaaaaaaaaa);",
7522       Style);
7523   verifyFormat(
7524       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7525       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7526       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
7527       "    aaaaaaaaaaaaaaaa);",
7528       Style);
7529 }
7530 
7531 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
7532   FormatStyle Style = getLLVMStyleWithColumns(40);
7533   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7534                "          bbbbbbbbbbbbbbbbbbbbbb);",
7535                Style);
7536   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7537   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7538   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7539                "          bbbbbbbbbbbbbbbbbbbbbb);",
7540                Style);
7541   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7542   Style.AlignOperands = FormatStyle::OAS_Align;
7543   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7544                "          bbbbbbbbbbbbbbbbbbbbbb);",
7545                Style);
7546   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7547   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7548   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7549                "    bbbbbbbbbbbbbbbbbbbbbb);",
7550                Style);
7551 }
7552 
7553 TEST_F(FormatTest, BreaksConditionalExpressions) {
7554   verifyFormat(
7555       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7556       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7557       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7558   verifyFormat(
7559       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7560       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7561       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7562   verifyFormat(
7563       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7564       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7565   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
7566                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7567                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7568   verifyFormat(
7569       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
7570       "                                                    : aaaaaaaaaaaaa);");
7571   verifyFormat(
7572       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7573       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7574       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7575       "                   aaaaaaaaaaaaa);");
7576   verifyFormat(
7577       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7578       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7579       "                   aaaaaaaaaaaaa);");
7580   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7581                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7582                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7583                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7584                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7585   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7586                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7587                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7588                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7589                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7590                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7591                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7592   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7593                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7594                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7595                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7596                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7597   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7598                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7599                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7600   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7601                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7602                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7603                "        : aaaaaaaaaaaaaaaa;");
7604   verifyFormat(
7605       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7606       "    ? aaaaaaaaaaaaaaa\n"
7607       "    : aaaaaaaaaaaaaaa;");
7608   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7609                "          aaaaaaaaa\n"
7610                "      ? b\n"
7611                "      : c);");
7612   verifyFormat("return aaaa == bbbb\n"
7613                "           // comment\n"
7614                "           ? aaaa\n"
7615                "           : bbbb;");
7616   verifyFormat("unsigned Indent =\n"
7617                "    format(TheLine.First,\n"
7618                "           IndentForLevel[TheLine.Level] >= 0\n"
7619                "               ? IndentForLevel[TheLine.Level]\n"
7620                "               : TheLine * 2,\n"
7621                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7622                getLLVMStyleWithColumns(60));
7623   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7624                "                  ? aaaaaaaaaaaaaaa\n"
7625                "                  : bbbbbbbbbbbbbbb //\n"
7626                "                        ? ccccccccccccccc\n"
7627                "                        : ddddddddddddddd;");
7628   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7629                "                  ? aaaaaaaaaaaaaaa\n"
7630                "                  : (bbbbbbbbbbbbbbb //\n"
7631                "                         ? ccccccccccccccc\n"
7632                "                         : ddddddddddddddd);");
7633   verifyFormat(
7634       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7635       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7636       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
7637       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
7638       "                                      : aaaaaaaaaa;");
7639   verifyFormat(
7640       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7641       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
7642       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7643 
7644   FormatStyle NoBinPacking = getLLVMStyle();
7645   NoBinPacking.BinPackArguments = false;
7646   verifyFormat(
7647       "void f() {\n"
7648       "  g(aaa,\n"
7649       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7650       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7651       "        ? aaaaaaaaaaaaaaa\n"
7652       "        : aaaaaaaaaaaaaaa);\n"
7653       "}",
7654       NoBinPacking);
7655   verifyFormat(
7656       "void f() {\n"
7657       "  g(aaa,\n"
7658       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7659       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7660       "        ?: aaaaaaaaaaaaaaa);\n"
7661       "}",
7662       NoBinPacking);
7663 
7664   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
7665                "             // comment.\n"
7666                "             ccccccccccccccccccccccccccccccccccccccc\n"
7667                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7668                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
7669 
7670   // Assignments in conditional expressions. Apparently not uncommon :-(.
7671   verifyFormat("return a != b\n"
7672                "           // comment\n"
7673                "           ? a = b\n"
7674                "           : a = b;");
7675   verifyFormat("return a != b\n"
7676                "           // comment\n"
7677                "           ? a = a != b\n"
7678                "                     // comment\n"
7679                "                     ? a = b\n"
7680                "                     : a\n"
7681                "           : a;\n");
7682   verifyFormat("return a != b\n"
7683                "           // comment\n"
7684                "           ? a\n"
7685                "           : a = a != b\n"
7686                "                     // comment\n"
7687                "                     ? a = b\n"
7688                "                     : a;");
7689 
7690   // Chained conditionals
7691   FormatStyle Style = getLLVMStyleWithColumns(70);
7692   Style.AlignOperands = FormatStyle::OAS_Align;
7693   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7694                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7695                "                        : 3333333333333333;",
7696                Style);
7697   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7698                "       : bbbbbbbbbb     ? 2222222222222222\n"
7699                "                        : 3333333333333333;",
7700                Style);
7701   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
7702                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
7703                "                          : 3333333333333333;",
7704                Style);
7705   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7706                "       : bbbbbbbbbbbbbb ? 222222\n"
7707                "                        : 333333;",
7708                Style);
7709   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7710                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7711                "       : cccccccccccccc ? 3333333333333333\n"
7712                "                        : 4444444444444444;",
7713                Style);
7714   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
7715                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7716                "                        : 3333333333333333;",
7717                Style);
7718   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7719                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7720                "                        : (aaa ? bbb : ccc);",
7721                Style);
7722   verifyFormat(
7723       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7724       "                                             : cccccccccccccccccc)\n"
7725       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7726       "                        : 3333333333333333;",
7727       Style);
7728   verifyFormat(
7729       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7730       "                                             : cccccccccccccccccc)\n"
7731       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7732       "                        : 3333333333333333;",
7733       Style);
7734   verifyFormat(
7735       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7736       "                                             : dddddddddddddddddd)\n"
7737       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7738       "                        : 3333333333333333;",
7739       Style);
7740   verifyFormat(
7741       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7742       "                                             : dddddddddddddddddd)\n"
7743       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7744       "                        : 3333333333333333;",
7745       Style);
7746   verifyFormat(
7747       "return aaaaaaaaa        ? 1111111111111111\n"
7748       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7749       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7750       "                                             : dddddddddddddddddd)\n",
7751       Style);
7752   verifyFormat(
7753       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7754       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7755       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7756       "                                             : cccccccccccccccccc);",
7757       Style);
7758   verifyFormat(
7759       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7760       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7761       "                                             : eeeeeeeeeeeeeeeeee)\n"
7762       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7763       "                        : 3333333333333333;",
7764       Style);
7765   verifyFormat(
7766       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
7767       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7768       "                                             : eeeeeeeeeeeeeeeeee)\n"
7769       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7770       "                        : 3333333333333333;",
7771       Style);
7772   verifyFormat(
7773       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7774       "                           : cccccccccccc    ? dddddddddddddddddd\n"
7775       "                                             : eeeeeeeeeeeeeeeeee)\n"
7776       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7777       "                        : 3333333333333333;",
7778       Style);
7779   verifyFormat(
7780       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7781       "                                             : cccccccccccccccccc\n"
7782       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7783       "                        : 3333333333333333;",
7784       Style);
7785   verifyFormat(
7786       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7787       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
7788       "                                             : eeeeeeeeeeeeeeeeee\n"
7789       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7790       "                        : 3333333333333333;",
7791       Style);
7792   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
7793                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
7794                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
7795                "                                   : eeeeeeeeeeeeeeeeee)\n"
7796                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7797                "                             : 3333333333333333;",
7798                Style);
7799   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
7800                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7801                "             : cccccccccccccccc ? dddddddddddddddddd\n"
7802                "                                : eeeeeeeeeeeeeeeeee\n"
7803                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7804                "                                 : 3333333333333333;",
7805                Style);
7806 
7807   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7808   Style.BreakBeforeTernaryOperators = false;
7809   // FIXME: Aligning the question marks is weird given DontAlign.
7810   // Consider disabling this alignment in this case. Also check whether this
7811   // will render the adjustment from https://reviews.llvm.org/D82199
7812   // unnecessary.
7813   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
7814                "    bbbb                ? cccccccccccccccccc :\n"
7815                "                          ddddd;\n",
7816                Style);
7817 
7818   EXPECT_EQ(
7819       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7820       "    /*\n"
7821       "     */\n"
7822       "    function() {\n"
7823       "      try {\n"
7824       "        return JJJJJJJJJJJJJJ(\n"
7825       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7826       "      }\n"
7827       "    } :\n"
7828       "    function() {};",
7829       format(
7830           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7831           "     /*\n"
7832           "      */\n"
7833           "     function() {\n"
7834           "      try {\n"
7835           "        return JJJJJJJJJJJJJJ(\n"
7836           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7837           "      }\n"
7838           "    } :\n"
7839           "    function() {};",
7840           getGoogleStyle(FormatStyle::LK_JavaScript)));
7841 }
7842 
7843 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
7844   FormatStyle Style = getLLVMStyleWithColumns(70);
7845   Style.BreakBeforeTernaryOperators = false;
7846   verifyFormat(
7847       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7848       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7849       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7850       Style);
7851   verifyFormat(
7852       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7853       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7854       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7855       Style);
7856   verifyFormat(
7857       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7858       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7859       Style);
7860   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
7861                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7862                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7863                Style);
7864   verifyFormat(
7865       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
7866       "                                                      aaaaaaaaaaaaa);",
7867       Style);
7868   verifyFormat(
7869       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7870       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7871       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7872       "                   aaaaaaaaaaaaa);",
7873       Style);
7874   verifyFormat(
7875       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7876       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7877       "                   aaaaaaaaaaaaa);",
7878       Style);
7879   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7880                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7881                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7882                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7883                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7884                Style);
7885   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7886                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7887                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7888                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7889                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7890                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7891                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7892                Style);
7893   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7894                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
7895                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7896                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7897                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7898                Style);
7899   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7900                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7901                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7902                Style);
7903   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7904                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7905                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7906                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7907                Style);
7908   verifyFormat(
7909       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7910       "    aaaaaaaaaaaaaaa :\n"
7911       "    aaaaaaaaaaaaaaa;",
7912       Style);
7913   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7914                "          aaaaaaaaa ?\n"
7915                "      b :\n"
7916                "      c);",
7917                Style);
7918   verifyFormat("unsigned Indent =\n"
7919                "    format(TheLine.First,\n"
7920                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
7921                "               IndentForLevel[TheLine.Level] :\n"
7922                "               TheLine * 2,\n"
7923                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7924                Style);
7925   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
7926                "                  aaaaaaaaaaaaaaa :\n"
7927                "                  bbbbbbbbbbbbbbb ? //\n"
7928                "                      ccccccccccccccc :\n"
7929                "                      ddddddddddddddd;",
7930                Style);
7931   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
7932                "                  aaaaaaaaaaaaaaa :\n"
7933                "                  (bbbbbbbbbbbbbbb ? //\n"
7934                "                       ccccccccccccccc :\n"
7935                "                       ddddddddddddddd);",
7936                Style);
7937   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7938                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
7939                "            ccccccccccccccccccccccccccc;",
7940                Style);
7941   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7942                "           aaaaa :\n"
7943                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
7944                Style);
7945 
7946   // Chained conditionals
7947   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7948                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7949                "                          3333333333333333;",
7950                Style);
7951   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7952                "       bbbbbbbbbb       ? 2222222222222222 :\n"
7953                "                          3333333333333333;",
7954                Style);
7955   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
7956                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7957                "                          3333333333333333;",
7958                Style);
7959   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7960                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
7961                "                          333333;",
7962                Style);
7963   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7964                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7965                "       cccccccccccccccc ? 3333333333333333 :\n"
7966                "                          4444444444444444;",
7967                Style);
7968   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
7969                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7970                "                          3333333333333333;",
7971                Style);
7972   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7973                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7974                "                          (aaa ? bbb : ccc);",
7975                Style);
7976   verifyFormat(
7977       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7978       "                                               cccccccccccccccccc) :\n"
7979       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7980       "                          3333333333333333;",
7981       Style);
7982   verifyFormat(
7983       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7984       "                                               cccccccccccccccccc) :\n"
7985       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7986       "                          3333333333333333;",
7987       Style);
7988   verifyFormat(
7989       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7990       "                                               dddddddddddddddddd) :\n"
7991       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7992       "                          3333333333333333;",
7993       Style);
7994   verifyFormat(
7995       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7996       "                                               dddddddddddddddddd) :\n"
7997       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7998       "                          3333333333333333;",
7999       Style);
8000   verifyFormat(
8001       "return aaaaaaaaa        ? 1111111111111111 :\n"
8002       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8003       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8004       "                                               dddddddddddddddddd)\n",
8005       Style);
8006   verifyFormat(
8007       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8008       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8009       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8010       "                                               cccccccccccccccccc);",
8011       Style);
8012   verifyFormat(
8013       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8014       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8015       "                                               eeeeeeeeeeeeeeeeee) :\n"
8016       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8017       "                          3333333333333333;",
8018       Style);
8019   verifyFormat(
8020       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8021       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8022       "                                               eeeeeeeeeeeeeeeeee) :\n"
8023       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8024       "                          3333333333333333;",
8025       Style);
8026   verifyFormat(
8027       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8028       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8029       "                                               eeeeeeeeeeeeeeeeee) :\n"
8030       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8031       "                          3333333333333333;",
8032       Style);
8033   verifyFormat(
8034       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8035       "                                               cccccccccccccccccc :\n"
8036       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8037       "                          3333333333333333;",
8038       Style);
8039   verifyFormat(
8040       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8041       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8042       "                                               eeeeeeeeeeeeeeeeee :\n"
8043       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8044       "                          3333333333333333;",
8045       Style);
8046   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8047                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8048                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8049                "                                 eeeeeeeeeeeeeeeeee) :\n"
8050                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8051                "                               3333333333333333;",
8052                Style);
8053   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8054                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8055                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8056                "                                  eeeeeeeeeeeeeeeeee :\n"
8057                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8058                "                               3333333333333333;",
8059                Style);
8060 }
8061 
8062 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8063   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8064                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8065   verifyFormat("bool a = true, b = false;");
8066 
8067   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8068                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8069                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8070                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8071   verifyFormat(
8072       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8073       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8074       "     d = e && f;");
8075   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8076                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8077   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8078                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8079   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8080                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8081 
8082   FormatStyle Style = getGoogleStyle();
8083   Style.PointerAlignment = FormatStyle::PAS_Left;
8084   Style.DerivePointerAlignment = false;
8085   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8086                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8087                "    *b = bbbbbbbbbbbbbbbbbbb;",
8088                Style);
8089   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8090                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8091                Style);
8092   verifyFormat("vector<int*> a, b;", Style);
8093   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8094 }
8095 
8096 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8097   verifyFormat("arr[foo ? bar : baz];");
8098   verifyFormat("f()[foo ? bar : baz];");
8099   verifyFormat("(a + b)[foo ? bar : baz];");
8100   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8101 }
8102 
8103 TEST_F(FormatTest, AlignsStringLiterals) {
8104   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8105                "                                      \"short literal\");");
8106   verifyFormat(
8107       "looooooooooooooooooooooooongFunction(\n"
8108       "    \"short literal\"\n"
8109       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8110   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8111                "             \" string literals\",\n"
8112                "             and, other, parameters);");
8113   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8114             "      \"5678\";",
8115             format("fun + \"1243\" /* comment */\n"
8116                    "    \"5678\";",
8117                    getLLVMStyleWithColumns(28)));
8118   EXPECT_EQ(
8119       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8120       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8121       "         \"aaaaaaaaaaaaaaaa\";",
8122       format("aaaaaa ="
8123              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8124              "aaaaaaaaaaaaaaaaaaaaa\" "
8125              "\"aaaaaaaaaaaaaaaa\";"));
8126   verifyFormat("a = a + \"a\"\n"
8127                "        \"a\"\n"
8128                "        \"a\";");
8129   verifyFormat("f(\"a\", \"b\"\n"
8130                "       \"c\");");
8131 
8132   verifyFormat(
8133       "#define LL_FORMAT \"ll\"\n"
8134       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8135       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8136 
8137   verifyFormat("#define A(X)          \\\n"
8138                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8139                "  \"ccccc\"",
8140                getLLVMStyleWithColumns(23));
8141   verifyFormat("#define A \"def\"\n"
8142                "f(\"abc\" A \"ghi\"\n"
8143                "  \"jkl\");");
8144 
8145   verifyFormat("f(L\"a\"\n"
8146                "  L\"b\");");
8147   verifyFormat("#define A(X)            \\\n"
8148                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8149                "  L\"ccccc\"",
8150                getLLVMStyleWithColumns(25));
8151 
8152   verifyFormat("f(@\"a\"\n"
8153                "  @\"b\");");
8154   verifyFormat("NSString s = @\"a\"\n"
8155                "             @\"b\"\n"
8156                "             @\"c\";");
8157   verifyFormat("NSString s = @\"a\"\n"
8158                "              \"b\"\n"
8159                "              \"c\";");
8160 }
8161 
8162 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8163   FormatStyle Style = getLLVMStyle();
8164   // No declarations or definitions should be moved to own line.
8165   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8166   verifyFormat("class A {\n"
8167                "  int f() { return 1; }\n"
8168                "  int g();\n"
8169                "};\n"
8170                "int f() { return 1; }\n"
8171                "int g();\n",
8172                Style);
8173 
8174   // All declarations and definitions should have the return type moved to its
8175   // own line.
8176   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8177   Style.TypenameMacros = {"LIST"};
8178   verifyFormat("SomeType\n"
8179                "funcdecl(LIST(uint64_t));",
8180                Style);
8181   verifyFormat("class E {\n"
8182                "  int\n"
8183                "  f() {\n"
8184                "    return 1;\n"
8185                "  }\n"
8186                "  int\n"
8187                "  g();\n"
8188                "};\n"
8189                "int\n"
8190                "f() {\n"
8191                "  return 1;\n"
8192                "}\n"
8193                "int\n"
8194                "g();\n",
8195                Style);
8196 
8197   // Top-level definitions, and no kinds of declarations should have the
8198   // return type moved to its own line.
8199   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8200   verifyFormat("class B {\n"
8201                "  int f() { return 1; }\n"
8202                "  int g();\n"
8203                "};\n"
8204                "int\n"
8205                "f() {\n"
8206                "  return 1;\n"
8207                "}\n"
8208                "int g();\n",
8209                Style);
8210 
8211   // Top-level definitions and declarations should have the return type moved
8212   // to its own line.
8213   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8214   verifyFormat("class C {\n"
8215                "  int f() { return 1; }\n"
8216                "  int g();\n"
8217                "};\n"
8218                "int\n"
8219                "f() {\n"
8220                "  return 1;\n"
8221                "}\n"
8222                "int\n"
8223                "g();\n",
8224                Style);
8225 
8226   // All definitions should have the return type moved to its own line, but no
8227   // kinds of declarations.
8228   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8229   verifyFormat("class D {\n"
8230                "  int\n"
8231                "  f() {\n"
8232                "    return 1;\n"
8233                "  }\n"
8234                "  int g();\n"
8235                "};\n"
8236                "int\n"
8237                "f() {\n"
8238                "  return 1;\n"
8239                "}\n"
8240                "int g();\n",
8241                Style);
8242   verifyFormat("const char *\n"
8243                "f(void) {\n" // Break here.
8244                "  return \"\";\n"
8245                "}\n"
8246                "const char *bar(void);\n", // No break here.
8247                Style);
8248   verifyFormat("template <class T>\n"
8249                "T *\n"
8250                "f(T &c) {\n" // Break here.
8251                "  return NULL;\n"
8252                "}\n"
8253                "template <class T> T *f(T &c);\n", // No break here.
8254                Style);
8255   verifyFormat("class C {\n"
8256                "  int\n"
8257                "  operator+() {\n"
8258                "    return 1;\n"
8259                "  }\n"
8260                "  int\n"
8261                "  operator()() {\n"
8262                "    return 1;\n"
8263                "  }\n"
8264                "};\n",
8265                Style);
8266   verifyFormat("void\n"
8267                "A::operator()() {}\n"
8268                "void\n"
8269                "A::operator>>() {}\n"
8270                "void\n"
8271                "A::operator+() {}\n"
8272                "void\n"
8273                "A::operator*() {}\n"
8274                "void\n"
8275                "A::operator->() {}\n"
8276                "void\n"
8277                "A::operator void *() {}\n"
8278                "void\n"
8279                "A::operator void &() {}\n"
8280                "void\n"
8281                "A::operator void &&() {}\n"
8282                "void\n"
8283                "A::operator char *() {}\n"
8284                "void\n"
8285                "A::operator[]() {}\n"
8286                "void\n"
8287                "A::operator!() {}\n"
8288                "void\n"
8289                "A::operator**() {}\n"
8290                "void\n"
8291                "A::operator<Foo> *() {}\n"
8292                "void\n"
8293                "A::operator<Foo> **() {}\n"
8294                "void\n"
8295                "A::operator<Foo> &() {}\n"
8296                "void\n"
8297                "A::operator void **() {}\n",
8298                Style);
8299   verifyFormat("constexpr auto\n"
8300                "operator()() const -> reference {}\n"
8301                "constexpr auto\n"
8302                "operator>>() const -> reference {}\n"
8303                "constexpr auto\n"
8304                "operator+() const -> reference {}\n"
8305                "constexpr auto\n"
8306                "operator*() const -> reference {}\n"
8307                "constexpr auto\n"
8308                "operator->() const -> reference {}\n"
8309                "constexpr auto\n"
8310                "operator++() const -> reference {}\n"
8311                "constexpr auto\n"
8312                "operator void *() const -> reference {}\n"
8313                "constexpr auto\n"
8314                "operator void **() const -> reference {}\n"
8315                "constexpr auto\n"
8316                "operator void *() const -> reference {}\n"
8317                "constexpr auto\n"
8318                "operator void &() const -> reference {}\n"
8319                "constexpr auto\n"
8320                "operator void &&() const -> reference {}\n"
8321                "constexpr auto\n"
8322                "operator char *() const -> reference {}\n"
8323                "constexpr auto\n"
8324                "operator!() const -> reference {}\n"
8325                "constexpr auto\n"
8326                "operator[]() const -> reference {}\n",
8327                Style);
8328   verifyFormat("void *operator new(std::size_t s);", // No break here.
8329                Style);
8330   verifyFormat("void *\n"
8331                "operator new(std::size_t s) {}",
8332                Style);
8333   verifyFormat("void *\n"
8334                "operator delete[](void *ptr) {}",
8335                Style);
8336   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8337   verifyFormat("const char *\n"
8338                "f(void)\n" // Break here.
8339                "{\n"
8340                "  return \"\";\n"
8341                "}\n"
8342                "const char *bar(void);\n", // No break here.
8343                Style);
8344   verifyFormat("template <class T>\n"
8345                "T *\n"     // Problem here: no line break
8346                "f(T &c)\n" // Break here.
8347                "{\n"
8348                "  return NULL;\n"
8349                "}\n"
8350                "template <class T> T *f(T &c);\n", // No break here.
8351                Style);
8352   verifyFormat("int\n"
8353                "foo(A<bool> a)\n"
8354                "{\n"
8355                "  return a;\n"
8356                "}\n",
8357                Style);
8358   verifyFormat("int\n"
8359                "foo(A<8> a)\n"
8360                "{\n"
8361                "  return a;\n"
8362                "}\n",
8363                Style);
8364   verifyFormat("int\n"
8365                "foo(A<B<bool>, 8> a)\n"
8366                "{\n"
8367                "  return a;\n"
8368                "}\n",
8369                Style);
8370   verifyFormat("int\n"
8371                "foo(A<B<8>, bool> a)\n"
8372                "{\n"
8373                "  return a;\n"
8374                "}\n",
8375                Style);
8376   verifyFormat("int\n"
8377                "foo(A<B<bool>, bool> a)\n"
8378                "{\n"
8379                "  return a;\n"
8380                "}\n",
8381                Style);
8382   verifyFormat("int\n"
8383                "foo(A<B<8>, 8> a)\n"
8384                "{\n"
8385                "  return a;\n"
8386                "}\n",
8387                Style);
8388 
8389   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8390   Style.BraceWrapping.AfterFunction = true;
8391   verifyFormat("int f(i);\n" // No break here.
8392                "int\n"       // Break here.
8393                "f(i)\n"
8394                "{\n"
8395                "  return i + 1;\n"
8396                "}\n"
8397                "int\n" // Break here.
8398                "f(i)\n"
8399                "{\n"
8400                "  return i + 1;\n"
8401                "};",
8402                Style);
8403   verifyFormat("int f(a, b, c);\n" // No break here.
8404                "int\n"             // Break here.
8405                "f(a, b, c)\n"      // Break here.
8406                "short a, b;\n"
8407                "float c;\n"
8408                "{\n"
8409                "  return a + b < c;\n"
8410                "}\n"
8411                "int\n"        // Break here.
8412                "f(a, b, c)\n" // Break here.
8413                "short a, b;\n"
8414                "float c;\n"
8415                "{\n"
8416                "  return a + b < c;\n"
8417                "};",
8418                Style);
8419   verifyFormat("byte *\n" // Break here.
8420                "f(a)\n"   // Break here.
8421                "byte a[];\n"
8422                "{\n"
8423                "  return a;\n"
8424                "}",
8425                Style);
8426   verifyFormat("bool f(int a, int) override;\n"
8427                "Bar g(int a, Bar) final;\n"
8428                "Bar h(a, Bar) final;",
8429                Style);
8430   verifyFormat("int\n"
8431                "f(a)",
8432                Style);
8433   verifyFormat("bool\n"
8434                "f(size_t = 0, bool b = false)\n"
8435                "{\n"
8436                "  return !b;\n"
8437                "}",
8438                Style);
8439 
8440   // The return breaking style doesn't affect:
8441   // * function and object definitions with attribute-like macros
8442   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8443                "    ABSL_GUARDED_BY(mutex) = {};",
8444                getGoogleStyleWithColumns(40));
8445   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8446                "    ABSL_GUARDED_BY(mutex);  // comment",
8447                getGoogleStyleWithColumns(40));
8448   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8449                "    ABSL_GUARDED_BY(mutex1)\n"
8450                "        ABSL_GUARDED_BY(mutex2);",
8451                getGoogleStyleWithColumns(40));
8452   verifyFormat("Tttttt f(int a, int b)\n"
8453                "    ABSL_GUARDED_BY(mutex1)\n"
8454                "        ABSL_GUARDED_BY(mutex2);",
8455                getGoogleStyleWithColumns(40));
8456   // * typedefs
8457   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
8458 
8459   Style = getGNUStyle();
8460 
8461   // Test for comments at the end of function declarations.
8462   verifyFormat("void\n"
8463                "foo (int a, /*abc*/ int b) // def\n"
8464                "{\n"
8465                "}\n",
8466                Style);
8467 
8468   verifyFormat("void\n"
8469                "foo (int a, /* abc */ int b) /* def */\n"
8470                "{\n"
8471                "}\n",
8472                Style);
8473 
8474   // Definitions that should not break after return type
8475   verifyFormat("void foo (int a, int b); // def\n", Style);
8476   verifyFormat("void foo (int a, int b); /* def */\n", Style);
8477   verifyFormat("void foo (int a, int b);\n", Style);
8478 }
8479 
8480 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
8481   FormatStyle NoBreak = getLLVMStyle();
8482   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
8483   FormatStyle Break = getLLVMStyle();
8484   Break.AlwaysBreakBeforeMultilineStrings = true;
8485   verifyFormat("aaaa = \"bbbb\"\n"
8486                "       \"cccc\";",
8487                NoBreak);
8488   verifyFormat("aaaa =\n"
8489                "    \"bbbb\"\n"
8490                "    \"cccc\";",
8491                Break);
8492   verifyFormat("aaaa(\"bbbb\"\n"
8493                "     \"cccc\");",
8494                NoBreak);
8495   verifyFormat("aaaa(\n"
8496                "    \"bbbb\"\n"
8497                "    \"cccc\");",
8498                Break);
8499   verifyFormat("aaaa(qqq, \"bbbb\"\n"
8500                "          \"cccc\");",
8501                NoBreak);
8502   verifyFormat("aaaa(qqq,\n"
8503                "     \"bbbb\"\n"
8504                "     \"cccc\");",
8505                Break);
8506   verifyFormat("aaaa(qqq,\n"
8507                "     L\"bbbb\"\n"
8508                "     L\"cccc\");",
8509                Break);
8510   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
8511                "                      \"bbbb\"));",
8512                Break);
8513   verifyFormat("string s = someFunction(\n"
8514                "    \"abc\"\n"
8515                "    \"abc\");",
8516                Break);
8517 
8518   // As we break before unary operators, breaking right after them is bad.
8519   verifyFormat("string foo = abc ? \"x\"\n"
8520                "                   \"blah blah blah blah blah blah\"\n"
8521                "                 : \"y\";",
8522                Break);
8523 
8524   // Don't break if there is no column gain.
8525   verifyFormat("f(\"aaaa\"\n"
8526                "  \"bbbb\");",
8527                Break);
8528 
8529   // Treat literals with escaped newlines like multi-line string literals.
8530   EXPECT_EQ("x = \"a\\\n"
8531             "b\\\n"
8532             "c\";",
8533             format("x = \"a\\\n"
8534                    "b\\\n"
8535                    "c\";",
8536                    NoBreak));
8537   EXPECT_EQ("xxxx =\n"
8538             "    \"a\\\n"
8539             "b\\\n"
8540             "c\";",
8541             format("xxxx = \"a\\\n"
8542                    "b\\\n"
8543                    "c\";",
8544                    Break));
8545 
8546   EXPECT_EQ("NSString *const kString =\n"
8547             "    @\"aaaa\"\n"
8548             "    @\"bbbb\";",
8549             format("NSString *const kString = @\"aaaa\"\n"
8550                    "@\"bbbb\";",
8551                    Break));
8552 
8553   Break.ColumnLimit = 0;
8554   verifyFormat("const char *hello = \"hello llvm\";", Break);
8555 }
8556 
8557 TEST_F(FormatTest, AlignsPipes) {
8558   verifyFormat(
8559       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8560       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8561       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8562   verifyFormat(
8563       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
8564       "                     << aaaaaaaaaaaaaaaaaaaa;");
8565   verifyFormat(
8566       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8567       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8568   verifyFormat(
8569       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
8570       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8571   verifyFormat(
8572       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
8573       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
8574       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
8575   verifyFormat(
8576       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8577       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8578       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8579   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8580                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8581                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8582                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8583   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
8584                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
8585   verifyFormat(
8586       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8587       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8588   verifyFormat(
8589       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
8590       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
8591 
8592   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
8593                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
8594   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8595                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8596                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
8597                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
8598   verifyFormat("LOG_IF(aaa == //\n"
8599                "       bbb)\n"
8600                "    << a << b;");
8601 
8602   // But sometimes, breaking before the first "<<" is desirable.
8603   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8604                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
8605   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
8606                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8607                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8608   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
8609                "    << BEF << IsTemplate << Description << E->getType();");
8610   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8611                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8612                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8613   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8614                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8615                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8616                "    << aaa;");
8617 
8618   verifyFormat(
8619       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8620       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8621 
8622   // Incomplete string literal.
8623   EXPECT_EQ("llvm::errs() << \"\n"
8624             "             << a;",
8625             format("llvm::errs() << \"\n<<a;"));
8626 
8627   verifyFormat("void f() {\n"
8628                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
8629                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
8630                "}");
8631 
8632   // Handle 'endl'.
8633   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
8634                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8635   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8636 
8637   // Handle '\n'.
8638   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
8639                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8640   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
8641                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
8642   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
8643                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
8644   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8645 }
8646 
8647 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
8648   verifyFormat("return out << \"somepacket = {\\n\"\n"
8649                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
8650                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
8651                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
8652                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
8653                "           << \"}\";");
8654 
8655   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8656                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8657                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
8658   verifyFormat(
8659       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
8660       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
8661       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
8662       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
8663       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
8664   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
8665                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8666   verifyFormat(
8667       "void f() {\n"
8668       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
8669       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
8670       "}");
8671 
8672   // Breaking before the first "<<" is generally not desirable.
8673   verifyFormat(
8674       "llvm::errs()\n"
8675       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8676       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8677       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8678       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8679       getLLVMStyleWithColumns(70));
8680   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8681                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8682                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8683                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8684                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8685                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8686                getLLVMStyleWithColumns(70));
8687 
8688   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8689                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8690                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
8691   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8692                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8693                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
8694   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
8695                "           (aaaa + aaaa);",
8696                getLLVMStyleWithColumns(40));
8697   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
8698                "                  (aaaaaaa + aaaaa));",
8699                getLLVMStyleWithColumns(40));
8700   verifyFormat(
8701       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
8702       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
8703       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
8704 }
8705 
8706 TEST_F(FormatTest, UnderstandsEquals) {
8707   verifyFormat(
8708       "aaaaaaaaaaaaaaaaa =\n"
8709       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8710   verifyFormat(
8711       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8712       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8713   verifyFormat(
8714       "if (a) {\n"
8715       "  f();\n"
8716       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8717       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
8718       "}");
8719 
8720   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8721                "        100000000 + 10000000) {\n}");
8722 }
8723 
8724 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
8725   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8726                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
8727 
8728   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8729                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
8730 
8731   verifyFormat(
8732       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
8733       "                                                          Parameter2);");
8734 
8735   verifyFormat(
8736       "ShortObject->shortFunction(\n"
8737       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
8738       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
8739 
8740   verifyFormat("loooooooooooooongFunction(\n"
8741                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
8742 
8743   verifyFormat(
8744       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
8745       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
8746 
8747   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8748                "    .WillRepeatedly(Return(SomeValue));");
8749   verifyFormat("void f() {\n"
8750                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8751                "      .Times(2)\n"
8752                "      .WillRepeatedly(Return(SomeValue));\n"
8753                "}");
8754   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
8755                "    ccccccccccccccccccccccc);");
8756   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8757                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8758                "          .aaaaa(aaaaa),\n"
8759                "      aaaaaaaaaaaaaaaaaaaaa);");
8760   verifyFormat("void f() {\n"
8761                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8762                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
8763                "}");
8764   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8765                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8766                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8767                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8768                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
8769   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8770                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8771                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8772                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
8773                "}");
8774 
8775   // Here, it is not necessary to wrap at "." or "->".
8776   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
8777                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8778   verifyFormat(
8779       "aaaaaaaaaaa->aaaaaaaaa(\n"
8780       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8781       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
8782 
8783   verifyFormat(
8784       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8785       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
8786   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
8787                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8788   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
8789                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8790 
8791   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8792                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8793                "    .a();");
8794 
8795   FormatStyle NoBinPacking = getLLVMStyle();
8796   NoBinPacking.BinPackParameters = false;
8797   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8798                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8799                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
8800                "                         aaaaaaaaaaaaaaaaaaa,\n"
8801                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8802                NoBinPacking);
8803 
8804   // If there is a subsequent call, change to hanging indentation.
8805   verifyFormat(
8806       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8807       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
8808       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8809   verifyFormat(
8810       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8811       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
8812   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8813                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8814                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8815   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8816                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8817                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
8818 }
8819 
8820 TEST_F(FormatTest, WrapsTemplateDeclarations) {
8821   verifyFormat("template <typename T>\n"
8822                "virtual void loooooooooooongFunction(int Param1, int Param2);");
8823   verifyFormat("template <typename T>\n"
8824                "// T should be one of {A, B}.\n"
8825                "virtual void loooooooooooongFunction(int Param1, int Param2);");
8826   verifyFormat(
8827       "template <typename T>\n"
8828       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
8829   verifyFormat("template <typename T>\n"
8830                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
8831                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
8832   verifyFormat(
8833       "template <typename T>\n"
8834       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
8835       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
8836   verifyFormat(
8837       "template <typename T>\n"
8838       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
8839       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
8840       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8841   verifyFormat("template <typename T>\n"
8842                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8843                "    int aaaaaaaaaaaaaaaaaaaaaa);");
8844   verifyFormat(
8845       "template <typename T1, typename T2 = char, typename T3 = char,\n"
8846       "          typename T4 = char>\n"
8847       "void f();");
8848   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
8849                "          template <typename> class cccccccccccccccccccccc,\n"
8850                "          typename ddddddddddddd>\n"
8851                "class C {};");
8852   verifyFormat(
8853       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
8854       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8855 
8856   verifyFormat("void f() {\n"
8857                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
8858                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
8859                "}");
8860 
8861   verifyFormat("template <typename T> class C {};");
8862   verifyFormat("template <typename T> void f();");
8863   verifyFormat("template <typename T> void f() {}");
8864   verifyFormat(
8865       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8866       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8867       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
8868       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8869       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8870       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
8871       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
8872       getLLVMStyleWithColumns(72));
8873   EXPECT_EQ("static_cast<A< //\n"
8874             "    B> *>(\n"
8875             "\n"
8876             ");",
8877             format("static_cast<A<//\n"
8878                    "    B>*>(\n"
8879                    "\n"
8880                    "    );"));
8881   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8882                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
8883 
8884   FormatStyle AlwaysBreak = getLLVMStyle();
8885   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
8886   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
8887   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
8888   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
8889   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8890                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8891                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
8892   verifyFormat("template <template <typename> class Fooooooo,\n"
8893                "          template <typename> class Baaaaaaar>\n"
8894                "struct C {};",
8895                AlwaysBreak);
8896   verifyFormat("template <typename T> // T can be A, B or C.\n"
8897                "struct C {};",
8898                AlwaysBreak);
8899   verifyFormat("template <enum E> class A {\n"
8900                "public:\n"
8901                "  E *f();\n"
8902                "};");
8903 
8904   FormatStyle NeverBreak = getLLVMStyle();
8905   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
8906   verifyFormat("template <typename T> class C {};", NeverBreak);
8907   verifyFormat("template <typename T> void f();", NeverBreak);
8908   verifyFormat("template <typename T> void f() {}", NeverBreak);
8909   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
8910                "bbbbbbbbbbbbbbbbbbbb) {}",
8911                NeverBreak);
8912   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8913                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8914                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
8915                NeverBreak);
8916   verifyFormat("template <template <typename> class Fooooooo,\n"
8917                "          template <typename> class Baaaaaaar>\n"
8918                "struct C {};",
8919                NeverBreak);
8920   verifyFormat("template <typename T> // T can be A, B or C.\n"
8921                "struct C {};",
8922                NeverBreak);
8923   verifyFormat("template <enum E> class A {\n"
8924                "public:\n"
8925                "  E *f();\n"
8926                "};",
8927                NeverBreak);
8928   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
8929   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
8930                "bbbbbbbbbbbbbbbbbbbb) {}",
8931                NeverBreak);
8932 }
8933 
8934 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
8935   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
8936   Style.ColumnLimit = 60;
8937   EXPECT_EQ("// Baseline - no comments.\n"
8938             "template <\n"
8939             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
8940             "void f() {}",
8941             format("// Baseline - no comments.\n"
8942                    "template <\n"
8943                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
8944                    "void f() {}",
8945                    Style));
8946 
8947   EXPECT_EQ("template <\n"
8948             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
8949             "void f() {}",
8950             format("template <\n"
8951                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8952                    "void f() {}",
8953                    Style));
8954 
8955   EXPECT_EQ(
8956       "template <\n"
8957       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
8958       "void f() {}",
8959       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
8960              "void f() {}",
8961              Style));
8962 
8963   EXPECT_EQ(
8964       "template <\n"
8965       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
8966       "                                               // multiline\n"
8967       "void f() {}",
8968       format("template <\n"
8969              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8970              "                                              // multiline\n"
8971              "void f() {}",
8972              Style));
8973 
8974   EXPECT_EQ(
8975       "template <typename aaaaaaaaaa<\n"
8976       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
8977       "void f() {}",
8978       format(
8979           "template <\n"
8980           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
8981           "void f() {}",
8982           Style));
8983 }
8984 
8985 TEST_F(FormatTest, WrapsTemplateParameters) {
8986   FormatStyle Style = getLLVMStyle();
8987   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8988   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
8989   verifyFormat(
8990       "template <typename... a> struct q {};\n"
8991       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
8992       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
8993       "    y;",
8994       Style);
8995   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8996   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
8997   verifyFormat(
8998       "template <typename... a> struct r {};\n"
8999       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9000       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9001       "    y;",
9002       Style);
9003   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9004   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9005   verifyFormat("template <typename... a> struct s {};\n"
9006                "extern s<\n"
9007                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9008                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9009                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9010                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9011                "    y;",
9012                Style);
9013   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9014   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9015   verifyFormat("template <typename... a> struct t {};\n"
9016                "extern t<\n"
9017                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9018                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9019                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9020                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9021                "    y;",
9022                Style);
9023 }
9024 
9025 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9026   verifyFormat(
9027       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9028       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9029   verifyFormat(
9030       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9031       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9032       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9033 
9034   // FIXME: Should we have the extra indent after the second break?
9035   verifyFormat(
9036       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9037       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9038       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9039 
9040   verifyFormat(
9041       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9042       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9043 
9044   // Breaking at nested name specifiers is generally not desirable.
9045   verifyFormat(
9046       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9047       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9048 
9049   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9050                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9051                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9052                "                   aaaaaaaaaaaaaaaaaaaaa);",
9053                getLLVMStyleWithColumns(74));
9054 
9055   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9056                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9057                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9058 }
9059 
9060 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9061   verifyFormat("A<int> a;");
9062   verifyFormat("A<A<A<int>>> a;");
9063   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9064   verifyFormat("bool x = a < 1 || 2 > a;");
9065   verifyFormat("bool x = 5 < f<int>();");
9066   verifyFormat("bool x = f<int>() > 5;");
9067   verifyFormat("bool x = 5 < a<int>::x;");
9068   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9069   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9070 
9071   verifyGoogleFormat("A<A<int>> a;");
9072   verifyGoogleFormat("A<A<A<int>>> a;");
9073   verifyGoogleFormat("A<A<A<A<int>>>> a;");
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;");
9079   verifyGoogleFormat("A< ::A> a;");
9080   verifyGoogleFormat("A< ::A<int> > a;");
9081   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9082   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9083   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9084   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9085   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9086             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9087 
9088   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9089 
9090   // template closer followed by a token that starts with > or =
9091   verifyFormat("bool b = a<1> > 1;");
9092   verifyFormat("bool b = a<1> >= 1;");
9093   verifyFormat("int i = a<1> >> 1;");
9094   FormatStyle Style = getLLVMStyle();
9095   Style.SpaceBeforeAssignmentOperators = false;
9096   verifyFormat("bool b= a<1> == 1;", Style);
9097   verifyFormat("a<int> = 1;", Style);
9098   verifyFormat("a<int> >>= 1;", Style);
9099 
9100   verifyFormat("test < a | b >> c;");
9101   verifyFormat("test<test<a | b>> c;");
9102   verifyFormat("test >> a >> b;");
9103   verifyFormat("test << a >> b;");
9104 
9105   verifyFormat("f<int>();");
9106   verifyFormat("template <typename T> void f() {}");
9107   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9108   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9109                "sizeof(char)>::type>;");
9110   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9111   verifyFormat("f(a.operator()<A>());");
9112   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9113                "      .template operator()<A>());",
9114                getLLVMStyleWithColumns(35));
9115 
9116   // Not template parameters.
9117   verifyFormat("return a < b && c > d;");
9118   verifyFormat("void f() {\n"
9119                "  while (a < b && c > d) {\n"
9120                "  }\n"
9121                "}");
9122   verifyFormat("template <typename... Types>\n"
9123                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9124 
9125   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9126                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9127                getLLVMStyleWithColumns(60));
9128   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9129   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9130   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9131   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9132 }
9133 
9134 TEST_F(FormatTest, UnderstandsShiftOperators) {
9135   verifyFormat("if (i < x >> 1)");
9136   verifyFormat("while (i < x >> 1)");
9137   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9138   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9139   verifyFormat(
9140       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9141   verifyFormat("Foo.call<Bar<Function>>()");
9142   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9143   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9144                "++i, v = v >> 1)");
9145   verifyFormat("if (w<u<v<x>>, 1>::t)");
9146 }
9147 
9148 TEST_F(FormatTest, BitshiftOperatorWidth) {
9149   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9150             "                   bar */",
9151             format("int    a=1<<2;  /* foo\n"
9152                    "                   bar */"));
9153 
9154   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9155             "                     bar */",
9156             format("int  b  =256>>1 ;  /* foo\n"
9157                    "                      bar */"));
9158 }
9159 
9160 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9161   verifyFormat("COMPARE(a, ==, b);");
9162   verifyFormat("auto s = sizeof...(Ts) - 1;");
9163 }
9164 
9165 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9166   verifyFormat("int A::*x;");
9167   verifyFormat("int (S::*func)(void *);");
9168   verifyFormat("void f() { int (S::*func)(void *); }");
9169   verifyFormat("typedef bool *(Class::*Member)() const;");
9170   verifyFormat("void f() {\n"
9171                "  (a->*f)();\n"
9172                "  a->*x;\n"
9173                "  (a.*f)();\n"
9174                "  ((*a).*f)();\n"
9175                "  a.*x;\n"
9176                "}");
9177   verifyFormat("void f() {\n"
9178                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9179                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9180                "}");
9181   verifyFormat(
9182       "(aaaaaaaaaa->*bbbbbbb)(\n"
9183       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9184   FormatStyle Style = getLLVMStyle();
9185   Style.PointerAlignment = FormatStyle::PAS_Left;
9186   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9187 }
9188 
9189 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9190   verifyFormat("int a = -2;");
9191   verifyFormat("f(-1, -2, -3);");
9192   verifyFormat("a[-1] = 5;");
9193   verifyFormat("int a = 5 + -2;");
9194   verifyFormat("if (i == -1) {\n}");
9195   verifyFormat("if (i != -1) {\n}");
9196   verifyFormat("if (i > -1) {\n}");
9197   verifyFormat("if (i < -1) {\n}");
9198   verifyFormat("++(a->f());");
9199   verifyFormat("--(a->f());");
9200   verifyFormat("(a->f())++;");
9201   verifyFormat("a[42]++;");
9202   verifyFormat("if (!(a->f())) {\n}");
9203   verifyFormat("if (!+i) {\n}");
9204   verifyFormat("~&a;");
9205 
9206   verifyFormat("a-- > b;");
9207   verifyFormat("b ? -a : c;");
9208   verifyFormat("n * sizeof char16;");
9209   verifyFormat("n * alignof char16;", getGoogleStyle());
9210   verifyFormat("sizeof(char);");
9211   verifyFormat("alignof(char);", getGoogleStyle());
9212 
9213   verifyFormat("return -1;");
9214   verifyFormat("throw -1;");
9215   verifyFormat("switch (a) {\n"
9216                "case -1:\n"
9217                "  break;\n"
9218                "}");
9219   verifyFormat("#define X -1");
9220   verifyFormat("#define X -kConstant");
9221 
9222   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9223   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9224 
9225   verifyFormat("int a = /* confusing comment */ -1;");
9226   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9227   verifyFormat("int a = i /* confusing comment */++;");
9228 
9229   verifyFormat("co_yield -1;");
9230   verifyFormat("co_return -1;");
9231 
9232   // Check that * is not treated as a binary operator when we set
9233   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9234   FormatStyle PASLeftStyle = getLLVMStyle();
9235   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9236   verifyFormat("co_return *a;", PASLeftStyle);
9237   verifyFormat("co_await *a;", PASLeftStyle);
9238   verifyFormat("co_yield *a", PASLeftStyle);
9239   verifyFormat("return *a;", PASLeftStyle);
9240 }
9241 
9242 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9243   verifyFormat("if (!aaaaaaaaaa( // break\n"
9244                "        aaaaa)) {\n"
9245                "}");
9246   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9247                "    aaaaa));");
9248   verifyFormat("*aaa = aaaaaaa( // break\n"
9249                "    bbbbbb);");
9250 }
9251 
9252 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9253   verifyFormat("bool operator<();");
9254   verifyFormat("bool operator>();");
9255   verifyFormat("bool operator=();");
9256   verifyFormat("bool operator==();");
9257   verifyFormat("bool operator!=();");
9258   verifyFormat("int operator+();");
9259   verifyFormat("int operator++();");
9260   verifyFormat("int operator++(int) volatile noexcept;");
9261   verifyFormat("bool operator,();");
9262   verifyFormat("bool operator();");
9263   verifyFormat("bool operator()();");
9264   verifyFormat("bool operator[]();");
9265   verifyFormat("operator bool();");
9266   verifyFormat("operator int();");
9267   verifyFormat("operator void *();");
9268   verifyFormat("operator SomeType<int>();");
9269   verifyFormat("operator SomeType<int, int>();");
9270   verifyFormat("operator SomeType<SomeType<int>>();");
9271   verifyFormat("void *operator new(std::size_t size);");
9272   verifyFormat("void *operator new[](std::size_t size);");
9273   verifyFormat("void operator delete(void *ptr);");
9274   verifyFormat("void operator delete[](void *ptr);");
9275   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9276                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9277   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9278                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9279 
9280   verifyFormat(
9281       "ostream &operator<<(ostream &OutputStream,\n"
9282       "                    SomeReallyLongType WithSomeReallyLongValue);");
9283   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9284                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9285                "  return left.group < right.group;\n"
9286                "}");
9287   verifyFormat("SomeType &operator=(const SomeType &S);");
9288   verifyFormat("f.template operator()<int>();");
9289 
9290   verifyGoogleFormat("operator void*();");
9291   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9292   verifyGoogleFormat("operator ::A();");
9293 
9294   verifyFormat("using A::operator+;");
9295   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9296                "int i;");
9297 
9298   // Calling an operator as a member function.
9299   verifyFormat("void f() { a.operator*(); }");
9300   verifyFormat("void f() { a.operator*(b & b); }");
9301   verifyFormat("void f() { a->operator&(a * b); }");
9302   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9303   // TODO: Calling an operator as a non-member function is hard to distinguish.
9304   // https://llvm.org/PR50629
9305   // verifyFormat("void f() { operator*(a & a); }");
9306   // verifyFormat("void f() { operator&(a, b * b); }");
9307 
9308   verifyFormat("::operator delete(foo);");
9309   verifyFormat("::operator new(n * sizeof(foo));");
9310   verifyFormat("foo() { ::operator delete(foo); }");
9311   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9312 }
9313 
9314 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9315   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9316   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9317   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9318   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9319   verifyFormat("Deleted &operator=(const Deleted &) &;");
9320   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9321   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9322   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9323   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9324   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9325   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9326   verifyFormat("void Fn(T const &) const &;");
9327   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9328   verifyFormat("template <typename T>\n"
9329                "void F(T) && = delete;",
9330                getGoogleStyle());
9331 
9332   FormatStyle AlignLeft = getLLVMStyle();
9333   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9334   verifyFormat("void A::b() && {}", AlignLeft);
9335   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9336   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9337                AlignLeft);
9338   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9339   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9340   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9341   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9342   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9343   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9344   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9345   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9346 
9347   FormatStyle Spaces = getLLVMStyle();
9348   Spaces.SpacesInCStyleCastParentheses = true;
9349   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9350   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9351   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9352   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9353 
9354   Spaces.SpacesInCStyleCastParentheses = false;
9355   Spaces.SpacesInParentheses = true;
9356   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9357   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9358                Spaces);
9359   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9360   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9361 
9362   FormatStyle BreakTemplate = getLLVMStyle();
9363   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9364 
9365   verifyFormat("struct f {\n"
9366                "  template <class T>\n"
9367                "  int &foo(const std::string &str) &noexcept {}\n"
9368                "};",
9369                BreakTemplate);
9370 
9371   verifyFormat("struct f {\n"
9372                "  template <class T>\n"
9373                "  int &foo(const std::string &str) &&noexcept {}\n"
9374                "};",
9375                BreakTemplate);
9376 
9377   verifyFormat("struct f {\n"
9378                "  template <class T>\n"
9379                "  int &foo(const std::string &str) const &noexcept {}\n"
9380                "};",
9381                BreakTemplate);
9382 
9383   verifyFormat("struct f {\n"
9384                "  template <class T>\n"
9385                "  int &foo(const std::string &str) const &noexcept {}\n"
9386                "};",
9387                BreakTemplate);
9388 
9389   verifyFormat("struct f {\n"
9390                "  template <class T>\n"
9391                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
9392                "};",
9393                BreakTemplate);
9394 
9395   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
9396   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
9397       FormatStyle::BTDS_Yes;
9398   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
9399 
9400   verifyFormat("struct f {\n"
9401                "  template <class T>\n"
9402                "  int& foo(const std::string& str) & noexcept {}\n"
9403                "};",
9404                AlignLeftBreakTemplate);
9405 
9406   verifyFormat("struct f {\n"
9407                "  template <class T>\n"
9408                "  int& foo(const std::string& str) && noexcept {}\n"
9409                "};",
9410                AlignLeftBreakTemplate);
9411 
9412   verifyFormat("struct f {\n"
9413                "  template <class T>\n"
9414                "  int& foo(const std::string& str) const& noexcept {}\n"
9415                "};",
9416                AlignLeftBreakTemplate);
9417 
9418   verifyFormat("struct f {\n"
9419                "  template <class T>\n"
9420                "  int& foo(const std::string& str) const&& noexcept {}\n"
9421                "};",
9422                AlignLeftBreakTemplate);
9423 
9424   verifyFormat("struct f {\n"
9425                "  template <class T>\n"
9426                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
9427                "};",
9428                AlignLeftBreakTemplate);
9429 
9430   // The `&` in `Type&` should not be confused with a trailing `&` of
9431   // DEPRECATED(reason) member function.
9432   verifyFormat("struct f {\n"
9433                "  template <class T>\n"
9434                "  DEPRECATED(reason)\n"
9435                "  Type &foo(arguments) {}\n"
9436                "};",
9437                BreakTemplate);
9438 
9439   verifyFormat("struct f {\n"
9440                "  template <class T>\n"
9441                "  DEPRECATED(reason)\n"
9442                "  Type& foo(arguments) {}\n"
9443                "};",
9444                AlignLeftBreakTemplate);
9445 
9446   verifyFormat("void (*foopt)(int) = &func;");
9447 }
9448 
9449 TEST_F(FormatTest, UnderstandsNewAndDelete) {
9450   verifyFormat("void f() {\n"
9451                "  A *a = new A;\n"
9452                "  A *a = new (placement) A;\n"
9453                "  delete a;\n"
9454                "  delete (A *)a;\n"
9455                "}");
9456   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9457                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9458   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9459                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9460                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9461   verifyFormat("delete[] h->p;");
9462 
9463   verifyFormat("void operator delete(void *foo) ATTRIB;");
9464   verifyFormat("void operator new(void *foo) ATTRIB;");
9465   verifyFormat("void operator delete[](void *foo) ATTRIB;");
9466   verifyFormat("void operator delete(void *ptr) noexcept;");
9467 }
9468 
9469 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
9470   verifyFormat("int *f(int *a) {}");
9471   verifyFormat("int main(int argc, char **argv) {}");
9472   verifyFormat("Test::Test(int b) : a(b * b) {}");
9473   verifyIndependentOfContext("f(a, *a);");
9474   verifyFormat("void g() { f(*a); }");
9475   verifyIndependentOfContext("int a = b * 10;");
9476   verifyIndependentOfContext("int a = 10 * b;");
9477   verifyIndependentOfContext("int a = b * c;");
9478   verifyIndependentOfContext("int a += b * c;");
9479   verifyIndependentOfContext("int a -= b * c;");
9480   verifyIndependentOfContext("int a *= b * c;");
9481   verifyIndependentOfContext("int a /= b * c;");
9482   verifyIndependentOfContext("int a = *b;");
9483   verifyIndependentOfContext("int a = *b * c;");
9484   verifyIndependentOfContext("int a = b * *c;");
9485   verifyIndependentOfContext("int a = b * (10);");
9486   verifyIndependentOfContext("S << b * (10);");
9487   verifyIndependentOfContext("return 10 * b;");
9488   verifyIndependentOfContext("return *b * *c;");
9489   verifyIndependentOfContext("return a & ~b;");
9490   verifyIndependentOfContext("f(b ? *c : *d);");
9491   verifyIndependentOfContext("int a = b ? *c : *d;");
9492   verifyIndependentOfContext("*b = a;");
9493   verifyIndependentOfContext("a * ~b;");
9494   verifyIndependentOfContext("a * !b;");
9495   verifyIndependentOfContext("a * +b;");
9496   verifyIndependentOfContext("a * -b;");
9497   verifyIndependentOfContext("a * ++b;");
9498   verifyIndependentOfContext("a * --b;");
9499   verifyIndependentOfContext("a[4] * b;");
9500   verifyIndependentOfContext("a[a * a] = 1;");
9501   verifyIndependentOfContext("f() * b;");
9502   verifyIndependentOfContext("a * [self dostuff];");
9503   verifyIndependentOfContext("int x = a * (a + b);");
9504   verifyIndependentOfContext("(a *)(a + b);");
9505   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
9506   verifyIndependentOfContext("int *pa = (int *)&a;");
9507   verifyIndependentOfContext("return sizeof(int **);");
9508   verifyIndependentOfContext("return sizeof(int ******);");
9509   verifyIndependentOfContext("return (int **&)a;");
9510   verifyIndependentOfContext("f((*PointerToArray)[10]);");
9511   verifyFormat("void f(Type (*parameter)[10]) {}");
9512   verifyFormat("void f(Type (&parameter)[10]) {}");
9513   verifyGoogleFormat("return sizeof(int**);");
9514   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
9515   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
9516   verifyFormat("auto a = [](int **&, int ***) {};");
9517   verifyFormat("auto PointerBinding = [](const char *S) {};");
9518   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
9519   verifyFormat("[](const decltype(*a) &value) {}");
9520   verifyFormat("[](const typeof(*a) &value) {}");
9521   verifyFormat("[](const _Atomic(a *) &value) {}");
9522   verifyFormat("[](const __underlying_type(a) &value) {}");
9523   verifyFormat("decltype(a * b) F();");
9524   verifyFormat("typeof(a * b) F();");
9525   verifyFormat("#define MACRO() [](A *a) { return 1; }");
9526   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
9527   verifyIndependentOfContext("typedef void (*f)(int *a);");
9528   verifyIndependentOfContext("int i{a * b};");
9529   verifyIndependentOfContext("aaa && aaa->f();");
9530   verifyIndependentOfContext("int x = ~*p;");
9531   verifyFormat("Constructor() : a(a), area(width * height) {}");
9532   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
9533   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
9534   verifyFormat("void f() { f(a, c * d); }");
9535   verifyFormat("void f() { f(new a(), c * d); }");
9536   verifyFormat("void f(const MyOverride &override);");
9537   verifyFormat("void f(const MyFinal &final);");
9538   verifyIndependentOfContext("bool a = f() && override.f();");
9539   verifyIndependentOfContext("bool a = f() && final.f();");
9540 
9541   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
9542 
9543   verifyIndependentOfContext("A<int *> a;");
9544   verifyIndependentOfContext("A<int **> a;");
9545   verifyIndependentOfContext("A<int *, int *> a;");
9546   verifyIndependentOfContext("A<int *[]> a;");
9547   verifyIndependentOfContext(
9548       "const char *const p = reinterpret_cast<const char *const>(q);");
9549   verifyIndependentOfContext("A<int **, int **> a;");
9550   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
9551   verifyFormat("for (char **a = b; *a; ++a) {\n}");
9552   verifyFormat("for (; a && b;) {\n}");
9553   verifyFormat("bool foo = true && [] { return false; }();");
9554 
9555   verifyFormat(
9556       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9557       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9558 
9559   verifyGoogleFormat("int const* a = &b;");
9560   verifyGoogleFormat("**outparam = 1;");
9561   verifyGoogleFormat("*outparam = a * b;");
9562   verifyGoogleFormat("int main(int argc, char** argv) {}");
9563   verifyGoogleFormat("A<int*> a;");
9564   verifyGoogleFormat("A<int**> a;");
9565   verifyGoogleFormat("A<int*, int*> a;");
9566   verifyGoogleFormat("A<int**, int**> a;");
9567   verifyGoogleFormat("f(b ? *c : *d);");
9568   verifyGoogleFormat("int a = b ? *c : *d;");
9569   verifyGoogleFormat("Type* t = **x;");
9570   verifyGoogleFormat("Type* t = *++*x;");
9571   verifyGoogleFormat("*++*x;");
9572   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
9573   verifyGoogleFormat("Type* t = x++ * y;");
9574   verifyGoogleFormat(
9575       "const char* const p = reinterpret_cast<const char* const>(q);");
9576   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
9577   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
9578   verifyGoogleFormat("template <typename T>\n"
9579                      "void f(int i = 0, SomeType** temps = NULL);");
9580 
9581   FormatStyle Left = getLLVMStyle();
9582   Left.PointerAlignment = FormatStyle::PAS_Left;
9583   verifyFormat("x = *a(x) = *a(y);", Left);
9584   verifyFormat("for (;; *a = b) {\n}", Left);
9585   verifyFormat("return *this += 1;", Left);
9586   verifyFormat("throw *x;", Left);
9587   verifyFormat("delete *x;", Left);
9588   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
9589   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
9590   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
9591   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
9592   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
9593   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
9594   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
9595   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
9596   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
9597 
9598   verifyIndependentOfContext("a = *(x + y);");
9599   verifyIndependentOfContext("a = &(x + y);");
9600   verifyIndependentOfContext("*(x + y).call();");
9601   verifyIndependentOfContext("&(x + y)->call();");
9602   verifyFormat("void f() { &(*I).first; }");
9603 
9604   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
9605   verifyFormat("f(* /* confusing comment */ foo);");
9606   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
9607   verifyFormat("void foo(int * // this is the first paramters\n"
9608                "         ,\n"
9609                "         int second);");
9610   verifyFormat("double term = a * // first\n"
9611                "              b;");
9612   verifyFormat(
9613       "int *MyValues = {\n"
9614       "    *A, // Operator detection might be confused by the '{'\n"
9615       "    *BB // Operator detection might be confused by previous comment\n"
9616       "};");
9617 
9618   verifyIndependentOfContext("if (int *a = &b)");
9619   verifyIndependentOfContext("if (int &a = *b)");
9620   verifyIndependentOfContext("if (a & b[i])");
9621   verifyIndependentOfContext("if constexpr (a & b[i])");
9622   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
9623   verifyIndependentOfContext("if (a * (b * c))");
9624   verifyIndependentOfContext("if constexpr (a * (b * c))");
9625   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
9626   verifyIndependentOfContext("if (a::b::c::d & b[i])");
9627   verifyIndependentOfContext("if (*b[i])");
9628   verifyIndependentOfContext("if (int *a = (&b))");
9629   verifyIndependentOfContext("while (int *a = &b)");
9630   verifyIndependentOfContext("while (a * (b * c))");
9631   verifyIndependentOfContext("size = sizeof *a;");
9632   verifyIndependentOfContext("if (a && (b = c))");
9633   verifyFormat("void f() {\n"
9634                "  for (const int &v : Values) {\n"
9635                "  }\n"
9636                "}");
9637   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
9638   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
9639   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
9640 
9641   verifyFormat("#define A (!a * b)");
9642   verifyFormat("#define MACRO     \\\n"
9643                "  int *i = a * b; \\\n"
9644                "  void f(a *b);",
9645                getLLVMStyleWithColumns(19));
9646 
9647   verifyIndependentOfContext("A = new SomeType *[Length];");
9648   verifyIndependentOfContext("A = new SomeType *[Length]();");
9649   verifyIndependentOfContext("T **t = new T *;");
9650   verifyIndependentOfContext("T **t = new T *();");
9651   verifyGoogleFormat("A = new SomeType*[Length]();");
9652   verifyGoogleFormat("A = new SomeType*[Length];");
9653   verifyGoogleFormat("T** t = new T*;");
9654   verifyGoogleFormat("T** t = new T*();");
9655 
9656   verifyFormat("STATIC_ASSERT((a & b) == 0);");
9657   verifyFormat("STATIC_ASSERT(0 == (a & b));");
9658   verifyFormat("template <bool a, bool b> "
9659                "typename t::if<x && y>::type f() {}");
9660   verifyFormat("template <int *y> f() {}");
9661   verifyFormat("vector<int *> v;");
9662   verifyFormat("vector<int *const> v;");
9663   verifyFormat("vector<int *const **const *> v;");
9664   verifyFormat("vector<int *volatile> v;");
9665   verifyFormat("vector<a *_Nonnull> v;");
9666   verifyFormat("vector<a *_Nullable> v;");
9667   verifyFormat("vector<a *_Null_unspecified> v;");
9668   verifyFormat("vector<a *__ptr32> v;");
9669   verifyFormat("vector<a *__ptr64> v;");
9670   verifyFormat("vector<a *__capability> v;");
9671   FormatStyle TypeMacros = getLLVMStyle();
9672   TypeMacros.TypenameMacros = {"LIST"};
9673   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
9674   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
9675   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
9676   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
9677   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
9678 
9679   FormatStyle CustomQualifier = getLLVMStyle();
9680   // Add identifiers that should not be parsed as a qualifier by default.
9681   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9682   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
9683   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
9684   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
9685   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
9686   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
9687   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
9688   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
9689   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
9690   verifyFormat("vector<a * _NotAQualifier> v;");
9691   verifyFormat("vector<a * __not_a_qualifier> v;");
9692   verifyFormat("vector<a * b> v;");
9693   verifyFormat("foo<b && false>();");
9694   verifyFormat("foo<b & 1>();");
9695   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
9696   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
9697   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
9698   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
9699   verifyFormat(
9700       "template <class T, class = typename std::enable_if<\n"
9701       "                       std::is_integral<T>::value &&\n"
9702       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
9703       "void F();",
9704       getLLVMStyleWithColumns(70));
9705   verifyFormat("template <class T,\n"
9706                "          class = typename std::enable_if<\n"
9707                "              std::is_integral<T>::value &&\n"
9708                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
9709                "          class U>\n"
9710                "void F();",
9711                getLLVMStyleWithColumns(70));
9712   verifyFormat(
9713       "template <class T,\n"
9714       "          class = typename ::std::enable_if<\n"
9715       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
9716       "void F();",
9717       getGoogleStyleWithColumns(68));
9718 
9719   verifyIndependentOfContext("MACRO(int *i);");
9720   verifyIndependentOfContext("MACRO(auto *a);");
9721   verifyIndependentOfContext("MACRO(const A *a);");
9722   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
9723   verifyIndependentOfContext("MACRO(decltype(A) *a);");
9724   verifyIndependentOfContext("MACRO(typeof(A) *a);");
9725   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
9726   verifyIndependentOfContext("MACRO(A *const a);");
9727   verifyIndependentOfContext("MACRO(A *restrict a);");
9728   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
9729   verifyIndependentOfContext("MACRO(A *__restrict a);");
9730   verifyIndependentOfContext("MACRO(A *volatile a);");
9731   verifyIndependentOfContext("MACRO(A *__volatile a);");
9732   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
9733   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
9734   verifyIndependentOfContext("MACRO(A *_Nullable a);");
9735   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
9736   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
9737   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
9738   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
9739   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
9740   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
9741   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
9742   verifyIndependentOfContext("MACRO(A *__capability);");
9743   verifyIndependentOfContext("MACRO(A &__capability);");
9744   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
9745   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
9746   // If we add __my_qualifier to AttributeMacros it should always be parsed as
9747   // a type declaration:
9748   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
9749   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
9750   // Also check that TypenameMacros prevents parsing it as multiplication:
9751   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
9752   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
9753 
9754   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
9755   verifyFormat("void f() { f(float{1}, a * a); }");
9756   verifyFormat("void f() { f(float(1), a * a); }");
9757 
9758   verifyFormat("f((void (*)(int))g);");
9759   verifyFormat("f((void (&)(int))g);");
9760   verifyFormat("f((void (^)(int))g);");
9761 
9762   // FIXME: Is there a way to make this work?
9763   // verifyIndependentOfContext("MACRO(A *a);");
9764   verifyFormat("MACRO(A &B);");
9765   verifyFormat("MACRO(A *B);");
9766   verifyFormat("void f() { MACRO(A * B); }");
9767   verifyFormat("void f() { MACRO(A & B); }");
9768 
9769   // This lambda was mis-formatted after D88956 (treating it as a binop):
9770   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
9771   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
9772   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
9773   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
9774 
9775   verifyFormat("DatumHandle const *operator->() const { return input_; }");
9776   verifyFormat("return options != nullptr && operator==(*options);");
9777 
9778   EXPECT_EQ("#define OP(x)                                    \\\n"
9779             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
9780             "    return s << a.DebugString();                 \\\n"
9781             "  }",
9782             format("#define OP(x) \\\n"
9783                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
9784                    "    return s << a.DebugString(); \\\n"
9785                    "  }",
9786                    getLLVMStyleWithColumns(50)));
9787 
9788   // FIXME: We cannot handle this case yet; we might be able to figure out that
9789   // foo<x> d > v; doesn't make sense.
9790   verifyFormat("foo<a<b && c> d> v;");
9791 
9792   FormatStyle PointerMiddle = getLLVMStyle();
9793   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9794   verifyFormat("delete *x;", PointerMiddle);
9795   verifyFormat("int * x;", PointerMiddle);
9796   verifyFormat("int *[] x;", PointerMiddle);
9797   verifyFormat("template <int * y> f() {}", PointerMiddle);
9798   verifyFormat("int * f(int * a) {}", PointerMiddle);
9799   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
9800   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
9801   verifyFormat("A<int *> a;", PointerMiddle);
9802   verifyFormat("A<int **> a;", PointerMiddle);
9803   verifyFormat("A<int *, int *> a;", PointerMiddle);
9804   verifyFormat("A<int *[]> a;", PointerMiddle);
9805   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
9806   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
9807   verifyFormat("T ** t = new T *;", PointerMiddle);
9808 
9809   // Member function reference qualifiers aren't binary operators.
9810   verifyFormat("string // break\n"
9811                "operator()() & {}");
9812   verifyFormat("string // break\n"
9813                "operator()() && {}");
9814   verifyGoogleFormat("template <typename T>\n"
9815                      "auto x() & -> int {}");
9816 
9817   // Should be binary operators when used as an argument expression (overloaded
9818   // operator invoked as a member function).
9819   verifyFormat("void f() { a.operator()(a * a); }");
9820   verifyFormat("void f() { a->operator()(a & a); }");
9821   verifyFormat("void f() { a.operator()(*a & *a); }");
9822   verifyFormat("void f() { a->operator()(*a * *a); }");
9823 
9824   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
9825   verifyFormat("int operator()(T (&)[N]) { return 0; }");
9826 }
9827 
9828 TEST_F(FormatTest, UnderstandsAttributes) {
9829   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
9830   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
9831                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9832   FormatStyle AfterType = getLLVMStyle();
9833   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
9834   verifyFormat("__attribute__((nodebug)) void\n"
9835                "foo() {}\n",
9836                AfterType);
9837   verifyFormat("__unused void\n"
9838                "foo() {}",
9839                AfterType);
9840 
9841   FormatStyle CustomAttrs = getLLVMStyle();
9842   CustomAttrs.AttributeMacros.push_back("__unused");
9843   CustomAttrs.AttributeMacros.push_back("__attr1");
9844   CustomAttrs.AttributeMacros.push_back("__attr2");
9845   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
9846   verifyFormat("vector<SomeType *__attribute((foo))> v;");
9847   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
9848   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
9849   // Check that it is parsed as a multiplication without AttributeMacros and
9850   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
9851   verifyFormat("vector<SomeType * __attr1> v;");
9852   verifyFormat("vector<SomeType __attr1 *> v;");
9853   verifyFormat("vector<SomeType __attr1 *const> v;");
9854   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
9855   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
9856   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
9857   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
9858   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
9859   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
9860   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
9861   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
9862 
9863   // Check that these are not parsed as function declarations:
9864   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9865   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
9866   verifyFormat("SomeType s(InitValue);", CustomAttrs);
9867   verifyFormat("SomeType s{InitValue};", CustomAttrs);
9868   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
9869   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
9870   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
9871   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
9872   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
9873   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
9874 }
9875 
9876 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
9877   // Check that qualifiers on pointers don't break parsing of casts.
9878   verifyFormat("x = (foo *const)*v;");
9879   verifyFormat("x = (foo *volatile)*v;");
9880   verifyFormat("x = (foo *restrict)*v;");
9881   verifyFormat("x = (foo *__attribute__((foo)))*v;");
9882   verifyFormat("x = (foo *_Nonnull)*v;");
9883   verifyFormat("x = (foo *_Nullable)*v;");
9884   verifyFormat("x = (foo *_Null_unspecified)*v;");
9885   verifyFormat("x = (foo *_Nonnull)*v;");
9886   verifyFormat("x = (foo *[[clang::attr]])*v;");
9887   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
9888   verifyFormat("x = (foo *__ptr32)*v;");
9889   verifyFormat("x = (foo *__ptr64)*v;");
9890   verifyFormat("x = (foo *__capability)*v;");
9891 
9892   // Check that we handle multiple trailing qualifiers and skip them all to
9893   // determine that the expression is a cast to a pointer type.
9894   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
9895   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
9896   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
9897   StringRef AllQualifiers =
9898       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
9899       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
9900   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
9901   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
9902 
9903   // Also check that address-of is not parsed as a binary bitwise-and:
9904   verifyFormat("x = (foo *const)&v;");
9905   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
9906   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
9907 
9908   // Check custom qualifiers:
9909   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
9910   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9911   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
9912   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
9913   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
9914                CustomQualifier);
9915   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
9916                CustomQualifier);
9917 
9918   // Check that unknown identifiers result in binary operator parsing:
9919   verifyFormat("x = (foo * __unknown_qualifier) * v;");
9920   verifyFormat("x = (foo * __unknown_qualifier) & v;");
9921 }
9922 
9923 TEST_F(FormatTest, UnderstandsSquareAttributes) {
9924   verifyFormat("SomeType s [[unused]] (InitValue);");
9925   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
9926   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
9927   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
9928   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
9929   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9930                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9931   verifyFormat("[[nodiscard]] bool f() { return false; }");
9932   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
9933   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
9934   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
9935 
9936   // Make sure we do not mistake attributes for array subscripts.
9937   verifyFormat("int a() {}\n"
9938                "[[unused]] int b() {}\n");
9939   verifyFormat("NSArray *arr;\n"
9940                "arr[[Foo() bar]];");
9941 
9942   // On the other hand, we still need to correctly find array subscripts.
9943   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
9944 
9945   // Make sure that we do not mistake Objective-C method inside array literals
9946   // as attributes, even if those method names are also keywords.
9947   verifyFormat("@[ [foo bar] ];");
9948   verifyFormat("@[ [NSArray class] ];");
9949   verifyFormat("@[ [foo enum] ];");
9950 
9951   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
9952 
9953   // Make sure we do not parse attributes as lambda introducers.
9954   FormatStyle MultiLineFunctions = getLLVMStyle();
9955   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9956   verifyFormat("[[unused]] int b() {\n"
9957                "  return 42;\n"
9958                "}\n",
9959                MultiLineFunctions);
9960 }
9961 
9962 TEST_F(FormatTest, AttributeClass) {
9963   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
9964   verifyFormat("class S {\n"
9965                "  S(S&&) = default;\n"
9966                "};",
9967                Style);
9968   verifyFormat("class [[nodiscard]] S {\n"
9969                "  S(S&&) = default;\n"
9970                "};",
9971                Style);
9972   verifyFormat("class __attribute((maybeunused)) S {\n"
9973                "  S(S&&) = default;\n"
9974                "};",
9975                Style);
9976   verifyFormat("struct S {\n"
9977                "  S(S&&) = default;\n"
9978                "};",
9979                Style);
9980   verifyFormat("struct [[nodiscard]] S {\n"
9981                "  S(S&&) = default;\n"
9982                "};",
9983                Style);
9984 }
9985 
9986 TEST_F(FormatTest, AttributesAfterMacro) {
9987   FormatStyle Style = getLLVMStyle();
9988   verifyFormat("MACRO;\n"
9989                "__attribute__((maybe_unused)) int foo() {\n"
9990                "  //...\n"
9991                "}");
9992 
9993   verifyFormat("MACRO;\n"
9994                "[[nodiscard]] int foo() {\n"
9995                "  //...\n"
9996                "}");
9997 
9998   EXPECT_EQ("MACRO\n\n"
9999             "__attribute__((maybe_unused)) int foo() {\n"
10000             "  //...\n"
10001             "}",
10002             format("MACRO\n\n"
10003                    "__attribute__((maybe_unused)) int foo() {\n"
10004                    "  //...\n"
10005                    "}"));
10006 
10007   EXPECT_EQ("MACRO\n\n"
10008             "[[nodiscard]] int foo() {\n"
10009             "  //...\n"
10010             "}",
10011             format("MACRO\n\n"
10012                    "[[nodiscard]] int foo() {\n"
10013                    "  //...\n"
10014                    "}"));
10015 }
10016 
10017 TEST_F(FormatTest, AttributePenaltyBreaking) {
10018   FormatStyle Style = getLLVMStyle();
10019   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10020                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10021                Style);
10022   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10023                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10024                Style);
10025   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10026                "shared_ptr<ALongTypeName> &C d) {\n}",
10027                Style);
10028 }
10029 
10030 TEST_F(FormatTest, UnderstandsEllipsis) {
10031   FormatStyle Style = getLLVMStyle();
10032   verifyFormat("int printf(const char *fmt, ...);");
10033   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10034   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10035 
10036   verifyFormat("template <int *...PP> a;", Style);
10037 
10038   Style.PointerAlignment = FormatStyle::PAS_Left;
10039   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10040 
10041   verifyFormat("template <int*... PP> a;", Style);
10042 
10043   Style.PointerAlignment = FormatStyle::PAS_Middle;
10044   verifyFormat("template <int *... PP> a;", Style);
10045 }
10046 
10047 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10048   EXPECT_EQ("int *a;\n"
10049             "int *a;\n"
10050             "int *a;",
10051             format("int *a;\n"
10052                    "int* a;\n"
10053                    "int *a;",
10054                    getGoogleStyle()));
10055   EXPECT_EQ("int* a;\n"
10056             "int* a;\n"
10057             "int* a;",
10058             format("int* a;\n"
10059                    "int* a;\n"
10060                    "int *a;",
10061                    getGoogleStyle()));
10062   EXPECT_EQ("int *a;\n"
10063             "int *a;\n"
10064             "int *a;",
10065             format("int *a;\n"
10066                    "int * a;\n"
10067                    "int *  a;",
10068                    getGoogleStyle()));
10069   EXPECT_EQ("auto x = [] {\n"
10070             "  int *a;\n"
10071             "  int *a;\n"
10072             "  int *a;\n"
10073             "};",
10074             format("auto x=[]{int *a;\n"
10075                    "int * a;\n"
10076                    "int *  a;};",
10077                    getGoogleStyle()));
10078 }
10079 
10080 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10081   verifyFormat("int f(int &&a) {}");
10082   verifyFormat("int f(int a, char &&b) {}");
10083   verifyFormat("void f() { int &&a = b; }");
10084   verifyGoogleFormat("int f(int a, char&& b) {}");
10085   verifyGoogleFormat("void f() { int&& a = b; }");
10086 
10087   verifyIndependentOfContext("A<int &&> a;");
10088   verifyIndependentOfContext("A<int &&, int &&> a;");
10089   verifyGoogleFormat("A<int&&> a;");
10090   verifyGoogleFormat("A<int&&, int&&> a;");
10091 
10092   // Not rvalue references:
10093   verifyFormat("template <bool B, bool C> class A {\n"
10094                "  static_assert(B && C, \"Something is wrong\");\n"
10095                "};");
10096   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10097   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10098   verifyFormat("#define A(a, b) (a && b)");
10099 }
10100 
10101 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10102   verifyFormat("void f() {\n"
10103                "  x[aaaaaaaaa -\n"
10104                "    b] = 23;\n"
10105                "}",
10106                getLLVMStyleWithColumns(15));
10107 }
10108 
10109 TEST_F(FormatTest, FormatsCasts) {
10110   verifyFormat("Type *A = static_cast<Type *>(P);");
10111   verifyFormat("Type *A = (Type *)P;");
10112   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10113   verifyFormat("int a = (int)(2.0f);");
10114   verifyFormat("int a = (int)2.0f;");
10115   verifyFormat("x[(int32)y];");
10116   verifyFormat("x = (int32)y;");
10117   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10118   verifyFormat("int a = (int)*b;");
10119   verifyFormat("int a = (int)2.0f;");
10120   verifyFormat("int a = (int)~0;");
10121   verifyFormat("int a = (int)++a;");
10122   verifyFormat("int a = (int)sizeof(int);");
10123   verifyFormat("int a = (int)+2;");
10124   verifyFormat("my_int a = (my_int)2.0f;");
10125   verifyFormat("my_int a = (my_int)sizeof(int);");
10126   verifyFormat("return (my_int)aaa;");
10127   verifyFormat("#define x ((int)-1)");
10128   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10129   verifyFormat("#define p(q) ((int *)&q)");
10130   verifyFormat("fn(a)(b) + 1;");
10131 
10132   verifyFormat("void f() { my_int a = (my_int)*b; }");
10133   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10134   verifyFormat("my_int a = (my_int)~0;");
10135   verifyFormat("my_int a = (my_int)++a;");
10136   verifyFormat("my_int a = (my_int)-2;");
10137   verifyFormat("my_int a = (my_int)1;");
10138   verifyFormat("my_int a = (my_int *)1;");
10139   verifyFormat("my_int a = (const my_int)-1;");
10140   verifyFormat("my_int a = (const my_int *)-1;");
10141   verifyFormat("my_int a = (my_int)(my_int)-1;");
10142   verifyFormat("my_int a = (ns::my_int)-2;");
10143   verifyFormat("case (my_int)ONE:");
10144   verifyFormat("auto x = (X)this;");
10145   // Casts in Obj-C style calls used to not be recognized as such.
10146   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10147 
10148   // FIXME: single value wrapped with paren will be treated as cast.
10149   verifyFormat("void f(int i = (kValue)*kMask) {}");
10150 
10151   verifyFormat("{ (void)F; }");
10152 
10153   // Don't break after a cast's
10154   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10155                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10156                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10157 
10158   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10159   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10160   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10161   verifyFormat("bool *y = (bool *)(void *)(x);");
10162   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10163   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10164   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10165   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10166 
10167   // These are not casts.
10168   verifyFormat("void f(int *) {}");
10169   verifyFormat("f(foo)->b;");
10170   verifyFormat("f(foo).b;");
10171   verifyFormat("f(foo)(b);");
10172   verifyFormat("f(foo)[b];");
10173   verifyFormat("[](foo) { return 4; }(bar);");
10174   verifyFormat("(*funptr)(foo)[4];");
10175   verifyFormat("funptrs[4](foo)[4];");
10176   verifyFormat("void f(int *);");
10177   verifyFormat("void f(int *) = 0;");
10178   verifyFormat("void f(SmallVector<int>) {}");
10179   verifyFormat("void f(SmallVector<int>);");
10180   verifyFormat("void f(SmallVector<int>) = 0;");
10181   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10182   verifyFormat("int a = sizeof(int) * b;");
10183   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10184   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10185   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10186   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10187 
10188   // These are not casts, but at some point were confused with casts.
10189   verifyFormat("virtual void foo(int *) override;");
10190   verifyFormat("virtual void foo(char &) const;");
10191   verifyFormat("virtual void foo(int *a, char *) const;");
10192   verifyFormat("int a = sizeof(int *) + b;");
10193   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10194   verifyFormat("bool b = f(g<int>) && c;");
10195   verifyFormat("typedef void (*f)(int i) func;");
10196   verifyFormat("void operator++(int) noexcept;");
10197   verifyFormat("void operator++(int &) noexcept;");
10198   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10199                "&) noexcept;");
10200   verifyFormat(
10201       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10202   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10203   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10204   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10205   verifyFormat("void operator delete(foo &) noexcept;");
10206   verifyFormat("void operator delete(foo) noexcept;");
10207   verifyFormat("void operator delete(int) noexcept;");
10208   verifyFormat("void operator delete(int &) noexcept;");
10209   verifyFormat("void operator delete(int &) volatile noexcept;");
10210   verifyFormat("void operator delete(int &) const");
10211   verifyFormat("void operator delete(int &) = default");
10212   verifyFormat("void operator delete(int &) = delete");
10213   verifyFormat("void operator delete(int &) [[noreturn]]");
10214   verifyFormat("void operator delete(int &) throw();");
10215   verifyFormat("void operator delete(int &) throw(int);");
10216   verifyFormat("auto operator delete(int &) -> int;");
10217   verifyFormat("auto operator delete(int &) override");
10218   verifyFormat("auto operator delete(int &) final");
10219 
10220   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10221                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10222   // FIXME: The indentation here is not ideal.
10223   verifyFormat(
10224       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10225       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10226       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10227 }
10228 
10229 TEST_F(FormatTest, FormatsFunctionTypes) {
10230   verifyFormat("A<bool()> a;");
10231   verifyFormat("A<SomeType()> a;");
10232   verifyFormat("A<void (*)(int, std::string)> a;");
10233   verifyFormat("A<void *(int)>;");
10234   verifyFormat("void *(*a)(int *, SomeType *);");
10235   verifyFormat("int (*func)(void *);");
10236   verifyFormat("void f() { int (*func)(void *); }");
10237   verifyFormat("template <class CallbackClass>\n"
10238                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10239 
10240   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10241   verifyGoogleFormat("void* (*a)(int);");
10242   verifyGoogleFormat(
10243       "template <class CallbackClass>\n"
10244       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10245 
10246   // Other constructs can look somewhat like function types:
10247   verifyFormat("A<sizeof(*x)> a;");
10248   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10249   verifyFormat("some_var = function(*some_pointer_var)[0];");
10250   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10251   verifyFormat("int x = f(&h)();");
10252   verifyFormat("returnsFunction(&param1, &param2)(param);");
10253   verifyFormat("std::function<\n"
10254                "    LooooooooooongTemplatedType<\n"
10255                "        SomeType>*(\n"
10256                "        LooooooooooooooooongType type)>\n"
10257                "    function;",
10258                getGoogleStyleWithColumns(40));
10259 }
10260 
10261 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10262   verifyFormat("A (*foo_)[6];");
10263   verifyFormat("vector<int> (*foo_)[6];");
10264 }
10265 
10266 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10267   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10268                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10269   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10270                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10271   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10272                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10273 
10274   // Different ways of ()-initializiation.
10275   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10276                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10277   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10278                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10279   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10280                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10281   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10282                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10283 
10284   // Lambdas should not confuse the variable declaration heuristic.
10285   verifyFormat("LooooooooooooooooongType\n"
10286                "    variable(nullptr, [](A *a) {});",
10287                getLLVMStyleWithColumns(40));
10288 }
10289 
10290 TEST_F(FormatTest, BreaksLongDeclarations) {
10291   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10292                "    AnotherNameForTheLongType;");
10293   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10294                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10295   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10296                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10297   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10298                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10299   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10300                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10301   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10302                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10303   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10304                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10305   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10306                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10307   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10308                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10309   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10310                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10311   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10312                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10313   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10314                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10315   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10316                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10317   FormatStyle Indented = getLLVMStyle();
10318   Indented.IndentWrappedFunctionNames = true;
10319   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10320                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10321                Indented);
10322   verifyFormat(
10323       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10324       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10325       Indented);
10326   verifyFormat(
10327       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10328       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10329       Indented);
10330   verifyFormat(
10331       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10332       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10333       Indented);
10334 
10335   // FIXME: Without the comment, this breaks after "(".
10336   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10337                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10338                getGoogleStyle());
10339 
10340   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10341                "                  int LoooooooooooooooooooongParam2) {}");
10342   verifyFormat(
10343       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
10344       "                                   SourceLocation L, IdentifierIn *II,\n"
10345       "                                   Type *T) {}");
10346   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
10347                "ReallyReaaallyLongFunctionName(\n"
10348                "    const std::string &SomeParameter,\n"
10349                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10350                "        &ReallyReallyLongParameterName,\n"
10351                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10352                "        &AnotherLongParameterName) {}");
10353   verifyFormat("template <typename A>\n"
10354                "SomeLoooooooooooooooooooooongType<\n"
10355                "    typename some_namespace::SomeOtherType<A>::Type>\n"
10356                "Function() {}");
10357 
10358   verifyGoogleFormat(
10359       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
10360       "    aaaaaaaaaaaaaaaaaaaaaaa;");
10361   verifyGoogleFormat(
10362       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
10363       "                                   SourceLocation L) {}");
10364   verifyGoogleFormat(
10365       "some_namespace::LongReturnType\n"
10366       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
10367       "    int first_long_parameter, int second_parameter) {}");
10368 
10369   verifyGoogleFormat("template <typename T>\n"
10370                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10371                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
10372   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10373                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
10374 
10375   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
10376                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10377                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10378   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10379                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10380                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
10381   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10382                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
10383                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
10384                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10385 
10386   verifyFormat("template <typename T> // Templates on own line.\n"
10387                "static int            // Some comment.\n"
10388                "MyFunction(int a);",
10389                getLLVMStyle());
10390 }
10391 
10392 TEST_F(FormatTest, FormatsAccessModifiers) {
10393   FormatStyle Style = getLLVMStyle();
10394   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
10395             FormatStyle::ELBAMS_LogicalBlock);
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                Style);
10407   verifyFormat("struct foo {\n"
10408                "private:\n"
10409                "  void f() {}\n"
10410                "\n"
10411                "private:\n"
10412                "  int i;\n"
10413                "\n"
10414                "protected:\n"
10415                "  int j;\n"
10416                "};\n",
10417                "struct foo {\n"
10418                "private:\n"
10419                "  void f() {}\n"
10420                "private:\n"
10421                "  int i;\n"
10422                "protected:\n"
10423                "  int j;\n"
10424                "};\n",
10425                Style);
10426   verifyFormat("struct foo { /* comment */\n"
10427                "private:\n"
10428                "  int i;\n"
10429                "  // comment\n"
10430                "private:\n"
10431                "  int j;\n"
10432                "};\n",
10433                Style);
10434   verifyFormat("struct foo {\n"
10435                "#ifdef FOO\n"
10436                "#endif\n"
10437                "private:\n"
10438                "  int i;\n"
10439                "#ifdef FOO\n"
10440                "private:\n"
10441                "#endif\n"
10442                "  int j;\n"
10443                "};\n",
10444                Style);
10445   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10446   verifyFormat("struct foo {\n"
10447                "private:\n"
10448                "  void f() {}\n"
10449                "private:\n"
10450                "  int i;\n"
10451                "protected:\n"
10452                "  int j;\n"
10453                "};\n",
10454                Style);
10455   verifyFormat("struct foo {\n"
10456                "private:\n"
10457                "  void f() {}\n"
10458                "private:\n"
10459                "  int i;\n"
10460                "protected:\n"
10461                "  int j;\n"
10462                "};\n",
10463                "struct foo {\n"
10464                "\n"
10465                "private:\n"
10466                "  void f() {}\n"
10467                "\n"
10468                "private:\n"
10469                "  int i;\n"
10470                "\n"
10471                "protected:\n"
10472                "  int j;\n"
10473                "};\n",
10474                Style);
10475   verifyFormat("struct foo { /* comment */\n"
10476                "private:\n"
10477                "  int i;\n"
10478                "  // comment\n"
10479                "private:\n"
10480                "  int j;\n"
10481                "};\n",
10482                "struct foo { /* comment */\n"
10483                "\n"
10484                "private:\n"
10485                "  int i;\n"
10486                "  // comment\n"
10487                "\n"
10488                "private:\n"
10489                "  int j;\n"
10490                "};\n",
10491                Style);
10492   verifyFormat("struct foo {\n"
10493                "#ifdef FOO\n"
10494                "#endif\n"
10495                "private:\n"
10496                "  int i;\n"
10497                "#ifdef FOO\n"
10498                "private:\n"
10499                "#endif\n"
10500                "  int j;\n"
10501                "};\n",
10502                "struct foo {\n"
10503                "#ifdef FOO\n"
10504                "#endif\n"
10505                "\n"
10506                "private:\n"
10507                "  int i;\n"
10508                "#ifdef FOO\n"
10509                "\n"
10510                "private:\n"
10511                "#endif\n"
10512                "  int j;\n"
10513                "};\n",
10514                Style);
10515   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
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                Style);
10527   verifyFormat("struct foo {\n"
10528                "private:\n"
10529                "  void f() {}\n"
10530                "\n"
10531                "private:\n"
10532                "  int i;\n"
10533                "\n"
10534                "protected:\n"
10535                "  int j;\n"
10536                "};\n",
10537                "struct foo {\n"
10538                "private:\n"
10539                "  void f() {}\n"
10540                "private:\n"
10541                "  int i;\n"
10542                "protected:\n"
10543                "  int j;\n"
10544                "};\n",
10545                Style);
10546   verifyFormat("struct foo { /* comment */\n"
10547                "private:\n"
10548                "  int i;\n"
10549                "  // comment\n"
10550                "\n"
10551                "private:\n"
10552                "  int j;\n"
10553                "};\n",
10554                "struct foo { /* comment */\n"
10555                "private:\n"
10556                "  int i;\n"
10557                "  // comment\n"
10558                "\n"
10559                "private:\n"
10560                "  int j;\n"
10561                "};\n",
10562                Style);
10563   verifyFormat("struct foo {\n"
10564                "#ifdef FOO\n"
10565                "#endif\n"
10566                "\n"
10567                "private:\n"
10568                "  int i;\n"
10569                "#ifdef FOO\n"
10570                "\n"
10571                "private:\n"
10572                "#endif\n"
10573                "  int j;\n"
10574                "};\n",
10575                "struct foo {\n"
10576                "#ifdef FOO\n"
10577                "#endif\n"
10578                "private:\n"
10579                "  int i;\n"
10580                "#ifdef FOO\n"
10581                "private:\n"
10582                "#endif\n"
10583                "  int j;\n"
10584                "};\n",
10585                Style);
10586   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10587   EXPECT_EQ("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             format("struct foo {\n"
10599                    "\n"
10600                    "private:\n"
10601                    "  void f() {}\n"
10602                    "\n"
10603                    "private:\n"
10604                    "  int i;\n"
10605                    "\n"
10606                    "protected:\n"
10607                    "  int j;\n"
10608                    "};\n",
10609                    Style));
10610   verifyFormat("struct foo {\n"
10611                "private:\n"
10612                "  void f() {}\n"
10613                "private:\n"
10614                "  int i;\n"
10615                "protected:\n"
10616                "  int j;\n"
10617                "};\n",
10618                Style);
10619   EXPECT_EQ("struct foo { /* comment */\n"
10620             "\n"
10621             "private:\n"
10622             "  int i;\n"
10623             "  // comment\n"
10624             "\n"
10625             "private:\n"
10626             "  int j;\n"
10627             "};\n",
10628             format("struct foo { /* comment */\n"
10629                    "\n"
10630                    "private:\n"
10631                    "  int i;\n"
10632                    "  // comment\n"
10633                    "\n"
10634                    "private:\n"
10635                    "  int j;\n"
10636                    "};\n",
10637                    Style));
10638   verifyFormat("struct foo { /* comment */\n"
10639                "private:\n"
10640                "  int i;\n"
10641                "  // comment\n"
10642                "private:\n"
10643                "  int j;\n"
10644                "};\n",
10645                Style);
10646   EXPECT_EQ("struct foo {\n"
10647             "#ifdef FOO\n"
10648             "#endif\n"
10649             "\n"
10650             "private:\n"
10651             "  int i;\n"
10652             "#ifdef FOO\n"
10653             "\n"
10654             "private:\n"
10655             "#endif\n"
10656             "  int j;\n"
10657             "};\n",
10658             format("struct foo {\n"
10659                    "#ifdef FOO\n"
10660                    "#endif\n"
10661                    "\n"
10662                    "private:\n"
10663                    "  int i;\n"
10664                    "#ifdef FOO\n"
10665                    "\n"
10666                    "private:\n"
10667                    "#endif\n"
10668                    "  int j;\n"
10669                    "};\n",
10670                    Style));
10671   verifyFormat("struct foo {\n"
10672                "#ifdef FOO\n"
10673                "#endif\n"
10674                "private:\n"
10675                "  int i;\n"
10676                "#ifdef FOO\n"
10677                "private:\n"
10678                "#endif\n"
10679                "  int j;\n"
10680                "};\n",
10681                Style);
10682 
10683   FormatStyle NoEmptyLines = getLLVMStyle();
10684   NoEmptyLines.MaxEmptyLinesToKeep = 0;
10685   verifyFormat("struct foo {\n"
10686                "private:\n"
10687                "  void f() {}\n"
10688                "\n"
10689                "private:\n"
10690                "  int i;\n"
10691                "\n"
10692                "public:\n"
10693                "protected:\n"
10694                "  int j;\n"
10695                "};\n",
10696                NoEmptyLines);
10697 
10698   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10699   verifyFormat("struct foo {\n"
10700                "private:\n"
10701                "  void f() {}\n"
10702                "private:\n"
10703                "  int i;\n"
10704                "public:\n"
10705                "protected:\n"
10706                "  int j;\n"
10707                "};\n",
10708                NoEmptyLines);
10709 
10710   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10711   verifyFormat("struct foo {\n"
10712                "private:\n"
10713                "  void f() {}\n"
10714                "\n"
10715                "private:\n"
10716                "  int i;\n"
10717                "\n"
10718                "public:\n"
10719                "\n"
10720                "protected:\n"
10721                "  int j;\n"
10722                "};\n",
10723                NoEmptyLines);
10724 }
10725 
10726 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
10727 
10728   FormatStyle Style = getLLVMStyle();
10729   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
10730   verifyFormat("struct foo {\n"
10731                "private:\n"
10732                "  void f() {}\n"
10733                "\n"
10734                "private:\n"
10735                "  int i;\n"
10736                "\n"
10737                "protected:\n"
10738                "  int j;\n"
10739                "};\n",
10740                Style);
10741 
10742   // Check if lines are removed.
10743   verifyFormat("struct foo {\n"
10744                "private:\n"
10745                "  void f() {}\n"
10746                "\n"
10747                "private:\n"
10748                "  int i;\n"
10749                "\n"
10750                "protected:\n"
10751                "  int j;\n"
10752                "};\n",
10753                "struct foo {\n"
10754                "private:\n"
10755                "\n"
10756                "  void f() {}\n"
10757                "\n"
10758                "private:\n"
10759                "\n"
10760                "  int i;\n"
10761                "\n"
10762                "protected:\n"
10763                "\n"
10764                "  int j;\n"
10765                "};\n",
10766                Style);
10767 
10768   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10769   verifyFormat("struct foo {\n"
10770                "private:\n"
10771                "\n"
10772                "  void f() {}\n"
10773                "\n"
10774                "private:\n"
10775                "\n"
10776                "  int i;\n"
10777                "\n"
10778                "protected:\n"
10779                "\n"
10780                "  int j;\n"
10781                "};\n",
10782                Style);
10783 
10784   // Check if lines are added.
10785   verifyFormat("struct foo {\n"
10786                "private:\n"
10787                "\n"
10788                "  void f() {}\n"
10789                "\n"
10790                "private:\n"
10791                "\n"
10792                "  int i;\n"
10793                "\n"
10794                "protected:\n"
10795                "\n"
10796                "  int j;\n"
10797                "};\n",
10798                "struct foo {\n"
10799                "private:\n"
10800                "  void f() {}\n"
10801                "\n"
10802                "private:\n"
10803                "  int i;\n"
10804                "\n"
10805                "protected:\n"
10806                "  int j;\n"
10807                "};\n",
10808                Style);
10809 
10810   // Leave tests rely on the code layout, test::messUp can not be used.
10811   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10812   Style.MaxEmptyLinesToKeep = 0u;
10813   verifyFormat("struct foo {\n"
10814                "private:\n"
10815                "  void f() {}\n"
10816                "\n"
10817                "private:\n"
10818                "  int i;\n"
10819                "\n"
10820                "protected:\n"
10821                "  int j;\n"
10822                "};\n",
10823                Style);
10824 
10825   // Check if MaxEmptyLinesToKeep is respected.
10826   EXPECT_EQ("struct foo {\n"
10827             "private:\n"
10828             "  void f() {}\n"
10829             "\n"
10830             "private:\n"
10831             "  int i;\n"
10832             "\n"
10833             "protected:\n"
10834             "  int j;\n"
10835             "};\n",
10836             format("struct foo {\n"
10837                    "private:\n"
10838                    "\n\n\n"
10839                    "  void f() {}\n"
10840                    "\n"
10841                    "private:\n"
10842                    "\n\n\n"
10843                    "  int i;\n"
10844                    "\n"
10845                    "protected:\n"
10846                    "\n\n\n"
10847                    "  int j;\n"
10848                    "};\n",
10849                    Style));
10850 
10851   Style.MaxEmptyLinesToKeep = 1u;
10852   EXPECT_EQ("struct foo {\n"
10853             "private:\n"
10854             "\n"
10855             "  void f() {}\n"
10856             "\n"
10857             "private:\n"
10858             "\n"
10859             "  int i;\n"
10860             "\n"
10861             "protected:\n"
10862             "\n"
10863             "  int j;\n"
10864             "};\n",
10865             format("struct foo {\n"
10866                    "private:\n"
10867                    "\n"
10868                    "  void f() {}\n"
10869                    "\n"
10870                    "private:\n"
10871                    "\n"
10872                    "  int i;\n"
10873                    "\n"
10874                    "protected:\n"
10875                    "\n"
10876                    "  int j;\n"
10877                    "};\n",
10878                    Style));
10879   // Check if no lines are kept.
10880   EXPECT_EQ("struct foo {\n"
10881             "private:\n"
10882             "  void f() {}\n"
10883             "\n"
10884             "private:\n"
10885             "  int i;\n"
10886             "\n"
10887             "protected:\n"
10888             "  int j;\n"
10889             "};\n",
10890             format("struct foo {\n"
10891                    "private:\n"
10892                    "  void f() {}\n"
10893                    "\n"
10894                    "private:\n"
10895                    "  int i;\n"
10896                    "\n"
10897                    "protected:\n"
10898                    "  int j;\n"
10899                    "};\n",
10900                    Style));
10901   // Check if MaxEmptyLinesToKeep is respected.
10902   EXPECT_EQ("struct foo {\n"
10903             "private:\n"
10904             "\n"
10905             "  void f() {}\n"
10906             "\n"
10907             "private:\n"
10908             "\n"
10909             "  int i;\n"
10910             "\n"
10911             "protected:\n"
10912             "\n"
10913             "  int j;\n"
10914             "};\n",
10915             format("struct foo {\n"
10916                    "private:\n"
10917                    "\n\n\n"
10918                    "  void f() {}\n"
10919                    "\n"
10920                    "private:\n"
10921                    "\n\n\n"
10922                    "  int i;\n"
10923                    "\n"
10924                    "protected:\n"
10925                    "\n\n\n"
10926                    "  int j;\n"
10927                    "};\n",
10928                    Style));
10929 
10930   Style.MaxEmptyLinesToKeep = 10u;
10931   EXPECT_EQ("struct foo {\n"
10932             "private:\n"
10933             "\n\n\n"
10934             "  void f() {}\n"
10935             "\n"
10936             "private:\n"
10937             "\n\n\n"
10938             "  int i;\n"
10939             "\n"
10940             "protected:\n"
10941             "\n\n\n"
10942             "  int j;\n"
10943             "};\n",
10944             format("struct foo {\n"
10945                    "private:\n"
10946                    "\n\n\n"
10947                    "  void f() {}\n"
10948                    "\n"
10949                    "private:\n"
10950                    "\n\n\n"
10951                    "  int i;\n"
10952                    "\n"
10953                    "protected:\n"
10954                    "\n\n\n"
10955                    "  int j;\n"
10956                    "};\n",
10957                    Style));
10958 
10959   // Test with comments.
10960   Style = getLLVMStyle();
10961   verifyFormat("struct foo {\n"
10962                "private:\n"
10963                "  // comment\n"
10964                "  void f() {}\n"
10965                "\n"
10966                "private: /* comment */\n"
10967                "  int i;\n"
10968                "};\n",
10969                Style);
10970   verifyFormat("struct foo {\n"
10971                "private:\n"
10972                "  // comment\n"
10973                "  void f() {}\n"
10974                "\n"
10975                "private: /* comment */\n"
10976                "  int i;\n"
10977                "};\n",
10978                "struct foo {\n"
10979                "private:\n"
10980                "\n"
10981                "  // comment\n"
10982                "  void f() {}\n"
10983                "\n"
10984                "private: /* comment */\n"
10985                "\n"
10986                "  int i;\n"
10987                "};\n",
10988                Style);
10989 
10990   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10991   verifyFormat("struct foo {\n"
10992                "private:\n"
10993                "\n"
10994                "  // comment\n"
10995                "  void f() {}\n"
10996                "\n"
10997                "private: /* comment */\n"
10998                "\n"
10999                "  int i;\n"
11000                "};\n",
11001                "struct foo {\n"
11002                "private:\n"
11003                "  // comment\n"
11004                "  void f() {}\n"
11005                "\n"
11006                "private: /* comment */\n"
11007                "  int i;\n"
11008                "};\n",
11009                Style);
11010   verifyFormat("struct foo {\n"
11011                "private:\n"
11012                "\n"
11013                "  // comment\n"
11014                "  void f() {}\n"
11015                "\n"
11016                "private: /* comment */\n"
11017                "\n"
11018                "  int i;\n"
11019                "};\n",
11020                Style);
11021 
11022   // Test with preprocessor defines.
11023   Style = getLLVMStyle();
11024   verifyFormat("struct foo {\n"
11025                "private:\n"
11026                "#ifdef FOO\n"
11027                "#endif\n"
11028                "  void f() {}\n"
11029                "};\n",
11030                Style);
11031   verifyFormat("struct foo {\n"
11032                "private:\n"
11033                "#ifdef FOO\n"
11034                "#endif\n"
11035                "  void f() {}\n"
11036                "};\n",
11037                "struct foo {\n"
11038                "private:\n"
11039                "\n"
11040                "#ifdef FOO\n"
11041                "#endif\n"
11042                "  void f() {}\n"
11043                "};\n",
11044                Style);
11045 
11046   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11047   verifyFormat("struct foo {\n"
11048                "private:\n"
11049                "\n"
11050                "#ifdef FOO\n"
11051                "#endif\n"
11052                "  void f() {}\n"
11053                "};\n",
11054                "struct foo {\n"
11055                "private:\n"
11056                "#ifdef FOO\n"
11057                "#endif\n"
11058                "  void f() {}\n"
11059                "};\n",
11060                Style);
11061   verifyFormat("struct foo {\n"
11062                "private:\n"
11063                "\n"
11064                "#ifdef FOO\n"
11065                "#endif\n"
11066                "  void f() {}\n"
11067                "};\n",
11068                Style);
11069 }
11070 
11071 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11072   // Combined tests of EmptyLineAfterAccessModifier and
11073   // EmptyLineBeforeAccessModifier.
11074   FormatStyle Style = getLLVMStyle();
11075   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11076   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11077   verifyFormat("struct foo {\n"
11078                "private:\n"
11079                "\n"
11080                "protected:\n"
11081                "};\n",
11082                Style);
11083 
11084   Style.MaxEmptyLinesToKeep = 10u;
11085   // Both remove all new lines.
11086   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11087   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11088   verifyFormat("struct foo {\n"
11089                "private:\n"
11090                "protected:\n"
11091                "};\n",
11092                "struct foo {\n"
11093                "private:\n"
11094                "\n\n\n"
11095                "protected:\n"
11096                "};\n",
11097                Style);
11098 
11099   // Leave tests rely on the code layout, test::messUp can not be used.
11100   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11101   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11102   Style.MaxEmptyLinesToKeep = 10u;
11103   EXPECT_EQ("struct foo {\n"
11104             "private:\n"
11105             "\n\n\n"
11106             "protected:\n"
11107             "};\n",
11108             format("struct foo {\n"
11109                    "private:\n"
11110                    "\n\n\n"
11111                    "protected:\n"
11112                    "};\n",
11113                    Style));
11114   Style.MaxEmptyLinesToKeep = 3u;
11115   EXPECT_EQ("struct foo {\n"
11116             "private:\n"
11117             "\n\n\n"
11118             "protected:\n"
11119             "};\n",
11120             format("struct foo {\n"
11121                    "private:\n"
11122                    "\n\n\n"
11123                    "protected:\n"
11124                    "};\n",
11125                    Style));
11126   Style.MaxEmptyLinesToKeep = 1u;
11127   EXPECT_EQ("struct foo {\n"
11128             "private:\n"
11129             "\n\n\n"
11130             "protected:\n"
11131             "};\n",
11132             format("struct foo {\n"
11133                    "private:\n"
11134                    "\n\n\n"
11135                    "protected:\n"
11136                    "};\n",
11137                    Style)); // Based on new lines in original document and not
11138                             // on the setting.
11139 
11140   Style.MaxEmptyLinesToKeep = 10u;
11141   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11142   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11143   // Newlines are kept if they are greater than zero,
11144   // test::messUp removes all new lines which changes the logic
11145   EXPECT_EQ("struct foo {\n"
11146             "private:\n"
11147             "\n\n\n"
11148             "protected:\n"
11149             "};\n",
11150             format("struct foo {\n"
11151                    "private:\n"
11152                    "\n\n\n"
11153                    "protected:\n"
11154                    "};\n",
11155                    Style));
11156 
11157   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11158   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11159   // test::messUp removes all new lines which changes the logic
11160   EXPECT_EQ("struct foo {\n"
11161             "private:\n"
11162             "\n\n\n"
11163             "protected:\n"
11164             "};\n",
11165             format("struct foo {\n"
11166                    "private:\n"
11167                    "\n\n\n"
11168                    "protected:\n"
11169                    "};\n",
11170                    Style));
11171 
11172   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11173   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11174   EXPECT_EQ("struct foo {\n"
11175             "private:\n"
11176             "\n\n\n"
11177             "protected:\n"
11178             "};\n",
11179             format("struct foo {\n"
11180                    "private:\n"
11181                    "\n\n\n"
11182                    "protected:\n"
11183                    "};\n",
11184                    Style)); // test::messUp removes all new lines which changes
11185                             // the logic.
11186 
11187   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11188   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11189   verifyFormat("struct foo {\n"
11190                "private:\n"
11191                "protected:\n"
11192                "};\n",
11193                "struct foo {\n"
11194                "private:\n"
11195                "\n\n\n"
11196                "protected:\n"
11197                "};\n",
11198                Style);
11199 
11200   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11201   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11202   EXPECT_EQ("struct foo {\n"
11203             "private:\n"
11204             "\n\n\n"
11205             "protected:\n"
11206             "};\n",
11207             format("struct foo {\n"
11208                    "private:\n"
11209                    "\n\n\n"
11210                    "protected:\n"
11211                    "};\n",
11212                    Style)); // test::messUp removes all new lines which changes
11213                             // the logic.
11214 
11215   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11216   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11217   verifyFormat("struct foo {\n"
11218                "private:\n"
11219                "protected:\n"
11220                "};\n",
11221                "struct foo {\n"
11222                "private:\n"
11223                "\n\n\n"
11224                "protected:\n"
11225                "};\n",
11226                Style);
11227 
11228   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11229   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11230   verifyFormat("struct foo {\n"
11231                "private:\n"
11232                "protected:\n"
11233                "};\n",
11234                "struct foo {\n"
11235                "private:\n"
11236                "\n\n\n"
11237                "protected:\n"
11238                "};\n",
11239                Style);
11240 
11241   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11242   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11243   verifyFormat("struct foo {\n"
11244                "private:\n"
11245                "protected:\n"
11246                "};\n",
11247                "struct foo {\n"
11248                "private:\n"
11249                "\n\n\n"
11250                "protected:\n"
11251                "};\n",
11252                Style);
11253 
11254   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11255   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11256   verifyFormat("struct foo {\n"
11257                "private:\n"
11258                "protected:\n"
11259                "};\n",
11260                "struct foo {\n"
11261                "private:\n"
11262                "\n\n\n"
11263                "protected:\n"
11264                "};\n",
11265                Style);
11266 }
11267 
11268 TEST_F(FormatTest, FormatsArrays) {
11269   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11270                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11271   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11272                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11273   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11274                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11275   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11276                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11277   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11278                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11279   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11280                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11281                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11282   verifyFormat(
11283       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11284       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11285       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11286   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11287                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11288 
11289   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11290                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11291   verifyFormat(
11292       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11293       "                                  .aaaaaaa[0]\n"
11294       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11295   verifyFormat("a[::b::c];");
11296 
11297   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11298 
11299   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11300   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11301 }
11302 
11303 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11304   verifyFormat("(a)->b();");
11305   verifyFormat("--a;");
11306 }
11307 
11308 TEST_F(FormatTest, HandlesIncludeDirectives) {
11309   verifyFormat("#include <string>\n"
11310                "#include <a/b/c.h>\n"
11311                "#include \"a/b/string\"\n"
11312                "#include \"string.h\"\n"
11313                "#include \"string.h\"\n"
11314                "#include <a-a>\n"
11315                "#include < path with space >\n"
11316                "#include_next <test.h>"
11317                "#include \"abc.h\" // this is included for ABC\n"
11318                "#include \"some long include\" // with a comment\n"
11319                "#include \"some very long include path\"\n"
11320                "#include <some/very/long/include/path>\n",
11321                getLLVMStyleWithColumns(35));
11322   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11323   EXPECT_EQ("#include <a>", format("#include<a>"));
11324 
11325   verifyFormat("#import <string>");
11326   verifyFormat("#import <a/b/c.h>");
11327   verifyFormat("#import \"a/b/string\"");
11328   verifyFormat("#import \"string.h\"");
11329   verifyFormat("#import \"string.h\"");
11330   verifyFormat("#if __has_include(<strstream>)\n"
11331                "#include <strstream>\n"
11332                "#endif");
11333 
11334   verifyFormat("#define MY_IMPORT <a/b>");
11335 
11336   verifyFormat("#if __has_include(<a/b>)");
11337   verifyFormat("#if __has_include_next(<a/b>)");
11338   verifyFormat("#define F __has_include(<a/b>)");
11339   verifyFormat("#define F __has_include_next(<a/b>)");
11340 
11341   // Protocol buffer definition or missing "#".
11342   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
11343                getLLVMStyleWithColumns(30));
11344 
11345   FormatStyle Style = getLLVMStyle();
11346   Style.AlwaysBreakBeforeMultilineStrings = true;
11347   Style.ColumnLimit = 0;
11348   verifyFormat("#import \"abc.h\"", Style);
11349 
11350   // But 'import' might also be a regular C++ namespace.
11351   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11352                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11353 }
11354 
11355 //===----------------------------------------------------------------------===//
11356 // Error recovery tests.
11357 //===----------------------------------------------------------------------===//
11358 
11359 TEST_F(FormatTest, IncompleteParameterLists) {
11360   FormatStyle NoBinPacking = getLLVMStyle();
11361   NoBinPacking.BinPackParameters = false;
11362   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
11363                "                        double *min_x,\n"
11364                "                        double *max_x,\n"
11365                "                        double *min_y,\n"
11366                "                        double *max_y,\n"
11367                "                        double *min_z,\n"
11368                "                        double *max_z, ) {}",
11369                NoBinPacking);
11370 }
11371 
11372 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
11373   verifyFormat("void f() { return; }\n42");
11374   verifyFormat("void f() {\n"
11375                "  if (0)\n"
11376                "    return;\n"
11377                "}\n"
11378                "42");
11379   verifyFormat("void f() { return }\n42");
11380   verifyFormat("void f() {\n"
11381                "  if (0)\n"
11382                "    return\n"
11383                "}\n"
11384                "42");
11385 }
11386 
11387 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
11388   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
11389   EXPECT_EQ("void f() {\n"
11390             "  if (a)\n"
11391             "    return\n"
11392             "}",
11393             format("void  f  (  )  {  if  ( a )  return  }"));
11394   EXPECT_EQ("namespace N {\n"
11395             "void f()\n"
11396             "}",
11397             format("namespace  N  {  void f()  }"));
11398   EXPECT_EQ("namespace N {\n"
11399             "void f() {}\n"
11400             "void g()\n"
11401             "} // namespace N",
11402             format("namespace N  { void f( ) { } void g( ) }"));
11403 }
11404 
11405 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
11406   verifyFormat("int aaaaaaaa =\n"
11407                "    // Overlylongcomment\n"
11408                "    b;",
11409                getLLVMStyleWithColumns(20));
11410   verifyFormat("function(\n"
11411                "    ShortArgument,\n"
11412                "    LoooooooooooongArgument);\n",
11413                getLLVMStyleWithColumns(20));
11414 }
11415 
11416 TEST_F(FormatTest, IncorrectAccessSpecifier) {
11417   verifyFormat("public:");
11418   verifyFormat("class A {\n"
11419                "public\n"
11420                "  void f() {}\n"
11421                "};");
11422   verifyFormat("public\n"
11423                "int qwerty;");
11424   verifyFormat("public\n"
11425                "B {}");
11426   verifyFormat("public\n"
11427                "{}");
11428   verifyFormat("public\n"
11429                "B { int x; }");
11430 }
11431 
11432 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
11433   verifyFormat("{");
11434   verifyFormat("#})");
11435   verifyNoCrash("(/**/[:!] ?[).");
11436 }
11437 
11438 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
11439   // Found by oss-fuzz:
11440   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
11441   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
11442   Style.ColumnLimit = 60;
11443   verifyNoCrash(
11444       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
11445       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
11446       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
11447       Style);
11448 }
11449 
11450 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
11451   verifyFormat("do {\n}");
11452   verifyFormat("do {\n}\n"
11453                "f();");
11454   verifyFormat("do {\n}\n"
11455                "wheeee(fun);");
11456   verifyFormat("do {\n"
11457                "  f();\n"
11458                "}");
11459 }
11460 
11461 TEST_F(FormatTest, IncorrectCodeMissingParens) {
11462   verifyFormat("if {\n  foo;\n  foo();\n}");
11463   verifyFormat("switch {\n  foo;\n  foo();\n}");
11464   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
11465   verifyFormat("while {\n  foo;\n  foo();\n}");
11466   verifyFormat("do {\n  foo;\n  foo();\n} while;");
11467 }
11468 
11469 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
11470   verifyIncompleteFormat("namespace {\n"
11471                          "class Foo { Foo (\n"
11472                          "};\n"
11473                          "} // namespace");
11474 }
11475 
11476 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
11477   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
11478   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
11479   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
11480   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
11481 
11482   EXPECT_EQ("{\n"
11483             "  {\n"
11484             "    breakme(\n"
11485             "        qwe);\n"
11486             "  }\n",
11487             format("{\n"
11488                    "    {\n"
11489                    " breakme(qwe);\n"
11490                    "}\n",
11491                    getLLVMStyleWithColumns(10)));
11492 }
11493 
11494 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
11495   verifyFormat("int x = {\n"
11496                "    avariable,\n"
11497                "    b(alongervariable)};",
11498                getLLVMStyleWithColumns(25));
11499 }
11500 
11501 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
11502   verifyFormat("return (a)(b){1, 2, 3};");
11503 }
11504 
11505 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
11506   verifyFormat("vector<int> x{1, 2, 3, 4};");
11507   verifyFormat("vector<int> x{\n"
11508                "    1,\n"
11509                "    2,\n"
11510                "    3,\n"
11511                "    4,\n"
11512                "};");
11513   verifyFormat("vector<T> x{{}, {}, {}, {}};");
11514   verifyFormat("f({1, 2});");
11515   verifyFormat("auto v = Foo{-1};");
11516   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
11517   verifyFormat("Class::Class : member{1, 2, 3} {}");
11518   verifyFormat("new vector<int>{1, 2, 3};");
11519   verifyFormat("new int[3]{1, 2, 3};");
11520   verifyFormat("new int{1};");
11521   verifyFormat("return {arg1, arg2};");
11522   verifyFormat("return {arg1, SomeType{parameter}};");
11523   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
11524   verifyFormat("new T{arg1, arg2};");
11525   verifyFormat("f(MyMap[{composite, key}]);");
11526   verifyFormat("class Class {\n"
11527                "  T member = {arg1, arg2};\n"
11528                "};");
11529   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
11530   verifyFormat("const struct A a = {.a = 1, .b = 2};");
11531   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
11532   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
11533   verifyFormat("int a = std::is_integral<int>{} + 0;");
11534 
11535   verifyFormat("int foo(int i) { return fo1{}(i); }");
11536   verifyFormat("int foo(int i) { return fo1{}(i); }");
11537   verifyFormat("auto i = decltype(x){};");
11538   verifyFormat("auto i = typeof(x){};");
11539   verifyFormat("auto i = _Atomic(x){};");
11540   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
11541   verifyFormat("Node n{1, Node{1000}, //\n"
11542                "       2};");
11543   verifyFormat("Aaaa aaaaaaa{\n"
11544                "    {\n"
11545                "        aaaa,\n"
11546                "    },\n"
11547                "};");
11548   verifyFormat("class C : public D {\n"
11549                "  SomeClass SC{2};\n"
11550                "};");
11551   verifyFormat("class C : public A {\n"
11552                "  class D : public B {\n"
11553                "    void f() { int i{2}; }\n"
11554                "  };\n"
11555                "};");
11556   verifyFormat("#define A {a, a},");
11557   // Don't confuse braced list initializers with compound statements.
11558   verifyFormat(
11559       "class A {\n"
11560       "  A() : a{} {}\n"
11561       "  A(int b) : b(b) {}\n"
11562       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
11563       "  int a, b;\n"
11564       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
11565       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
11566       "{}\n"
11567       "};");
11568 
11569   // Avoid breaking between equal sign and opening brace
11570   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
11571   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
11572   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
11573                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
11574                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
11575                "     {\"ccccccccccccccccccccc\", 2}};",
11576                AvoidBreakingFirstArgument);
11577 
11578   // Binpacking only if there is no trailing comma
11579   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
11580                "                      cccccccccc, dddddddddd};",
11581                getLLVMStyleWithColumns(50));
11582   verifyFormat("const Aaaaaa aaaaa = {\n"
11583                "    aaaaaaaaaaa,\n"
11584                "    bbbbbbbbbbb,\n"
11585                "    ccccccccccc,\n"
11586                "    ddddddddddd,\n"
11587                "};",
11588                getLLVMStyleWithColumns(50));
11589 
11590   // Cases where distinguising braced lists and blocks is hard.
11591   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
11592   verifyFormat("void f() {\n"
11593                "  return; // comment\n"
11594                "}\n"
11595                "SomeType t;");
11596   verifyFormat("void f() {\n"
11597                "  if (a) {\n"
11598                "    f();\n"
11599                "  }\n"
11600                "}\n"
11601                "SomeType t;");
11602 
11603   // In combination with BinPackArguments = false.
11604   FormatStyle NoBinPacking = getLLVMStyle();
11605   NoBinPacking.BinPackArguments = false;
11606   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
11607                "                      bbbbb,\n"
11608                "                      ccccc,\n"
11609                "                      ddddd,\n"
11610                "                      eeeee,\n"
11611                "                      ffffff,\n"
11612                "                      ggggg,\n"
11613                "                      hhhhhh,\n"
11614                "                      iiiiii,\n"
11615                "                      jjjjjj,\n"
11616                "                      kkkkkk};",
11617                NoBinPacking);
11618   verifyFormat("const Aaaaaa aaaaa = {\n"
11619                "    aaaaa,\n"
11620                "    bbbbb,\n"
11621                "    ccccc,\n"
11622                "    ddddd,\n"
11623                "    eeeee,\n"
11624                "    ffffff,\n"
11625                "    ggggg,\n"
11626                "    hhhhhh,\n"
11627                "    iiiiii,\n"
11628                "    jjjjjj,\n"
11629                "    kkkkkk,\n"
11630                "};",
11631                NoBinPacking);
11632   verifyFormat(
11633       "const Aaaaaa aaaaa = {\n"
11634       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
11635       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
11636       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
11637       "};",
11638       NoBinPacking);
11639 
11640   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11641   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
11642             "    CDDDP83848_BMCR_REGISTER,\n"
11643             "    CDDDP83848_BMSR_REGISTER,\n"
11644             "    CDDDP83848_RBR_REGISTER};",
11645             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
11646                    "                                CDDDP83848_BMSR_REGISTER,\n"
11647                    "                                CDDDP83848_RBR_REGISTER};",
11648                    NoBinPacking));
11649 
11650   // FIXME: The alignment of these trailing comments might be bad. Then again,
11651   // this might be utterly useless in real code.
11652   verifyFormat("Constructor::Constructor()\n"
11653                "    : some_value{         //\n"
11654                "                 aaaaaaa, //\n"
11655                "                 bbbbbbb} {}");
11656 
11657   // In braced lists, the first comment is always assumed to belong to the
11658   // first element. Thus, it can be moved to the next or previous line as
11659   // appropriate.
11660   EXPECT_EQ("function({// First element:\n"
11661             "          1,\n"
11662             "          // Second element:\n"
11663             "          2});",
11664             format("function({\n"
11665                    "    // First element:\n"
11666                    "    1,\n"
11667                    "    // Second element:\n"
11668                    "    2});"));
11669   EXPECT_EQ("std::vector<int> MyNumbers{\n"
11670             "    // First element:\n"
11671             "    1,\n"
11672             "    // Second element:\n"
11673             "    2};",
11674             format("std::vector<int> MyNumbers{// First element:\n"
11675                    "                           1,\n"
11676                    "                           // Second element:\n"
11677                    "                           2};",
11678                    getLLVMStyleWithColumns(30)));
11679   // A trailing comma should still lead to an enforced line break and no
11680   // binpacking.
11681   EXPECT_EQ("vector<int> SomeVector = {\n"
11682             "    // aaa\n"
11683             "    1,\n"
11684             "    2,\n"
11685             "};",
11686             format("vector<int> SomeVector = { // aaa\n"
11687                    "    1, 2, };"));
11688 
11689   // C++11 brace initializer list l-braces should not be treated any differently
11690   // when breaking before lambda bodies is enabled
11691   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
11692   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
11693   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
11694   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
11695   verifyFormat(
11696       "std::runtime_error{\n"
11697       "    \"Long string which will force a break onto the next line...\"};",
11698       BreakBeforeLambdaBody);
11699 
11700   FormatStyle ExtraSpaces = getLLVMStyle();
11701   ExtraSpaces.Cpp11BracedListStyle = false;
11702   ExtraSpaces.ColumnLimit = 75;
11703   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
11704   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
11705   verifyFormat("f({ 1, 2 });", ExtraSpaces);
11706   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
11707   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
11708   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
11709   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
11710   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
11711   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
11712   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
11713   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
11714   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
11715   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
11716   verifyFormat("class Class {\n"
11717                "  T member = { arg1, arg2 };\n"
11718                "};",
11719                ExtraSpaces);
11720   verifyFormat(
11721       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11722       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
11723       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
11724       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
11725       ExtraSpaces);
11726   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
11727   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
11728                ExtraSpaces);
11729   verifyFormat(
11730       "someFunction(OtherParam,\n"
11731       "             BracedList{ // comment 1 (Forcing interesting break)\n"
11732       "                         param1, param2,\n"
11733       "                         // comment 2\n"
11734       "                         param3, param4 });",
11735       ExtraSpaces);
11736   verifyFormat(
11737       "std::this_thread::sleep_for(\n"
11738       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
11739       ExtraSpaces);
11740   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
11741                "    aaaaaaa,\n"
11742                "    aaaaaaaaaa,\n"
11743                "    aaaaa,\n"
11744                "    aaaaaaaaaaaaaaa,\n"
11745                "    aaa,\n"
11746                "    aaaaaaaaaa,\n"
11747                "    a,\n"
11748                "    aaaaaaaaaaaaaaaaaaaaa,\n"
11749                "    aaaaaaaaaaaa,\n"
11750                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
11751                "    aaaaaaa,\n"
11752                "    a};");
11753   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
11754   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
11755   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
11756 
11757   // Avoid breaking between initializer/equal sign and opening brace
11758   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
11759   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
11760                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11761                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11762                "  { \"ccccccccccccccccccccc\", 2 }\n"
11763                "};",
11764                ExtraSpaces);
11765   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
11766                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11767                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11768                "  { \"ccccccccccccccccccccc\", 2 }\n"
11769                "};",
11770                ExtraSpaces);
11771 
11772   FormatStyle SpaceBeforeBrace = getLLVMStyle();
11773   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
11774   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
11775   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
11776 
11777   FormatStyle SpaceBetweenBraces = getLLVMStyle();
11778   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
11779   SpaceBetweenBraces.SpacesInParentheses = true;
11780   SpaceBetweenBraces.SpacesInSquareBrackets = true;
11781   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
11782   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
11783   verifyFormat("vector< int > x{ // comment 1\n"
11784                "                 1, 2, 3, 4 };",
11785                SpaceBetweenBraces);
11786   SpaceBetweenBraces.ColumnLimit = 20;
11787   EXPECT_EQ("vector< int > x{\n"
11788             "    1, 2, 3, 4 };",
11789             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11790   SpaceBetweenBraces.ColumnLimit = 24;
11791   EXPECT_EQ("vector< int > x{ 1, 2,\n"
11792             "                 3, 4 };",
11793             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11794   EXPECT_EQ("vector< int > x{\n"
11795             "    1,\n"
11796             "    2,\n"
11797             "    3,\n"
11798             "    4,\n"
11799             "};",
11800             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
11801   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
11802   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
11803   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
11804 }
11805 
11806 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
11807   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11808                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11809                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11810                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11811                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11812                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
11813   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
11814                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11815                "                 1, 22, 333, 4444, 55555, //\n"
11816                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11817                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
11818   verifyFormat(
11819       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
11820       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
11821       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
11822       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11823       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11824       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11825       "                 7777777};");
11826   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11827                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11828                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
11829   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11830                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11831                "    // Separating comment.\n"
11832                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
11833   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11834                "    // Leading comment\n"
11835                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11836                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
11837   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11838                "                 1, 1, 1, 1};",
11839                getLLVMStyleWithColumns(39));
11840   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11841                "                 1, 1, 1, 1};",
11842                getLLVMStyleWithColumns(38));
11843   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
11844                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
11845                getLLVMStyleWithColumns(43));
11846   verifyFormat(
11847       "static unsigned SomeValues[10][3] = {\n"
11848       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
11849       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
11850   verifyFormat("static auto fields = new vector<string>{\n"
11851                "    \"aaaaaaaaaaaaa\",\n"
11852                "    \"aaaaaaaaaaaaa\",\n"
11853                "    \"aaaaaaaaaaaa\",\n"
11854                "    \"aaaaaaaaaaaaaa\",\n"
11855                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11856                "    \"aaaaaaaaaaaa\",\n"
11857                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11858                "};");
11859   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
11860   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
11861                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
11862                "                 3, cccccccccccccccccccccc};",
11863                getLLVMStyleWithColumns(60));
11864 
11865   // Trailing commas.
11866   verifyFormat("vector<int> x = {\n"
11867                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
11868                "};",
11869                getLLVMStyleWithColumns(39));
11870   verifyFormat("vector<int> x = {\n"
11871                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
11872                "};",
11873                getLLVMStyleWithColumns(39));
11874   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11875                "                 1, 1, 1, 1,\n"
11876                "                 /**/ /**/};",
11877                getLLVMStyleWithColumns(39));
11878 
11879   // Trailing comment in the first line.
11880   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
11881                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
11882                "    111111111,  222222222,  3333333333,  444444444,  //\n"
11883                "    11111111,   22222222,   333333333,   44444444};");
11884   // Trailing comment in the last line.
11885   verifyFormat("int aaaaa[] = {\n"
11886                "    1, 2, 3, // comment\n"
11887                "    4, 5, 6  // comment\n"
11888                "};");
11889 
11890   // With nested lists, we should either format one item per line or all nested
11891   // lists one on line.
11892   // FIXME: For some nested lists, we can do better.
11893   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
11894                "        {aaaaaaaaaaaaaaaaaaa},\n"
11895                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
11896                "        {aaaaaaaaaaaaaaaaa}};",
11897                getLLVMStyleWithColumns(60));
11898   verifyFormat(
11899       "SomeStruct my_struct_array = {\n"
11900       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
11901       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
11902       "    {aaa, aaa},\n"
11903       "    {aaa, aaa},\n"
11904       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
11905       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
11906       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
11907 
11908   // No column layout should be used here.
11909   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
11910                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
11911 
11912   verifyNoCrash("a<,");
11913 
11914   // No braced initializer here.
11915   verifyFormat("void f() {\n"
11916                "  struct Dummy {};\n"
11917                "  f(v);\n"
11918                "}");
11919 
11920   // Long lists should be formatted in columns even if they are nested.
11921   verifyFormat(
11922       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11923       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11924       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11925       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11926       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11927       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
11928 
11929   // Allow "single-column" layout even if that violates the column limit. There
11930   // isn't going to be a better way.
11931   verifyFormat("std::vector<int> a = {\n"
11932                "    aaaaaaaa,\n"
11933                "    aaaaaaaa,\n"
11934                "    aaaaaaaa,\n"
11935                "    aaaaaaaa,\n"
11936                "    aaaaaaaaaa,\n"
11937                "    aaaaaaaa,\n"
11938                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
11939                getLLVMStyleWithColumns(30));
11940   verifyFormat("vector<int> aaaa = {\n"
11941                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11942                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11943                "    aaaaaa.aaaaaaa,\n"
11944                "    aaaaaa.aaaaaaa,\n"
11945                "    aaaaaa.aaaaaaa,\n"
11946                "    aaaaaa.aaaaaaa,\n"
11947                "};");
11948 
11949   // Don't create hanging lists.
11950   verifyFormat("someFunction(Param, {List1, List2,\n"
11951                "                     List3});",
11952                getLLVMStyleWithColumns(35));
11953   verifyFormat("someFunction(Param, Param,\n"
11954                "             {List1, List2,\n"
11955                "              List3});",
11956                getLLVMStyleWithColumns(35));
11957   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
11958                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
11959 }
11960 
11961 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
11962   FormatStyle DoNotMerge = getLLVMStyle();
11963   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
11964 
11965   verifyFormat("void f() { return 42; }");
11966   verifyFormat("void f() {\n"
11967                "  return 42;\n"
11968                "}",
11969                DoNotMerge);
11970   verifyFormat("void f() {\n"
11971                "  // Comment\n"
11972                "}");
11973   verifyFormat("{\n"
11974                "#error {\n"
11975                "  int a;\n"
11976                "}");
11977   verifyFormat("{\n"
11978                "  int a;\n"
11979                "#error {\n"
11980                "}");
11981   verifyFormat("void f() {} // comment");
11982   verifyFormat("void f() { int a; } // comment");
11983   verifyFormat("void f() {\n"
11984                "} // comment",
11985                DoNotMerge);
11986   verifyFormat("void f() {\n"
11987                "  int a;\n"
11988                "} // comment",
11989                DoNotMerge);
11990   verifyFormat("void f() {\n"
11991                "} // comment",
11992                getLLVMStyleWithColumns(15));
11993 
11994   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
11995   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
11996 
11997   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
11998   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
11999   verifyFormat("class C {\n"
12000                "  C()\n"
12001                "      : iiiiiiii(nullptr),\n"
12002                "        kkkkkkk(nullptr),\n"
12003                "        mmmmmmm(nullptr),\n"
12004                "        nnnnnnn(nullptr) {}\n"
12005                "};",
12006                getGoogleStyle());
12007 
12008   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12009   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12010   EXPECT_EQ("class C {\n"
12011             "  A() : b(0) {}\n"
12012             "};",
12013             format("class C{A():b(0){}};", NoColumnLimit));
12014   EXPECT_EQ("A()\n"
12015             "    : b(0) {\n"
12016             "}",
12017             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12018 
12019   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12020   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12021       FormatStyle::SFS_None;
12022   EXPECT_EQ("A()\n"
12023             "    : b(0) {\n"
12024             "}",
12025             format("A():b(0){}", DoNotMergeNoColumnLimit));
12026   EXPECT_EQ("A()\n"
12027             "    : b(0) {\n"
12028             "}",
12029             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12030 
12031   verifyFormat("#define A          \\\n"
12032                "  void f() {       \\\n"
12033                "    int i;         \\\n"
12034                "  }",
12035                getLLVMStyleWithColumns(20));
12036   verifyFormat("#define A           \\\n"
12037                "  void f() { int i; }",
12038                getLLVMStyleWithColumns(21));
12039   verifyFormat("#define A            \\\n"
12040                "  void f() {         \\\n"
12041                "    int i;           \\\n"
12042                "  }                  \\\n"
12043                "  int j;",
12044                getLLVMStyleWithColumns(22));
12045   verifyFormat("#define A             \\\n"
12046                "  void f() { int i; } \\\n"
12047                "  int j;",
12048                getLLVMStyleWithColumns(23));
12049 }
12050 
12051 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12052   FormatStyle MergeEmptyOnly = getLLVMStyle();
12053   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12054   verifyFormat("class C {\n"
12055                "  int f() {}\n"
12056                "};",
12057                MergeEmptyOnly);
12058   verifyFormat("class C {\n"
12059                "  int f() {\n"
12060                "    return 42;\n"
12061                "  }\n"
12062                "};",
12063                MergeEmptyOnly);
12064   verifyFormat("int f() {}", MergeEmptyOnly);
12065   verifyFormat("int f() {\n"
12066                "  return 42;\n"
12067                "}",
12068                MergeEmptyOnly);
12069 
12070   // Also verify behavior when BraceWrapping.AfterFunction = true
12071   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12072   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12073   verifyFormat("int f() {}", MergeEmptyOnly);
12074   verifyFormat("class C {\n"
12075                "  int f() {}\n"
12076                "};",
12077                MergeEmptyOnly);
12078 }
12079 
12080 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12081   FormatStyle MergeInlineOnly = getLLVMStyle();
12082   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12083   verifyFormat("class C {\n"
12084                "  int f() { return 42; }\n"
12085                "};",
12086                MergeInlineOnly);
12087   verifyFormat("int f() {\n"
12088                "  return 42;\n"
12089                "}",
12090                MergeInlineOnly);
12091 
12092   // SFS_Inline implies SFS_Empty
12093   verifyFormat("class C {\n"
12094                "  int f() {}\n"
12095                "};",
12096                MergeInlineOnly);
12097   verifyFormat("int f() {}", MergeInlineOnly);
12098 
12099   // Also verify behavior when BraceWrapping.AfterFunction = true
12100   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12101   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12102   verifyFormat("class C {\n"
12103                "  int f() { return 42; }\n"
12104                "};",
12105                MergeInlineOnly);
12106   verifyFormat("int f()\n"
12107                "{\n"
12108                "  return 42;\n"
12109                "}",
12110                MergeInlineOnly);
12111 
12112   // SFS_Inline implies SFS_Empty
12113   verifyFormat("int f() {}", MergeInlineOnly);
12114   verifyFormat("class C {\n"
12115                "  int f() {}\n"
12116                "};",
12117                MergeInlineOnly);
12118 }
12119 
12120 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
12121   FormatStyle MergeInlineOnly = getLLVMStyle();
12122   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
12123       FormatStyle::SFS_InlineOnly;
12124   verifyFormat("class C {\n"
12125                "  int f() { return 42; }\n"
12126                "};",
12127                MergeInlineOnly);
12128   verifyFormat("int f() {\n"
12129                "  return 42;\n"
12130                "}",
12131                MergeInlineOnly);
12132 
12133   // SFS_InlineOnly does not imply SFS_Empty
12134   verifyFormat("class C {\n"
12135                "  int f() {}\n"
12136                "};",
12137                MergeInlineOnly);
12138   verifyFormat("int f() {\n"
12139                "}",
12140                MergeInlineOnly);
12141 
12142   // Also verify behavior when BraceWrapping.AfterFunction = true
12143   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12144   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12145   verifyFormat("class C {\n"
12146                "  int f() { return 42; }\n"
12147                "};",
12148                MergeInlineOnly);
12149   verifyFormat("int f()\n"
12150                "{\n"
12151                "  return 42;\n"
12152                "}",
12153                MergeInlineOnly);
12154 
12155   // SFS_InlineOnly does not imply SFS_Empty
12156   verifyFormat("int f()\n"
12157                "{\n"
12158                "}",
12159                MergeInlineOnly);
12160   verifyFormat("class C {\n"
12161                "  int f() {}\n"
12162                "};",
12163                MergeInlineOnly);
12164 }
12165 
12166 TEST_F(FormatTest, SplitEmptyFunction) {
12167   FormatStyle Style = getLLVMStyleWithColumns(40);
12168   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12169   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12170   Style.BraceWrapping.AfterFunction = true;
12171   Style.BraceWrapping.SplitEmptyFunction = false;
12172 
12173   verifyFormat("int f()\n"
12174                "{}",
12175                Style);
12176   verifyFormat("int f()\n"
12177                "{\n"
12178                "  return 42;\n"
12179                "}",
12180                Style);
12181   verifyFormat("int f()\n"
12182                "{\n"
12183                "  // some comment\n"
12184                "}",
12185                Style);
12186 
12187   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12188   verifyFormat("int f() {}", Style);
12189   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12190                "{}",
12191                Style);
12192   verifyFormat("int f()\n"
12193                "{\n"
12194                "  return 0;\n"
12195                "}",
12196                Style);
12197 
12198   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12199   verifyFormat("class Foo {\n"
12200                "  int f() {}\n"
12201                "};\n",
12202                Style);
12203   verifyFormat("class Foo {\n"
12204                "  int f() { return 0; }\n"
12205                "};\n",
12206                Style);
12207   verifyFormat("class Foo {\n"
12208                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12209                "  {}\n"
12210                "};\n",
12211                Style);
12212   verifyFormat("class Foo {\n"
12213                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12214                "  {\n"
12215                "    return 0;\n"
12216                "  }\n"
12217                "};\n",
12218                Style);
12219 
12220   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12221   verifyFormat("int f() {}", Style);
12222   verifyFormat("int f() { return 0; }", Style);
12223   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12224                "{}",
12225                Style);
12226   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12227                "{\n"
12228                "  return 0;\n"
12229                "}",
12230                Style);
12231 }
12232 
12233 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
12234   FormatStyle Style = getLLVMStyleWithColumns(40);
12235   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12236   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12237   Style.BraceWrapping.AfterFunction = true;
12238   Style.BraceWrapping.SplitEmptyFunction = true;
12239   Style.BraceWrapping.SplitEmptyRecord = false;
12240 
12241   verifyFormat("class C {};", Style);
12242   verifyFormat("struct C {};", Style);
12243   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12244                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12245                "{\n"
12246                "}",
12247                Style);
12248   verifyFormat("class C {\n"
12249                "  C()\n"
12250                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
12251                "        bbbbbbbbbbbbbbbbbbb()\n"
12252                "  {\n"
12253                "  }\n"
12254                "  void\n"
12255                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12256                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
12257                "  {\n"
12258                "  }\n"
12259                "};",
12260                Style);
12261 }
12262 
12263 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12264   FormatStyle Style = getLLVMStyle();
12265   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12266   verifyFormat("#ifdef A\n"
12267                "int f() {}\n"
12268                "#else\n"
12269                "int g() {}\n"
12270                "#endif",
12271                Style);
12272 }
12273 
12274 TEST_F(FormatTest, SplitEmptyClass) {
12275   FormatStyle Style = getLLVMStyle();
12276   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12277   Style.BraceWrapping.AfterClass = true;
12278   Style.BraceWrapping.SplitEmptyRecord = false;
12279 
12280   verifyFormat("class Foo\n"
12281                "{};",
12282                Style);
12283   verifyFormat("/* something */ class Foo\n"
12284                "{};",
12285                Style);
12286   verifyFormat("template <typename X> class Foo\n"
12287                "{};",
12288                Style);
12289   verifyFormat("class Foo\n"
12290                "{\n"
12291                "  Foo();\n"
12292                "};",
12293                Style);
12294   verifyFormat("typedef class Foo\n"
12295                "{\n"
12296                "} Foo_t;",
12297                Style);
12298 
12299   Style.BraceWrapping.SplitEmptyRecord = true;
12300   Style.BraceWrapping.AfterStruct = true;
12301   verifyFormat("class rep\n"
12302                "{\n"
12303                "};",
12304                Style);
12305   verifyFormat("struct rep\n"
12306                "{\n"
12307                "};",
12308                Style);
12309   verifyFormat("template <typename T> class rep\n"
12310                "{\n"
12311                "};",
12312                Style);
12313   verifyFormat("template <typename T> struct rep\n"
12314                "{\n"
12315                "};",
12316                Style);
12317   verifyFormat("class rep\n"
12318                "{\n"
12319                "  int x;\n"
12320                "};",
12321                Style);
12322   verifyFormat("struct rep\n"
12323                "{\n"
12324                "  int x;\n"
12325                "};",
12326                Style);
12327   verifyFormat("template <typename T> class rep\n"
12328                "{\n"
12329                "  int x;\n"
12330                "};",
12331                Style);
12332   verifyFormat("template <typename T> struct rep\n"
12333                "{\n"
12334                "  int x;\n"
12335                "};",
12336                Style);
12337   verifyFormat("template <typename T> class rep // Foo\n"
12338                "{\n"
12339                "  int x;\n"
12340                "};",
12341                Style);
12342   verifyFormat("template <typename T> struct rep // Bar\n"
12343                "{\n"
12344                "  int x;\n"
12345                "};",
12346                Style);
12347 
12348   verifyFormat("template <typename T> class rep<T>\n"
12349                "{\n"
12350                "  int x;\n"
12351                "};",
12352                Style);
12353 
12354   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12355                "{\n"
12356                "  int x;\n"
12357                "};",
12358                Style);
12359   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12360                "{\n"
12361                "};",
12362                Style);
12363 
12364   verifyFormat("#include \"stdint.h\"\n"
12365                "namespace rep {}",
12366                Style);
12367   verifyFormat("#include <stdint.h>\n"
12368                "namespace rep {}",
12369                Style);
12370   verifyFormat("#include <stdint.h>\n"
12371                "namespace rep {}",
12372                "#include <stdint.h>\n"
12373                "namespace rep {\n"
12374                "\n"
12375                "\n"
12376                "}",
12377                Style);
12378 }
12379 
12380 TEST_F(FormatTest, SplitEmptyStruct) {
12381   FormatStyle Style = getLLVMStyle();
12382   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12383   Style.BraceWrapping.AfterStruct = true;
12384   Style.BraceWrapping.SplitEmptyRecord = false;
12385 
12386   verifyFormat("struct Foo\n"
12387                "{};",
12388                Style);
12389   verifyFormat("/* something */ struct Foo\n"
12390                "{};",
12391                Style);
12392   verifyFormat("template <typename X> struct Foo\n"
12393                "{};",
12394                Style);
12395   verifyFormat("struct Foo\n"
12396                "{\n"
12397                "  Foo();\n"
12398                "};",
12399                Style);
12400   verifyFormat("typedef struct Foo\n"
12401                "{\n"
12402                "} Foo_t;",
12403                Style);
12404   // typedef struct Bar {} Bar_t;
12405 }
12406 
12407 TEST_F(FormatTest, SplitEmptyUnion) {
12408   FormatStyle Style = getLLVMStyle();
12409   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12410   Style.BraceWrapping.AfterUnion = true;
12411   Style.BraceWrapping.SplitEmptyRecord = false;
12412 
12413   verifyFormat("union Foo\n"
12414                "{};",
12415                Style);
12416   verifyFormat("/* something */ union Foo\n"
12417                "{};",
12418                Style);
12419   verifyFormat("union Foo\n"
12420                "{\n"
12421                "  A,\n"
12422                "};",
12423                Style);
12424   verifyFormat("typedef union Foo\n"
12425                "{\n"
12426                "} Foo_t;",
12427                Style);
12428 }
12429 
12430 TEST_F(FormatTest, SplitEmptyNamespace) {
12431   FormatStyle Style = getLLVMStyle();
12432   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12433   Style.BraceWrapping.AfterNamespace = true;
12434   Style.BraceWrapping.SplitEmptyNamespace = false;
12435 
12436   verifyFormat("namespace Foo\n"
12437                "{};",
12438                Style);
12439   verifyFormat("/* something */ namespace Foo\n"
12440                "{};",
12441                Style);
12442   verifyFormat("inline namespace Foo\n"
12443                "{};",
12444                Style);
12445   verifyFormat("/* something */ inline namespace Foo\n"
12446                "{};",
12447                Style);
12448   verifyFormat("export namespace Foo\n"
12449                "{};",
12450                Style);
12451   verifyFormat("namespace Foo\n"
12452                "{\n"
12453                "void Bar();\n"
12454                "};",
12455                Style);
12456 }
12457 
12458 TEST_F(FormatTest, NeverMergeShortRecords) {
12459   FormatStyle Style = getLLVMStyle();
12460 
12461   verifyFormat("class Foo {\n"
12462                "  Foo();\n"
12463                "};",
12464                Style);
12465   verifyFormat("typedef class Foo {\n"
12466                "  Foo();\n"
12467                "} Foo_t;",
12468                Style);
12469   verifyFormat("struct Foo {\n"
12470                "  Foo();\n"
12471                "};",
12472                Style);
12473   verifyFormat("typedef struct Foo {\n"
12474                "  Foo();\n"
12475                "} Foo_t;",
12476                Style);
12477   verifyFormat("union Foo {\n"
12478                "  A,\n"
12479                "};",
12480                Style);
12481   verifyFormat("typedef union Foo {\n"
12482                "  A,\n"
12483                "} Foo_t;",
12484                Style);
12485   verifyFormat("namespace Foo {\n"
12486                "void Bar();\n"
12487                "};",
12488                Style);
12489 
12490   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12491   Style.BraceWrapping.AfterClass = true;
12492   Style.BraceWrapping.AfterStruct = true;
12493   Style.BraceWrapping.AfterUnion = true;
12494   Style.BraceWrapping.AfterNamespace = true;
12495   verifyFormat("class Foo\n"
12496                "{\n"
12497                "  Foo();\n"
12498                "};",
12499                Style);
12500   verifyFormat("typedef class Foo\n"
12501                "{\n"
12502                "  Foo();\n"
12503                "} Foo_t;",
12504                Style);
12505   verifyFormat("struct Foo\n"
12506                "{\n"
12507                "  Foo();\n"
12508                "};",
12509                Style);
12510   verifyFormat("typedef struct Foo\n"
12511                "{\n"
12512                "  Foo();\n"
12513                "} Foo_t;",
12514                Style);
12515   verifyFormat("union Foo\n"
12516                "{\n"
12517                "  A,\n"
12518                "};",
12519                Style);
12520   verifyFormat("typedef union Foo\n"
12521                "{\n"
12522                "  A,\n"
12523                "} Foo_t;",
12524                Style);
12525   verifyFormat("namespace Foo\n"
12526                "{\n"
12527                "void Bar();\n"
12528                "};",
12529                Style);
12530 }
12531 
12532 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
12533   // Elaborate type variable declarations.
12534   verifyFormat("struct foo a = {bar};\nint n;");
12535   verifyFormat("class foo a = {bar};\nint n;");
12536   verifyFormat("union foo a = {bar};\nint n;");
12537 
12538   // Elaborate types inside function definitions.
12539   verifyFormat("struct foo f() {}\nint n;");
12540   verifyFormat("class foo f() {}\nint n;");
12541   verifyFormat("union foo f() {}\nint n;");
12542 
12543   // Templates.
12544   verifyFormat("template <class X> void f() {}\nint n;");
12545   verifyFormat("template <struct X> void f() {}\nint n;");
12546   verifyFormat("template <union X> void f() {}\nint n;");
12547 
12548   // Actual definitions...
12549   verifyFormat("struct {\n} n;");
12550   verifyFormat(
12551       "template <template <class T, class Y>, class Z> class X {\n} n;");
12552   verifyFormat("union Z {\n  int n;\n} x;");
12553   verifyFormat("class MACRO Z {\n} n;");
12554   verifyFormat("class MACRO(X) Z {\n} n;");
12555   verifyFormat("class __attribute__(X) Z {\n} n;");
12556   verifyFormat("class __declspec(X) Z {\n} n;");
12557   verifyFormat("class A##B##C {\n} n;");
12558   verifyFormat("class alignas(16) Z {\n} n;");
12559   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
12560   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
12561 
12562   // Redefinition from nested context:
12563   verifyFormat("class A::B::C {\n} n;");
12564 
12565   // Template definitions.
12566   verifyFormat(
12567       "template <typename F>\n"
12568       "Matcher(const Matcher<F> &Other,\n"
12569       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
12570       "                             !is_same<F, T>::value>::type * = 0)\n"
12571       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
12572 
12573   // FIXME: This is still incorrectly handled at the formatter side.
12574   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
12575   verifyFormat("int i = SomeFunction(a<b, a> b);");
12576 
12577   // FIXME:
12578   // This now gets parsed incorrectly as class definition.
12579   // verifyFormat("class A<int> f() {\n}\nint n;");
12580 
12581   // Elaborate types where incorrectly parsing the structural element would
12582   // break the indent.
12583   verifyFormat("if (true)\n"
12584                "  class X x;\n"
12585                "else\n"
12586                "  f();\n");
12587 
12588   // This is simply incomplete. Formatting is not important, but must not crash.
12589   verifyFormat("class A:");
12590 }
12591 
12592 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
12593   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
12594             format("#error Leave     all         white!!!!! space* alone!\n"));
12595   EXPECT_EQ(
12596       "#warning Leave     all         white!!!!! space* alone!\n",
12597       format("#warning Leave     all         white!!!!! space* alone!\n"));
12598   EXPECT_EQ("#error 1", format("  #  error   1"));
12599   EXPECT_EQ("#warning 1", format("  #  warning 1"));
12600 }
12601 
12602 TEST_F(FormatTest, FormatHashIfExpressions) {
12603   verifyFormat("#if AAAA && BBBB");
12604   verifyFormat("#if (AAAA && BBBB)");
12605   verifyFormat("#elif (AAAA && BBBB)");
12606   // FIXME: Come up with a better indentation for #elif.
12607   verifyFormat(
12608       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
12609       "    defined(BBBBBBBB)\n"
12610       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
12611       "    defined(BBBBBBBB)\n"
12612       "#endif",
12613       getLLVMStyleWithColumns(65));
12614 }
12615 
12616 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
12617   FormatStyle AllowsMergedIf = getGoogleStyle();
12618   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
12619       FormatStyle::SIS_WithoutElse;
12620   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
12621   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
12622   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
12623   EXPECT_EQ("if (true) return 42;",
12624             format("if (true)\nreturn 42;", AllowsMergedIf));
12625   FormatStyle ShortMergedIf = AllowsMergedIf;
12626   ShortMergedIf.ColumnLimit = 25;
12627   verifyFormat("#define A \\\n"
12628                "  if (true) return 42;",
12629                ShortMergedIf);
12630   verifyFormat("#define A \\\n"
12631                "  f();    \\\n"
12632                "  if (true)\n"
12633                "#define B",
12634                ShortMergedIf);
12635   verifyFormat("#define A \\\n"
12636                "  f();    \\\n"
12637                "  if (true)\n"
12638                "g();",
12639                ShortMergedIf);
12640   verifyFormat("{\n"
12641                "#ifdef A\n"
12642                "  // Comment\n"
12643                "  if (true) continue;\n"
12644                "#endif\n"
12645                "  // Comment\n"
12646                "  if (true) continue;\n"
12647                "}",
12648                ShortMergedIf);
12649   ShortMergedIf.ColumnLimit = 33;
12650   verifyFormat("#define A \\\n"
12651                "  if constexpr (true) return 42;",
12652                ShortMergedIf);
12653   verifyFormat("#define A \\\n"
12654                "  if CONSTEXPR (true) return 42;",
12655                ShortMergedIf);
12656   ShortMergedIf.ColumnLimit = 29;
12657   verifyFormat("#define A                   \\\n"
12658                "  if (aaaaaaaaaa) return 1; \\\n"
12659                "  return 2;",
12660                ShortMergedIf);
12661   ShortMergedIf.ColumnLimit = 28;
12662   verifyFormat("#define A         \\\n"
12663                "  if (aaaaaaaaaa) \\\n"
12664                "    return 1;     \\\n"
12665                "  return 2;",
12666                ShortMergedIf);
12667   verifyFormat("#define A                \\\n"
12668                "  if constexpr (aaaaaaa) \\\n"
12669                "    return 1;            \\\n"
12670                "  return 2;",
12671                ShortMergedIf);
12672   verifyFormat("#define A                \\\n"
12673                "  if CONSTEXPR (aaaaaaa) \\\n"
12674                "    return 1;            \\\n"
12675                "  return 2;",
12676                ShortMergedIf);
12677 }
12678 
12679 TEST_F(FormatTest, FormatStarDependingOnContext) {
12680   verifyFormat("void f(int *a);");
12681   verifyFormat("void f() { f(fint * b); }");
12682   verifyFormat("class A {\n  void f(int *a);\n};");
12683   verifyFormat("class A {\n  int *a;\n};");
12684   verifyFormat("namespace a {\n"
12685                "namespace b {\n"
12686                "class A {\n"
12687                "  void f() {}\n"
12688                "  int *a;\n"
12689                "};\n"
12690                "} // namespace b\n"
12691                "} // namespace a");
12692 }
12693 
12694 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
12695   verifyFormat("while");
12696   verifyFormat("operator");
12697 }
12698 
12699 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
12700   // This code would be painfully slow to format if we didn't skip it.
12701   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
12702                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12703                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12704                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12705                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12706                    "A(1, 1)\n"
12707                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
12708                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12709                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12710                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12711                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12712                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12713                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12714                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12715                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12716                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
12717   // Deeply nested part is untouched, rest is formatted.
12718   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
12719             format(std::string("int    i;\n") + Code + "int    j;\n",
12720                    getLLVMStyle(), SC_ExpectIncomplete));
12721 }
12722 
12723 //===----------------------------------------------------------------------===//
12724 // Objective-C tests.
12725 //===----------------------------------------------------------------------===//
12726 
12727 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
12728   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
12729   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
12730             format("-(NSUInteger)indexOfObject:(id)anObject;"));
12731   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
12732   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
12733   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
12734             format("-(NSInteger)Method3:(id)anObject;"));
12735   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
12736             format("-(NSInteger)Method4:(id)anObject;"));
12737   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
12738             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
12739   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
12740             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
12741   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12742             "forAllCells:(BOOL)flag;",
12743             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12744                    "forAllCells:(BOOL)flag;"));
12745 
12746   // Very long objectiveC method declaration.
12747   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
12748                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
12749   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
12750                "                    inRange:(NSRange)range\n"
12751                "                   outRange:(NSRange)out_range\n"
12752                "                  outRange1:(NSRange)out_range1\n"
12753                "                  outRange2:(NSRange)out_range2\n"
12754                "                  outRange3:(NSRange)out_range3\n"
12755                "                  outRange4:(NSRange)out_range4\n"
12756                "                  outRange5:(NSRange)out_range5\n"
12757                "                  outRange6:(NSRange)out_range6\n"
12758                "                  outRange7:(NSRange)out_range7\n"
12759                "                  outRange8:(NSRange)out_range8\n"
12760                "                  outRange9:(NSRange)out_range9;");
12761 
12762   // When the function name has to be wrapped.
12763   FormatStyle Style = getLLVMStyle();
12764   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
12765   // and always indents instead.
12766   Style.IndentWrappedFunctionNames = false;
12767   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12768                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
12769                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
12770                "}",
12771                Style);
12772   Style.IndentWrappedFunctionNames = true;
12773   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12774                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
12775                "               anotherName:(NSString)dddddddddddddd {\n"
12776                "}",
12777                Style);
12778 
12779   verifyFormat("- (int)sum:(vector<int>)numbers;");
12780   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
12781   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
12782   // protocol lists (but not for template classes):
12783   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
12784 
12785   verifyFormat("- (int (*)())foo:(int (*)())f;");
12786   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
12787 
12788   // If there's no return type (very rare in practice!), LLVM and Google style
12789   // agree.
12790   verifyFormat("- foo;");
12791   verifyFormat("- foo:(int)f;");
12792   verifyGoogleFormat("- foo:(int)foo;");
12793 }
12794 
12795 TEST_F(FormatTest, BreaksStringLiterals) {
12796   EXPECT_EQ("\"some text \"\n"
12797             "\"other\";",
12798             format("\"some text other\";", getLLVMStyleWithColumns(12)));
12799   EXPECT_EQ("\"some text \"\n"
12800             "\"other\";",
12801             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
12802   EXPECT_EQ(
12803       "#define A  \\\n"
12804       "  \"some \"  \\\n"
12805       "  \"text \"  \\\n"
12806       "  \"other\";",
12807       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
12808   EXPECT_EQ(
12809       "#define A  \\\n"
12810       "  \"so \"    \\\n"
12811       "  \"text \"  \\\n"
12812       "  \"other\";",
12813       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
12814 
12815   EXPECT_EQ("\"some text\"",
12816             format("\"some text\"", getLLVMStyleWithColumns(1)));
12817   EXPECT_EQ("\"some text\"",
12818             format("\"some text\"", getLLVMStyleWithColumns(11)));
12819   EXPECT_EQ("\"some \"\n"
12820             "\"text\"",
12821             format("\"some text\"", getLLVMStyleWithColumns(10)));
12822   EXPECT_EQ("\"some \"\n"
12823             "\"text\"",
12824             format("\"some text\"", getLLVMStyleWithColumns(7)));
12825   EXPECT_EQ("\"some\"\n"
12826             "\" tex\"\n"
12827             "\"t\"",
12828             format("\"some text\"", getLLVMStyleWithColumns(6)));
12829   EXPECT_EQ("\"some\"\n"
12830             "\" tex\"\n"
12831             "\" and\"",
12832             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
12833   EXPECT_EQ("\"some\"\n"
12834             "\"/tex\"\n"
12835             "\"/and\"",
12836             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
12837 
12838   EXPECT_EQ("variable =\n"
12839             "    \"long string \"\n"
12840             "    \"literal\";",
12841             format("variable = \"long string literal\";",
12842                    getLLVMStyleWithColumns(20)));
12843 
12844   EXPECT_EQ("variable = f(\n"
12845             "    \"long string \"\n"
12846             "    \"literal\",\n"
12847             "    short,\n"
12848             "    loooooooooooooooooooong);",
12849             format("variable = f(\"long string literal\", short, "
12850                    "loooooooooooooooooooong);",
12851                    getLLVMStyleWithColumns(20)));
12852 
12853   EXPECT_EQ(
12854       "f(g(\"long string \"\n"
12855       "    \"literal\"),\n"
12856       "  b);",
12857       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
12858   EXPECT_EQ("f(g(\"long string \"\n"
12859             "    \"literal\",\n"
12860             "    a),\n"
12861             "  b);",
12862             format("f(g(\"long string literal\", a), b);",
12863                    getLLVMStyleWithColumns(20)));
12864   EXPECT_EQ(
12865       "f(\"one two\".split(\n"
12866       "    variable));",
12867       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
12868   EXPECT_EQ("f(\"one two three four five six \"\n"
12869             "  \"seven\".split(\n"
12870             "      really_looooong_variable));",
12871             format("f(\"one two three four five six seven\"."
12872                    "split(really_looooong_variable));",
12873                    getLLVMStyleWithColumns(33)));
12874 
12875   EXPECT_EQ("f(\"some \"\n"
12876             "  \"text\",\n"
12877             "  other);",
12878             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
12879 
12880   // Only break as a last resort.
12881   verifyFormat(
12882       "aaaaaaaaaaaaaaaaaaaa(\n"
12883       "    aaaaaaaaaaaaaaaaaaaa,\n"
12884       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
12885 
12886   EXPECT_EQ("\"splitmea\"\n"
12887             "\"trandomp\"\n"
12888             "\"oint\"",
12889             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
12890 
12891   EXPECT_EQ("\"split/\"\n"
12892             "\"pathat/\"\n"
12893             "\"slashes\"",
12894             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
12895 
12896   EXPECT_EQ("\"split/\"\n"
12897             "\"pathat/\"\n"
12898             "\"slashes\"",
12899             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
12900   EXPECT_EQ("\"split at \"\n"
12901             "\"spaces/at/\"\n"
12902             "\"slashes.at.any$\"\n"
12903             "\"non-alphanumeric%\"\n"
12904             "\"1111111111characte\"\n"
12905             "\"rs\"",
12906             format("\"split at "
12907                    "spaces/at/"
12908                    "slashes.at."
12909                    "any$non-"
12910                    "alphanumeric%"
12911                    "1111111111characte"
12912                    "rs\"",
12913                    getLLVMStyleWithColumns(20)));
12914 
12915   // Verify that splitting the strings understands
12916   // Style::AlwaysBreakBeforeMultilineStrings.
12917   EXPECT_EQ("aaaaaaaaaaaa(\n"
12918             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
12919             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
12920             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
12921                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
12922                    "aaaaaaaaaaaaaaaaaaaaaa\");",
12923                    getGoogleStyle()));
12924   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12925             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
12926             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
12927                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
12928                    "aaaaaaaaaaaaaaaaaaaaaa\";",
12929                    getGoogleStyle()));
12930   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12931             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
12932             format("llvm::outs() << "
12933                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
12934                    "aaaaaaaaaaaaaaaaaaa\";"));
12935   EXPECT_EQ("ffff(\n"
12936             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12937             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
12938             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
12939                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
12940                    getGoogleStyle()));
12941 
12942   FormatStyle Style = getLLVMStyleWithColumns(12);
12943   Style.BreakStringLiterals = false;
12944   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
12945 
12946   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
12947   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
12948   EXPECT_EQ("#define A \\\n"
12949             "  \"some \" \\\n"
12950             "  \"text \" \\\n"
12951             "  \"other\";",
12952             format("#define A \"some text other\";", AlignLeft));
12953 }
12954 
12955 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
12956   EXPECT_EQ("C a = \"some more \"\n"
12957             "      \"text\";",
12958             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
12959 }
12960 
12961 TEST_F(FormatTest, FullyRemoveEmptyLines) {
12962   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
12963   NoEmptyLines.MaxEmptyLinesToKeep = 0;
12964   EXPECT_EQ("int i = a(b());",
12965             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
12966 }
12967 
12968 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
12969   EXPECT_EQ(
12970       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12971       "(\n"
12972       "    \"x\t\");",
12973       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12974              "aaaaaaa("
12975              "\"x\t\");"));
12976 }
12977 
12978 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
12979   EXPECT_EQ(
12980       "u8\"utf8 string \"\n"
12981       "u8\"literal\";",
12982       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
12983   EXPECT_EQ(
12984       "u\"utf16 string \"\n"
12985       "u\"literal\";",
12986       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
12987   EXPECT_EQ(
12988       "U\"utf32 string \"\n"
12989       "U\"literal\";",
12990       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
12991   EXPECT_EQ("L\"wide string \"\n"
12992             "L\"literal\";",
12993             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
12994   EXPECT_EQ("@\"NSString \"\n"
12995             "@\"literal\";",
12996             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
12997   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
12998 
12999   // This input makes clang-format try to split the incomplete unicode escape
13000   // sequence, which used to lead to a crasher.
13001   verifyNoCrash(
13002       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13003       getLLVMStyleWithColumns(60));
13004 }
13005 
13006 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13007   FormatStyle Style = getGoogleStyleWithColumns(15);
13008   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13009   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13010   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13011   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13012   EXPECT_EQ("u8R\"x(raw literal)x\";",
13013             format("u8R\"x(raw literal)x\";", Style));
13014 }
13015 
13016 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13017   FormatStyle Style = getLLVMStyleWithColumns(20);
13018   EXPECT_EQ(
13019       "_T(\"aaaaaaaaaaaaaa\")\n"
13020       "_T(\"aaaaaaaaaaaaaa\")\n"
13021       "_T(\"aaaaaaaaaaaa\")",
13022       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13023   EXPECT_EQ("f(x,\n"
13024             "  _T(\"aaaaaaaaaaaa\")\n"
13025             "  _T(\"aaa\"),\n"
13026             "  z);",
13027             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13028 
13029   // FIXME: Handle embedded spaces in one iteration.
13030   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13031   //            "_T(\"aaaaaaaaaaaaa\")\n"
13032   //            "_T(\"aaaaaaaaaaaaa\")\n"
13033   //            "_T(\"a\")",
13034   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13035   //                   getLLVMStyleWithColumns(20)));
13036   EXPECT_EQ(
13037       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13038       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13039   EXPECT_EQ("f(\n"
13040             "#if !TEST\n"
13041             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13042             "#endif\n"
13043             ");",
13044             format("f(\n"
13045                    "#if !TEST\n"
13046                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13047                    "#endif\n"
13048                    ");"));
13049   EXPECT_EQ("f(\n"
13050             "\n"
13051             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13052             format("f(\n"
13053                    "\n"
13054                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13055   // Regression test for accessing tokens past the end of a vector in the
13056   // TokenLexer.
13057   verifyNoCrash(R"(_T(
13058 "
13059 )
13060 )");
13061 }
13062 
13063 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13064   // In a function call with two operands, the second can be broken with no line
13065   // break before it.
13066   EXPECT_EQ(
13067       "func(a, \"long long \"\n"
13068       "        \"long long\");",
13069       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13070   // In a function call with three operands, the second must be broken with a
13071   // line break before it.
13072   EXPECT_EQ("func(a,\n"
13073             "     \"long long long \"\n"
13074             "     \"long\",\n"
13075             "     c);",
13076             format("func(a, \"long long long long\", c);",
13077                    getLLVMStyleWithColumns(24)));
13078   // In a function call with three operands, the third must be broken with a
13079   // line break before it.
13080   EXPECT_EQ("func(a, b,\n"
13081             "     \"long long long \"\n"
13082             "     \"long\");",
13083             format("func(a, b, \"long long long long\");",
13084                    getLLVMStyleWithColumns(24)));
13085   // In a function call with three operands, both the second and the third must
13086   // be broken with a line break before them.
13087   EXPECT_EQ("func(a,\n"
13088             "     \"long long long \"\n"
13089             "     \"long\",\n"
13090             "     \"long long long \"\n"
13091             "     \"long\");",
13092             format("func(a, \"long long long long\", \"long long long long\");",
13093                    getLLVMStyleWithColumns(24)));
13094   // In a chain of << with two operands, the second can be broken with no line
13095   // break before it.
13096   EXPECT_EQ("a << \"line line \"\n"
13097             "     \"line\";",
13098             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13099   // In a chain of << with three operands, the second can be broken with no line
13100   // break before it.
13101   EXPECT_EQ(
13102       "abcde << \"line \"\n"
13103       "         \"line line\"\n"
13104       "      << c;",
13105       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13106   // In a chain of << with three operands, the third must be broken with a line
13107   // break before it.
13108   EXPECT_EQ(
13109       "a << b\n"
13110       "  << \"line line \"\n"
13111       "     \"line\";",
13112       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13113   // In a chain of << with three operands, the second can be broken with no line
13114   // break before it and the third must be broken with a line break before it.
13115   EXPECT_EQ("abcd << \"line line \"\n"
13116             "        \"line\"\n"
13117             "     << \"line line \"\n"
13118             "        \"line\";",
13119             format("abcd << \"line line line\" << \"line line line\";",
13120                    getLLVMStyleWithColumns(20)));
13121   // In a chain of binary operators with two operands, the second can be broken
13122   // with no line break before it.
13123   EXPECT_EQ(
13124       "abcd + \"line line \"\n"
13125       "       \"line line\";",
13126       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
13127   // In a chain of binary operators with three operands, the second must be
13128   // broken with a line break before it.
13129   EXPECT_EQ("abcd +\n"
13130             "    \"line line \"\n"
13131             "    \"line line\" +\n"
13132             "    e;",
13133             format("abcd + \"line line line line\" + e;",
13134                    getLLVMStyleWithColumns(20)));
13135   // In a function call with two operands, with AlignAfterOpenBracket enabled,
13136   // the first must be broken with a line break before it.
13137   FormatStyle Style = getLLVMStyleWithColumns(25);
13138   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13139   EXPECT_EQ("someFunction(\n"
13140             "    \"long long long \"\n"
13141             "    \"long\",\n"
13142             "    a);",
13143             format("someFunction(\"long long long long\", a);", Style));
13144 }
13145 
13146 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
13147   EXPECT_EQ(
13148       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13149       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13150       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13151       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13152              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
13153              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
13154 }
13155 
13156 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
13157   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
13158             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
13159   EXPECT_EQ("fffffffffff(g(R\"x(\n"
13160             "multiline raw string literal xxxxxxxxxxxxxx\n"
13161             ")x\",\n"
13162             "              a),\n"
13163             "            b);",
13164             format("fffffffffff(g(R\"x(\n"
13165                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13166                    ")x\", a), b);",
13167                    getGoogleStyleWithColumns(20)));
13168   EXPECT_EQ("fffffffffff(\n"
13169             "    g(R\"x(qqq\n"
13170             "multiline raw string literal xxxxxxxxxxxxxx\n"
13171             ")x\",\n"
13172             "      a),\n"
13173             "    b);",
13174             format("fffffffffff(g(R\"x(qqq\n"
13175                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13176                    ")x\", a), b);",
13177                    getGoogleStyleWithColumns(20)));
13178 
13179   EXPECT_EQ("fffffffffff(R\"x(\n"
13180             "multiline raw string literal xxxxxxxxxxxxxx\n"
13181             ")x\");",
13182             format("fffffffffff(R\"x(\n"
13183                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13184                    ")x\");",
13185                    getGoogleStyleWithColumns(20)));
13186   EXPECT_EQ("fffffffffff(R\"x(\n"
13187             "multiline raw string literal xxxxxxxxxxxxxx\n"
13188             ")x\" + bbbbbb);",
13189             format("fffffffffff(R\"x(\n"
13190                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13191                    ")x\" +   bbbbbb);",
13192                    getGoogleStyleWithColumns(20)));
13193   EXPECT_EQ("fffffffffff(\n"
13194             "    R\"x(\n"
13195             "multiline raw string literal xxxxxxxxxxxxxx\n"
13196             ")x\" +\n"
13197             "    bbbbbb);",
13198             format("fffffffffff(\n"
13199                    " R\"x(\n"
13200                    "multiline raw string literal xxxxxxxxxxxxxx\n"
13201                    ")x\" + bbbbbb);",
13202                    getGoogleStyleWithColumns(20)));
13203   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
13204             format("fffffffffff(\n"
13205                    " R\"(single line raw string)\" + bbbbbb);"));
13206 }
13207 
13208 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
13209   verifyFormat("string a = \"unterminated;");
13210   EXPECT_EQ("function(\"unterminated,\n"
13211             "         OtherParameter);",
13212             format("function(  \"unterminated,\n"
13213                    "    OtherParameter);"));
13214 }
13215 
13216 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
13217   FormatStyle Style = getLLVMStyle();
13218   Style.Standard = FormatStyle::LS_Cpp03;
13219   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
13220             format("#define x(_a) printf(\"foo\"_a);", Style));
13221 }
13222 
13223 TEST_F(FormatTest, CppLexVersion) {
13224   FormatStyle Style = getLLVMStyle();
13225   // Formatting of x * y differs if x is a type.
13226   verifyFormat("void foo() { MACRO(a * b); }", Style);
13227   verifyFormat("void foo() { MACRO(int *b); }", Style);
13228 
13229   // LLVM style uses latest lexer.
13230   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13231   Style.Standard = FormatStyle::LS_Cpp17;
13232   // But in c++17, char8_t isn't a keyword.
13233   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13234 }
13235 
13236 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13237 
13238 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13239   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13240             "             \"ddeeefff\");",
13241             format("someFunction(\"aaabbbcccdddeeefff\");",
13242                    getLLVMStyleWithColumns(25)));
13243   EXPECT_EQ("someFunction1234567890(\n"
13244             "    \"aaabbbcccdddeeefff\");",
13245             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13246                    getLLVMStyleWithColumns(26)));
13247   EXPECT_EQ("someFunction1234567890(\n"
13248             "    \"aaabbbcccdddeeeff\"\n"
13249             "    \"f\");",
13250             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13251                    getLLVMStyleWithColumns(25)));
13252   EXPECT_EQ("someFunction1234567890(\n"
13253             "    \"aaabbbcccdddeeeff\"\n"
13254             "    \"f\");",
13255             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13256                    getLLVMStyleWithColumns(24)));
13257   EXPECT_EQ("someFunction(\n"
13258             "    \"aaabbbcc ddde \"\n"
13259             "    \"efff\");",
13260             format("someFunction(\"aaabbbcc ddde efff\");",
13261                    getLLVMStyleWithColumns(25)));
13262   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13263             "             \"ddeeefff\");",
13264             format("someFunction(\"aaabbbccc ddeeefff\");",
13265                    getLLVMStyleWithColumns(25)));
13266   EXPECT_EQ("someFunction1234567890(\n"
13267             "    \"aaabb \"\n"
13268             "    \"cccdddeeefff\");",
13269             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13270                    getLLVMStyleWithColumns(25)));
13271   EXPECT_EQ("#define A          \\\n"
13272             "  string s =       \\\n"
13273             "      \"123456789\"  \\\n"
13274             "      \"0\";         \\\n"
13275             "  int i;",
13276             format("#define A string s = \"1234567890\"; int i;",
13277                    getLLVMStyleWithColumns(20)));
13278   EXPECT_EQ("someFunction(\n"
13279             "    \"aaabbbcc \"\n"
13280             "    \"dddeeefff\");",
13281             format("someFunction(\"aaabbbcc dddeeefff\");",
13282                    getLLVMStyleWithColumns(25)));
13283 }
13284 
13285 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13286   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13287   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13288   EXPECT_EQ("\"test\"\n"
13289             "\"\\n\"",
13290             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13291   EXPECT_EQ("\"tes\\\\\"\n"
13292             "\"n\"",
13293             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
13294   EXPECT_EQ("\"\\\\\\\\\"\n"
13295             "\"\\n\"",
13296             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
13297   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
13298   EXPECT_EQ("\"\\uff01\"\n"
13299             "\"test\"",
13300             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
13301   EXPECT_EQ("\"\\Uff01ff02\"",
13302             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
13303   EXPECT_EQ("\"\\x000000000001\"\n"
13304             "\"next\"",
13305             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
13306   EXPECT_EQ("\"\\x000000000001next\"",
13307             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
13308   EXPECT_EQ("\"\\x000000000001\"",
13309             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
13310   EXPECT_EQ("\"test\"\n"
13311             "\"\\000000\"\n"
13312             "\"000001\"",
13313             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
13314   EXPECT_EQ("\"test\\000\"\n"
13315             "\"00000000\"\n"
13316             "\"1\"",
13317             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
13318 }
13319 
13320 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
13321   verifyFormat("void f() {\n"
13322                "  return g() {}\n"
13323                "  void h() {}");
13324   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
13325                "g();\n"
13326                "}");
13327 }
13328 
13329 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
13330   verifyFormat(
13331       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
13332 }
13333 
13334 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
13335   verifyFormat("class X {\n"
13336                "  void f() {\n"
13337                "  }\n"
13338                "};",
13339                getLLVMStyleWithColumns(12));
13340 }
13341 
13342 TEST_F(FormatTest, ConfigurableIndentWidth) {
13343   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
13344   EightIndent.IndentWidth = 8;
13345   EightIndent.ContinuationIndentWidth = 8;
13346   verifyFormat("void f() {\n"
13347                "        someFunction();\n"
13348                "        if (true) {\n"
13349                "                f();\n"
13350                "        }\n"
13351                "}",
13352                EightIndent);
13353   verifyFormat("class X {\n"
13354                "        void f() {\n"
13355                "        }\n"
13356                "};",
13357                EightIndent);
13358   verifyFormat("int x[] = {\n"
13359                "        call(),\n"
13360                "        call()};",
13361                EightIndent);
13362 }
13363 
13364 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
13365   verifyFormat("double\n"
13366                "f();",
13367                getLLVMStyleWithColumns(8));
13368 }
13369 
13370 TEST_F(FormatTest, ConfigurableUseOfTab) {
13371   FormatStyle Tab = getLLVMStyleWithColumns(42);
13372   Tab.IndentWidth = 8;
13373   Tab.UseTab = FormatStyle::UT_Always;
13374   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13375 
13376   EXPECT_EQ("if (aaaaaaaa && // q\n"
13377             "    bb)\t\t// w\n"
13378             "\t;",
13379             format("if (aaaaaaaa &&// q\n"
13380                    "bb)// w\n"
13381                    ";",
13382                    Tab));
13383   EXPECT_EQ("if (aaa && bbb) // w\n"
13384             "\t;",
13385             format("if(aaa&&bbb)// w\n"
13386                    ";",
13387                    Tab));
13388 
13389   verifyFormat("class X {\n"
13390                "\tvoid f() {\n"
13391                "\t\tsomeFunction(parameter1,\n"
13392                "\t\t\t     parameter2);\n"
13393                "\t}\n"
13394                "};",
13395                Tab);
13396   verifyFormat("#define A                        \\\n"
13397                "\tvoid f() {               \\\n"
13398                "\t\tsomeFunction(    \\\n"
13399                "\t\t    parameter1,  \\\n"
13400                "\t\t    parameter2); \\\n"
13401                "\t}",
13402                Tab);
13403   verifyFormat("int a;\t      // x\n"
13404                "int bbbbbbbb; // x\n",
13405                Tab);
13406 
13407   Tab.TabWidth = 4;
13408   Tab.IndentWidth = 8;
13409   verifyFormat("class TabWidth4Indent8 {\n"
13410                "\t\tvoid f() {\n"
13411                "\t\t\t\tsomeFunction(parameter1,\n"
13412                "\t\t\t\t\t\t\t parameter2);\n"
13413                "\t\t}\n"
13414                "};",
13415                Tab);
13416 
13417   Tab.TabWidth = 4;
13418   Tab.IndentWidth = 4;
13419   verifyFormat("class TabWidth4Indent4 {\n"
13420                "\tvoid f() {\n"
13421                "\t\tsomeFunction(parameter1,\n"
13422                "\t\t\t\t\t parameter2);\n"
13423                "\t}\n"
13424                "};",
13425                Tab);
13426 
13427   Tab.TabWidth = 8;
13428   Tab.IndentWidth = 4;
13429   verifyFormat("class TabWidth8Indent4 {\n"
13430                "    void f() {\n"
13431                "\tsomeFunction(parameter1,\n"
13432                "\t\t     parameter2);\n"
13433                "    }\n"
13434                "};",
13435                Tab);
13436 
13437   Tab.TabWidth = 8;
13438   Tab.IndentWidth = 8;
13439   EXPECT_EQ("/*\n"
13440             "\t      a\t\tcomment\n"
13441             "\t      in multiple lines\n"
13442             "       */",
13443             format("   /*\t \t \n"
13444                    " \t \t a\t\tcomment\t \t\n"
13445                    " \t \t in multiple lines\t\n"
13446                    " \t  */",
13447                    Tab));
13448 
13449   Tab.UseTab = FormatStyle::UT_ForIndentation;
13450   verifyFormat("{\n"
13451                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13452                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13453                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13454                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13455                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13456                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13457                "};",
13458                Tab);
13459   verifyFormat("enum AA {\n"
13460                "\ta1, // Force multiple lines\n"
13461                "\ta2,\n"
13462                "\ta3\n"
13463                "};",
13464                Tab);
13465   EXPECT_EQ("if (aaaaaaaa && // q\n"
13466             "    bb)         // w\n"
13467             "\t;",
13468             format("if (aaaaaaaa &&// q\n"
13469                    "bb)// w\n"
13470                    ";",
13471                    Tab));
13472   verifyFormat("class X {\n"
13473                "\tvoid f() {\n"
13474                "\t\tsomeFunction(parameter1,\n"
13475                "\t\t             parameter2);\n"
13476                "\t}\n"
13477                "};",
13478                Tab);
13479   verifyFormat("{\n"
13480                "\tQ(\n"
13481                "\t    {\n"
13482                "\t\t    int a;\n"
13483                "\t\t    someFunction(aaaaaaaa,\n"
13484                "\t\t                 bbbbbbb);\n"
13485                "\t    },\n"
13486                "\t    p);\n"
13487                "}",
13488                Tab);
13489   EXPECT_EQ("{\n"
13490             "\t/* aaaa\n"
13491             "\t   bbbb */\n"
13492             "}",
13493             format("{\n"
13494                    "/* aaaa\n"
13495                    "   bbbb */\n"
13496                    "}",
13497                    Tab));
13498   EXPECT_EQ("{\n"
13499             "\t/*\n"
13500             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13501             "\t  bbbbbbbbbbbbb\n"
13502             "\t*/\n"
13503             "}",
13504             format("{\n"
13505                    "/*\n"
13506                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13507                    "*/\n"
13508                    "}",
13509                    Tab));
13510   EXPECT_EQ("{\n"
13511             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13512             "\t// bbbbbbbbbbbbb\n"
13513             "}",
13514             format("{\n"
13515                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13516                    "}",
13517                    Tab));
13518   EXPECT_EQ("{\n"
13519             "\t/*\n"
13520             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13521             "\t  bbbbbbbbbbbbb\n"
13522             "\t*/\n"
13523             "}",
13524             format("{\n"
13525                    "\t/*\n"
13526                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13527                    "\t*/\n"
13528                    "}",
13529                    Tab));
13530   EXPECT_EQ("{\n"
13531             "\t/*\n"
13532             "\n"
13533             "\t*/\n"
13534             "}",
13535             format("{\n"
13536                    "\t/*\n"
13537                    "\n"
13538                    "\t*/\n"
13539                    "}",
13540                    Tab));
13541   EXPECT_EQ("{\n"
13542             "\t/*\n"
13543             " asdf\n"
13544             "\t*/\n"
13545             "}",
13546             format("{\n"
13547                    "\t/*\n"
13548                    " asdf\n"
13549                    "\t*/\n"
13550                    "}",
13551                    Tab));
13552 
13553   verifyFormat("void f() {\n"
13554                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
13555                "\t            : bbbbbbbbbbbbbbbbbb\n"
13556                "}",
13557                Tab);
13558   FormatStyle TabNoBreak = Tab;
13559   TabNoBreak.BreakBeforeTernaryOperators = false;
13560   verifyFormat("void f() {\n"
13561                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
13562                "\t              bbbbbbbbbbbbbbbbbb\n"
13563                "}",
13564                TabNoBreak);
13565   verifyFormat("void f() {\n"
13566                "\treturn true ?\n"
13567                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
13568                "\t           bbbbbbbbbbbbbbbbbbbb\n"
13569                "}",
13570                TabNoBreak);
13571 
13572   Tab.UseTab = FormatStyle::UT_Never;
13573   EXPECT_EQ("/*\n"
13574             "              a\t\tcomment\n"
13575             "              in multiple lines\n"
13576             "       */",
13577             format("   /*\t \t \n"
13578                    " \t \t a\t\tcomment\t \t\n"
13579                    " \t \t in multiple lines\t\n"
13580                    " \t  */",
13581                    Tab));
13582   EXPECT_EQ("/* some\n"
13583             "   comment */",
13584             format(" \t \t /* some\n"
13585                    " \t \t    comment */",
13586                    Tab));
13587   EXPECT_EQ("int a; /* some\n"
13588             "   comment */",
13589             format(" \t \t int a; /* some\n"
13590                    " \t \t    comment */",
13591                    Tab));
13592 
13593   EXPECT_EQ("int a; /* some\n"
13594             "comment */",
13595             format(" \t \t int\ta; /* some\n"
13596                    " \t \t    comment */",
13597                    Tab));
13598   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13599             "    comment */",
13600             format(" \t \t f(\"\t\t\"); /* some\n"
13601                    " \t \t    comment */",
13602                    Tab));
13603   EXPECT_EQ("{\n"
13604             "        /*\n"
13605             "         * Comment\n"
13606             "         */\n"
13607             "        int i;\n"
13608             "}",
13609             format("{\n"
13610                    "\t/*\n"
13611                    "\t * Comment\n"
13612                    "\t */\n"
13613                    "\t int i;\n"
13614                    "}",
13615                    Tab));
13616 
13617   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13618   Tab.TabWidth = 8;
13619   Tab.IndentWidth = 8;
13620   EXPECT_EQ("if (aaaaaaaa && // q\n"
13621             "    bb)         // w\n"
13622             "\t;",
13623             format("if (aaaaaaaa &&// q\n"
13624                    "bb)// w\n"
13625                    ";",
13626                    Tab));
13627   EXPECT_EQ("if (aaa && bbb) // w\n"
13628             "\t;",
13629             format("if(aaa&&bbb)// w\n"
13630                    ";",
13631                    Tab));
13632   verifyFormat("class X {\n"
13633                "\tvoid f() {\n"
13634                "\t\tsomeFunction(parameter1,\n"
13635                "\t\t\t     parameter2);\n"
13636                "\t}\n"
13637                "};",
13638                Tab);
13639   verifyFormat("#define A                        \\\n"
13640                "\tvoid f() {               \\\n"
13641                "\t\tsomeFunction(    \\\n"
13642                "\t\t    parameter1,  \\\n"
13643                "\t\t    parameter2); \\\n"
13644                "\t}",
13645                Tab);
13646   Tab.TabWidth = 4;
13647   Tab.IndentWidth = 8;
13648   verifyFormat("class TabWidth4Indent8 {\n"
13649                "\t\tvoid f() {\n"
13650                "\t\t\t\tsomeFunction(parameter1,\n"
13651                "\t\t\t\t\t\t\t parameter2);\n"
13652                "\t\t}\n"
13653                "};",
13654                Tab);
13655   Tab.TabWidth = 4;
13656   Tab.IndentWidth = 4;
13657   verifyFormat("class TabWidth4Indent4 {\n"
13658                "\tvoid f() {\n"
13659                "\t\tsomeFunction(parameter1,\n"
13660                "\t\t\t\t\t parameter2);\n"
13661                "\t}\n"
13662                "};",
13663                Tab);
13664   Tab.TabWidth = 8;
13665   Tab.IndentWidth = 4;
13666   verifyFormat("class TabWidth8Indent4 {\n"
13667                "    void f() {\n"
13668                "\tsomeFunction(parameter1,\n"
13669                "\t\t     parameter2);\n"
13670                "    }\n"
13671                "};",
13672                Tab);
13673   Tab.TabWidth = 8;
13674   Tab.IndentWidth = 8;
13675   EXPECT_EQ("/*\n"
13676             "\t      a\t\tcomment\n"
13677             "\t      in multiple lines\n"
13678             "       */",
13679             format("   /*\t \t \n"
13680                    " \t \t a\t\tcomment\t \t\n"
13681                    " \t \t in multiple lines\t\n"
13682                    " \t  */",
13683                    Tab));
13684   verifyFormat("{\n"
13685                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13686                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13687                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13688                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13689                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13690                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13691                "};",
13692                Tab);
13693   verifyFormat("enum AA {\n"
13694                "\ta1, // Force multiple lines\n"
13695                "\ta2,\n"
13696                "\ta3\n"
13697                "};",
13698                Tab);
13699   EXPECT_EQ("if (aaaaaaaa && // q\n"
13700             "    bb)         // w\n"
13701             "\t;",
13702             format("if (aaaaaaaa &&// q\n"
13703                    "bb)// w\n"
13704                    ";",
13705                    Tab));
13706   verifyFormat("class X {\n"
13707                "\tvoid f() {\n"
13708                "\t\tsomeFunction(parameter1,\n"
13709                "\t\t\t     parameter2);\n"
13710                "\t}\n"
13711                "};",
13712                Tab);
13713   verifyFormat("{\n"
13714                "\tQ(\n"
13715                "\t    {\n"
13716                "\t\t    int a;\n"
13717                "\t\t    someFunction(aaaaaaaa,\n"
13718                "\t\t\t\t bbbbbbb);\n"
13719                "\t    },\n"
13720                "\t    p);\n"
13721                "}",
13722                Tab);
13723   EXPECT_EQ("{\n"
13724             "\t/* aaaa\n"
13725             "\t   bbbb */\n"
13726             "}",
13727             format("{\n"
13728                    "/* aaaa\n"
13729                    "   bbbb */\n"
13730                    "}",
13731                    Tab));
13732   EXPECT_EQ("{\n"
13733             "\t/*\n"
13734             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13735             "\t  bbbbbbbbbbbbb\n"
13736             "\t*/\n"
13737             "}",
13738             format("{\n"
13739                    "/*\n"
13740                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13741                    "*/\n"
13742                    "}",
13743                    Tab));
13744   EXPECT_EQ("{\n"
13745             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13746             "\t// bbbbbbbbbbbbb\n"
13747             "}",
13748             format("{\n"
13749                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13750                    "}",
13751                    Tab));
13752   EXPECT_EQ("{\n"
13753             "\t/*\n"
13754             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13755             "\t  bbbbbbbbbbbbb\n"
13756             "\t*/\n"
13757             "}",
13758             format("{\n"
13759                    "\t/*\n"
13760                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13761                    "\t*/\n"
13762                    "}",
13763                    Tab));
13764   EXPECT_EQ("{\n"
13765             "\t/*\n"
13766             "\n"
13767             "\t*/\n"
13768             "}",
13769             format("{\n"
13770                    "\t/*\n"
13771                    "\n"
13772                    "\t*/\n"
13773                    "}",
13774                    Tab));
13775   EXPECT_EQ("{\n"
13776             "\t/*\n"
13777             " asdf\n"
13778             "\t*/\n"
13779             "}",
13780             format("{\n"
13781                    "\t/*\n"
13782                    " asdf\n"
13783                    "\t*/\n"
13784                    "}",
13785                    Tab));
13786   EXPECT_EQ("/* some\n"
13787             "   comment */",
13788             format(" \t \t /* some\n"
13789                    " \t \t    comment */",
13790                    Tab));
13791   EXPECT_EQ("int a; /* some\n"
13792             "   comment */",
13793             format(" \t \t int a; /* some\n"
13794                    " \t \t    comment */",
13795                    Tab));
13796   EXPECT_EQ("int a; /* some\n"
13797             "comment */",
13798             format(" \t \t int\ta; /* some\n"
13799                    " \t \t    comment */",
13800                    Tab));
13801   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13802             "    comment */",
13803             format(" \t \t f(\"\t\t\"); /* some\n"
13804                    " \t \t    comment */",
13805                    Tab));
13806   EXPECT_EQ("{\n"
13807             "\t/*\n"
13808             "\t * Comment\n"
13809             "\t */\n"
13810             "\tint i;\n"
13811             "}",
13812             format("{\n"
13813                    "\t/*\n"
13814                    "\t * Comment\n"
13815                    "\t */\n"
13816                    "\t int i;\n"
13817                    "}",
13818                    Tab));
13819   Tab.TabWidth = 2;
13820   Tab.IndentWidth = 2;
13821   EXPECT_EQ("{\n"
13822             "\t/* aaaa\n"
13823             "\t\t bbbb */\n"
13824             "}",
13825             format("{\n"
13826                    "/* aaaa\n"
13827                    "\t bbbb */\n"
13828                    "}",
13829                    Tab));
13830   EXPECT_EQ("{\n"
13831             "\t/*\n"
13832             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13833             "\t\tbbbbbbbbbbbbb\n"
13834             "\t*/\n"
13835             "}",
13836             format("{\n"
13837                    "/*\n"
13838                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13839                    "*/\n"
13840                    "}",
13841                    Tab));
13842   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13843   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13844   Tab.TabWidth = 4;
13845   Tab.IndentWidth = 4;
13846   verifyFormat("class Assign {\n"
13847                "\tvoid f() {\n"
13848                "\t\tint         x      = 123;\n"
13849                "\t\tint         random = 4;\n"
13850                "\t\tstd::string alphabet =\n"
13851                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
13852                "\t}\n"
13853                "};",
13854                Tab);
13855 
13856   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
13857   Tab.TabWidth = 8;
13858   Tab.IndentWidth = 8;
13859   EXPECT_EQ("if (aaaaaaaa && // q\n"
13860             "    bb)         // w\n"
13861             "\t;",
13862             format("if (aaaaaaaa &&// q\n"
13863                    "bb)// w\n"
13864                    ";",
13865                    Tab));
13866   EXPECT_EQ("if (aaa && bbb) // w\n"
13867             "\t;",
13868             format("if(aaa&&bbb)// w\n"
13869                    ";",
13870                    Tab));
13871   verifyFormat("class X {\n"
13872                "\tvoid f() {\n"
13873                "\t\tsomeFunction(parameter1,\n"
13874                "\t\t             parameter2);\n"
13875                "\t}\n"
13876                "};",
13877                Tab);
13878   verifyFormat("#define A                        \\\n"
13879                "\tvoid f() {               \\\n"
13880                "\t\tsomeFunction(    \\\n"
13881                "\t\t    parameter1,  \\\n"
13882                "\t\t    parameter2); \\\n"
13883                "\t}",
13884                Tab);
13885   Tab.TabWidth = 4;
13886   Tab.IndentWidth = 8;
13887   verifyFormat("class TabWidth4Indent8 {\n"
13888                "\t\tvoid f() {\n"
13889                "\t\t\t\tsomeFunction(parameter1,\n"
13890                "\t\t\t\t             parameter2);\n"
13891                "\t\t}\n"
13892                "};",
13893                Tab);
13894   Tab.TabWidth = 4;
13895   Tab.IndentWidth = 4;
13896   verifyFormat("class TabWidth4Indent4 {\n"
13897                "\tvoid f() {\n"
13898                "\t\tsomeFunction(parameter1,\n"
13899                "\t\t             parameter2);\n"
13900                "\t}\n"
13901                "};",
13902                Tab);
13903   Tab.TabWidth = 8;
13904   Tab.IndentWidth = 4;
13905   verifyFormat("class TabWidth8Indent4 {\n"
13906                "    void f() {\n"
13907                "\tsomeFunction(parameter1,\n"
13908                "\t             parameter2);\n"
13909                "    }\n"
13910                "};",
13911                Tab);
13912   Tab.TabWidth = 8;
13913   Tab.IndentWidth = 8;
13914   EXPECT_EQ("/*\n"
13915             "              a\t\tcomment\n"
13916             "              in multiple lines\n"
13917             "       */",
13918             format("   /*\t \t \n"
13919                    " \t \t a\t\tcomment\t \t\n"
13920                    " \t \t in multiple lines\t\n"
13921                    " \t  */",
13922                    Tab));
13923   verifyFormat("{\n"
13924                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13925                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13926                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13927                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13928                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13929                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13930                "};",
13931                Tab);
13932   verifyFormat("enum AA {\n"
13933                "\ta1, // Force multiple lines\n"
13934                "\ta2,\n"
13935                "\ta3\n"
13936                "};",
13937                Tab);
13938   EXPECT_EQ("if (aaaaaaaa && // q\n"
13939             "    bb)         // w\n"
13940             "\t;",
13941             format("if (aaaaaaaa &&// q\n"
13942                    "bb)// w\n"
13943                    ";",
13944                    Tab));
13945   verifyFormat("class X {\n"
13946                "\tvoid f() {\n"
13947                "\t\tsomeFunction(parameter1,\n"
13948                "\t\t             parameter2);\n"
13949                "\t}\n"
13950                "};",
13951                Tab);
13952   verifyFormat("{\n"
13953                "\tQ(\n"
13954                "\t    {\n"
13955                "\t\t    int a;\n"
13956                "\t\t    someFunction(aaaaaaaa,\n"
13957                "\t\t                 bbbbbbb);\n"
13958                "\t    },\n"
13959                "\t    p);\n"
13960                "}",
13961                Tab);
13962   EXPECT_EQ("{\n"
13963             "\t/* aaaa\n"
13964             "\t   bbbb */\n"
13965             "}",
13966             format("{\n"
13967                    "/* aaaa\n"
13968                    "   bbbb */\n"
13969                    "}",
13970                    Tab));
13971   EXPECT_EQ("{\n"
13972             "\t/*\n"
13973             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13974             "\t  bbbbbbbbbbbbb\n"
13975             "\t*/\n"
13976             "}",
13977             format("{\n"
13978                    "/*\n"
13979                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13980                    "*/\n"
13981                    "}",
13982                    Tab));
13983   EXPECT_EQ("{\n"
13984             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13985             "\t// bbbbbbbbbbbbb\n"
13986             "}",
13987             format("{\n"
13988                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13989                    "}",
13990                    Tab));
13991   EXPECT_EQ("{\n"
13992             "\t/*\n"
13993             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13994             "\t  bbbbbbbbbbbbb\n"
13995             "\t*/\n"
13996             "}",
13997             format("{\n"
13998                    "\t/*\n"
13999                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14000                    "\t*/\n"
14001                    "}",
14002                    Tab));
14003   EXPECT_EQ("{\n"
14004             "\t/*\n"
14005             "\n"
14006             "\t*/\n"
14007             "}",
14008             format("{\n"
14009                    "\t/*\n"
14010                    "\n"
14011                    "\t*/\n"
14012                    "}",
14013                    Tab));
14014   EXPECT_EQ("{\n"
14015             "\t/*\n"
14016             " asdf\n"
14017             "\t*/\n"
14018             "}",
14019             format("{\n"
14020                    "\t/*\n"
14021                    " asdf\n"
14022                    "\t*/\n"
14023                    "}",
14024                    Tab));
14025   EXPECT_EQ("/* some\n"
14026             "   comment */",
14027             format(" \t \t /* some\n"
14028                    " \t \t    comment */",
14029                    Tab));
14030   EXPECT_EQ("int a; /* some\n"
14031             "   comment */",
14032             format(" \t \t int a; /* some\n"
14033                    " \t \t    comment */",
14034                    Tab));
14035   EXPECT_EQ("int a; /* some\n"
14036             "comment */",
14037             format(" \t \t int\ta; /* some\n"
14038                    " \t \t    comment */",
14039                    Tab));
14040   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14041             "    comment */",
14042             format(" \t \t f(\"\t\t\"); /* some\n"
14043                    " \t \t    comment */",
14044                    Tab));
14045   EXPECT_EQ("{\n"
14046             "\t/*\n"
14047             "\t * Comment\n"
14048             "\t */\n"
14049             "\tint i;\n"
14050             "}",
14051             format("{\n"
14052                    "\t/*\n"
14053                    "\t * Comment\n"
14054                    "\t */\n"
14055                    "\t int i;\n"
14056                    "}",
14057                    Tab));
14058   Tab.TabWidth = 2;
14059   Tab.IndentWidth = 2;
14060   EXPECT_EQ("{\n"
14061             "\t/* aaaa\n"
14062             "\t   bbbb */\n"
14063             "}",
14064             format("{\n"
14065                    "/* aaaa\n"
14066                    "   bbbb */\n"
14067                    "}",
14068                    Tab));
14069   EXPECT_EQ("{\n"
14070             "\t/*\n"
14071             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14072             "\t  bbbbbbbbbbbbb\n"
14073             "\t*/\n"
14074             "}",
14075             format("{\n"
14076                    "/*\n"
14077                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14078                    "*/\n"
14079                    "}",
14080                    Tab));
14081   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14082   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14083   Tab.TabWidth = 4;
14084   Tab.IndentWidth = 4;
14085   verifyFormat("class Assign {\n"
14086                "\tvoid f() {\n"
14087                "\t\tint         x      = 123;\n"
14088                "\t\tint         random = 4;\n"
14089                "\t\tstd::string alphabet =\n"
14090                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14091                "\t}\n"
14092                "};",
14093                Tab);
14094   Tab.AlignOperands = FormatStyle::OAS_Align;
14095   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
14096                "                 cccccccccccccccccccc;",
14097                Tab);
14098   // no alignment
14099   verifyFormat("int aaaaaaaaaa =\n"
14100                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
14101                Tab);
14102   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
14103                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
14104                "                        : 333333333333333;",
14105                Tab);
14106   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14107   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
14108   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
14109                "               + cccccccccccccccccccc;",
14110                Tab);
14111 }
14112 
14113 TEST_F(FormatTest, ZeroTabWidth) {
14114   FormatStyle Tab = getLLVMStyleWithColumns(42);
14115   Tab.IndentWidth = 8;
14116   Tab.UseTab = FormatStyle::UT_Never;
14117   Tab.TabWidth = 0;
14118   EXPECT_EQ("void a(){\n"
14119             "    // line starts with '\t'\n"
14120             "};",
14121             format("void a(){\n"
14122                    "\t// line starts with '\t'\n"
14123                    "};",
14124                    Tab));
14125 
14126   EXPECT_EQ("void a(){\n"
14127             "    // line starts with '\t'\n"
14128             "};",
14129             format("void a(){\n"
14130                    "\t\t// line starts with '\t'\n"
14131                    "};",
14132                    Tab));
14133 
14134   Tab.UseTab = FormatStyle::UT_ForIndentation;
14135   EXPECT_EQ("void a(){\n"
14136             "    // line starts with '\t'\n"
14137             "};",
14138             format("void a(){\n"
14139                    "\t// line starts with '\t'\n"
14140                    "};",
14141                    Tab));
14142 
14143   EXPECT_EQ("void a(){\n"
14144             "    // line starts with '\t'\n"
14145             "};",
14146             format("void a(){\n"
14147                    "\t\t// line starts with '\t'\n"
14148                    "};",
14149                    Tab));
14150 
14151   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14152   EXPECT_EQ("void a(){\n"
14153             "    // line starts with '\t'\n"
14154             "};",
14155             format("void a(){\n"
14156                    "\t// line starts with '\t'\n"
14157                    "};",
14158                    Tab));
14159 
14160   EXPECT_EQ("void a(){\n"
14161             "    // line starts with '\t'\n"
14162             "};",
14163             format("void a(){\n"
14164                    "\t\t// line starts with '\t'\n"
14165                    "};",
14166                    Tab));
14167 
14168   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14169   EXPECT_EQ("void a(){\n"
14170             "    // line starts with '\t'\n"
14171             "};",
14172             format("void a(){\n"
14173                    "\t// line starts with '\t'\n"
14174                    "};",
14175                    Tab));
14176 
14177   EXPECT_EQ("void a(){\n"
14178             "    // line starts with '\t'\n"
14179             "};",
14180             format("void a(){\n"
14181                    "\t\t// line starts with '\t'\n"
14182                    "};",
14183                    Tab));
14184 
14185   Tab.UseTab = FormatStyle::UT_Always;
14186   EXPECT_EQ("void a(){\n"
14187             "// line starts with '\t'\n"
14188             "};",
14189             format("void a(){\n"
14190                    "\t// line starts with '\t'\n"
14191                    "};",
14192                    Tab));
14193 
14194   EXPECT_EQ("void a(){\n"
14195             "// line starts with '\t'\n"
14196             "};",
14197             format("void a(){\n"
14198                    "\t\t// line starts with '\t'\n"
14199                    "};",
14200                    Tab));
14201 }
14202 
14203 TEST_F(FormatTest, CalculatesOriginalColumn) {
14204   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14205             "q\"; /* some\n"
14206             "       comment */",
14207             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14208                    "q\"; /* some\n"
14209                    "       comment */",
14210                    getLLVMStyle()));
14211   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14212             "/* some\n"
14213             "   comment */",
14214             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
14215                    " /* some\n"
14216                    "    comment */",
14217                    getLLVMStyle()));
14218   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14219             "qqq\n"
14220             "/* some\n"
14221             "   comment */",
14222             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14223                    "qqq\n"
14224                    " /* some\n"
14225                    "    comment */",
14226                    getLLVMStyle()));
14227   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14228             "wwww; /* some\n"
14229             "         comment */",
14230             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
14231                    "wwww; /* some\n"
14232                    "         comment */",
14233                    getLLVMStyle()));
14234 }
14235 
14236 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
14237   FormatStyle NoSpace = getLLVMStyle();
14238   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
14239 
14240   verifyFormat("while(true)\n"
14241                "  continue;",
14242                NoSpace);
14243   verifyFormat("for(;;)\n"
14244                "  continue;",
14245                NoSpace);
14246   verifyFormat("if(true)\n"
14247                "  f();\n"
14248                "else if(true)\n"
14249                "  f();",
14250                NoSpace);
14251   verifyFormat("do {\n"
14252                "  do_something();\n"
14253                "} while(something());",
14254                NoSpace);
14255   verifyFormat("switch(x) {\n"
14256                "default:\n"
14257                "  break;\n"
14258                "}",
14259                NoSpace);
14260   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14261   verifyFormat("size_t x = sizeof(x);", NoSpace);
14262   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14263   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14264   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14265   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14266   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14267   verifyFormat("alignas(128) char a[128];", NoSpace);
14268   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14269   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14270   verifyFormat("int f() throw(Deprecated);", NoSpace);
14271   verifyFormat("typedef void (*cb)(int);", NoSpace);
14272   verifyFormat("T A::operator()();", NoSpace);
14273   verifyFormat("X A::operator++(T);", NoSpace);
14274   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14275 
14276   FormatStyle Space = getLLVMStyle();
14277   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14278 
14279   verifyFormat("int f ();", Space);
14280   verifyFormat("void f (int a, T b) {\n"
14281                "  while (true)\n"
14282                "    continue;\n"
14283                "}",
14284                Space);
14285   verifyFormat("if (true)\n"
14286                "  f ();\n"
14287                "else if (true)\n"
14288                "  f ();",
14289                Space);
14290   verifyFormat("do {\n"
14291                "  do_something ();\n"
14292                "} while (something ());",
14293                Space);
14294   verifyFormat("switch (x) {\n"
14295                "default:\n"
14296                "  break;\n"
14297                "}",
14298                Space);
14299   verifyFormat("A::A () : a (1) {}", Space);
14300   verifyFormat("void f () __attribute__ ((asdf));", Space);
14301   verifyFormat("*(&a + 1);\n"
14302                "&((&a)[1]);\n"
14303                "a[(b + c) * d];\n"
14304                "(((a + 1) * 2) + 3) * 4;",
14305                Space);
14306   verifyFormat("#define A(x) x", Space);
14307   verifyFormat("#define A (x) x", Space);
14308   verifyFormat("#if defined(x)\n"
14309                "#endif",
14310                Space);
14311   verifyFormat("auto i = std::make_unique<int> (5);", Space);
14312   verifyFormat("size_t x = sizeof (x);", Space);
14313   verifyFormat("auto f (int x) -> decltype (x);", Space);
14314   verifyFormat("auto f (int x) -> typeof (x);", Space);
14315   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
14316   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
14317   verifyFormat("int f (T x) noexcept (x.create ());", Space);
14318   verifyFormat("alignas (128) char a[128];", Space);
14319   verifyFormat("size_t x = alignof (MyType);", Space);
14320   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
14321   verifyFormat("int f () throw (Deprecated);", Space);
14322   verifyFormat("typedef void (*cb) (int);", Space);
14323   // FIXME these tests regressed behaviour.
14324   // verifyFormat("T A::operator() ();", Space);
14325   // verifyFormat("X A::operator++ (T);", Space);
14326   verifyFormat("auto lambda = [] () { return 0; };", Space);
14327   verifyFormat("int x = int (y);", Space);
14328 
14329   FormatStyle SomeSpace = getLLVMStyle();
14330   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
14331 
14332   verifyFormat("[]() -> float {}", SomeSpace);
14333   verifyFormat("[] (auto foo) {}", SomeSpace);
14334   verifyFormat("[foo]() -> int {}", SomeSpace);
14335   verifyFormat("int f();", SomeSpace);
14336   verifyFormat("void f (int a, T b) {\n"
14337                "  while (true)\n"
14338                "    continue;\n"
14339                "}",
14340                SomeSpace);
14341   verifyFormat("if (true)\n"
14342                "  f();\n"
14343                "else if (true)\n"
14344                "  f();",
14345                SomeSpace);
14346   verifyFormat("do {\n"
14347                "  do_something();\n"
14348                "} while (something());",
14349                SomeSpace);
14350   verifyFormat("switch (x) {\n"
14351                "default:\n"
14352                "  break;\n"
14353                "}",
14354                SomeSpace);
14355   verifyFormat("A::A() : a (1) {}", SomeSpace);
14356   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
14357   verifyFormat("*(&a + 1);\n"
14358                "&((&a)[1]);\n"
14359                "a[(b + c) * d];\n"
14360                "(((a + 1) * 2) + 3) * 4;",
14361                SomeSpace);
14362   verifyFormat("#define A(x) x", SomeSpace);
14363   verifyFormat("#define A (x) x", SomeSpace);
14364   verifyFormat("#if defined(x)\n"
14365                "#endif",
14366                SomeSpace);
14367   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
14368   verifyFormat("size_t x = sizeof (x);", SomeSpace);
14369   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
14370   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
14371   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
14372   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
14373   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
14374   verifyFormat("alignas (128) char a[128];", SomeSpace);
14375   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
14376   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14377                SomeSpace);
14378   verifyFormat("int f() throw (Deprecated);", SomeSpace);
14379   verifyFormat("typedef void (*cb) (int);", SomeSpace);
14380   verifyFormat("T A::operator()();", SomeSpace);
14381   // FIXME these tests regressed behaviour.
14382   // verifyFormat("X A::operator++ (T);", SomeSpace);
14383   verifyFormat("int x = int (y);", SomeSpace);
14384   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
14385 
14386   FormatStyle SpaceControlStatements = getLLVMStyle();
14387   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14388   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
14389 
14390   verifyFormat("while (true)\n"
14391                "  continue;",
14392                SpaceControlStatements);
14393   verifyFormat("if (true)\n"
14394                "  f();\n"
14395                "else if (true)\n"
14396                "  f();",
14397                SpaceControlStatements);
14398   verifyFormat("for (;;) {\n"
14399                "  do_something();\n"
14400                "}",
14401                SpaceControlStatements);
14402   verifyFormat("do {\n"
14403                "  do_something();\n"
14404                "} while (something());",
14405                SpaceControlStatements);
14406   verifyFormat("switch (x) {\n"
14407                "default:\n"
14408                "  break;\n"
14409                "}",
14410                SpaceControlStatements);
14411 
14412   FormatStyle SpaceFuncDecl = getLLVMStyle();
14413   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14414   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
14415 
14416   verifyFormat("int f ();", SpaceFuncDecl);
14417   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
14418   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
14419   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
14420   verifyFormat("#define A(x) x", SpaceFuncDecl);
14421   verifyFormat("#define A (x) x", SpaceFuncDecl);
14422   verifyFormat("#if defined(x)\n"
14423                "#endif",
14424                SpaceFuncDecl);
14425   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
14426   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
14427   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
14428   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
14429   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
14430   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
14431   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
14432   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
14433   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
14434   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14435                SpaceFuncDecl);
14436   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
14437   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
14438   // FIXME these tests regressed behaviour.
14439   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
14440   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
14441   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
14442   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
14443   verifyFormat("int x = int(y);", SpaceFuncDecl);
14444   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14445                SpaceFuncDecl);
14446 
14447   FormatStyle SpaceFuncDef = getLLVMStyle();
14448   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14449   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
14450 
14451   verifyFormat("int f();", SpaceFuncDef);
14452   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
14453   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
14454   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
14455   verifyFormat("#define A(x) x", SpaceFuncDef);
14456   verifyFormat("#define A (x) x", SpaceFuncDef);
14457   verifyFormat("#if defined(x)\n"
14458                "#endif",
14459                SpaceFuncDef);
14460   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
14461   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
14462   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
14463   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
14464   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
14465   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
14466   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
14467   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
14468   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
14469   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
14470                SpaceFuncDef);
14471   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
14472   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
14473   verifyFormat("T A::operator()();", SpaceFuncDef);
14474   verifyFormat("X A::operator++(T);", SpaceFuncDef);
14475   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
14476   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
14477   verifyFormat("int x = int(y);", SpaceFuncDef);
14478   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
14479                SpaceFuncDef);
14480 
14481   FormatStyle SpaceIfMacros = getLLVMStyle();
14482   SpaceIfMacros.IfMacros.clear();
14483   SpaceIfMacros.IfMacros.push_back("MYIF");
14484   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14485   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
14486   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
14487   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
14488   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
14489 
14490   FormatStyle SpaceForeachMacros = getLLVMStyle();
14491   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14492   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
14493   verifyFormat("foreach (Item *item, itemlist) {}", SpaceForeachMacros);
14494   verifyFormat("Q_FOREACH (Item *item, itemlist) {}", SpaceForeachMacros);
14495   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {}", SpaceForeachMacros);
14496   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
14497 
14498   FormatStyle SomeSpace2 = getLLVMStyle();
14499   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14500   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
14501   verifyFormat("[]() -> float {}", SomeSpace2);
14502   verifyFormat("[] (auto foo) {}", SomeSpace2);
14503   verifyFormat("[foo]() -> int {}", SomeSpace2);
14504   verifyFormat("int f();", SomeSpace2);
14505   verifyFormat("void f (int a, T b) {\n"
14506                "  while (true)\n"
14507                "    continue;\n"
14508                "}",
14509                SomeSpace2);
14510   verifyFormat("if (true)\n"
14511                "  f();\n"
14512                "else if (true)\n"
14513                "  f();",
14514                SomeSpace2);
14515   verifyFormat("do {\n"
14516                "  do_something();\n"
14517                "} while (something());",
14518                SomeSpace2);
14519   verifyFormat("switch (x) {\n"
14520                "default:\n"
14521                "  break;\n"
14522                "}",
14523                SomeSpace2);
14524   verifyFormat("A::A() : a (1) {}", SomeSpace2);
14525   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
14526   verifyFormat("*(&a + 1);\n"
14527                "&((&a)[1]);\n"
14528                "a[(b + c) * d];\n"
14529                "(((a + 1) * 2) + 3) * 4;",
14530                SomeSpace2);
14531   verifyFormat("#define A(x) x", SomeSpace2);
14532   verifyFormat("#define A (x) x", SomeSpace2);
14533   verifyFormat("#if defined(x)\n"
14534                "#endif",
14535                SomeSpace2);
14536   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
14537   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
14538   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
14539   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
14540   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
14541   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
14542   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
14543   verifyFormat("alignas (128) char a[128];", SomeSpace2);
14544   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
14545   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14546                SomeSpace2);
14547   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
14548   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
14549   verifyFormat("T A::operator()();", SomeSpace2);
14550   // verifyFormat("X A::operator++ (T);", SomeSpace2);
14551   verifyFormat("int x = int (y);", SomeSpace2);
14552   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
14553 
14554   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
14555   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
14556   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
14557       .AfterOverloadedOperator = true;
14558 
14559   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
14560   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
14561   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
14562   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
14563 
14564   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
14565       .AfterOverloadedOperator = false;
14566 
14567   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
14568   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
14569   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
14570   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
14571 }
14572 
14573 TEST_F(FormatTest, SpaceAfterLogicalNot) {
14574   FormatStyle Spaces = getLLVMStyle();
14575   Spaces.SpaceAfterLogicalNot = true;
14576 
14577   verifyFormat("bool x = ! y", Spaces);
14578   verifyFormat("if (! isFailure())", Spaces);
14579   verifyFormat("if (! (a && b))", Spaces);
14580   verifyFormat("\"Error!\"", Spaces);
14581   verifyFormat("! ! x", Spaces);
14582 }
14583 
14584 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
14585   FormatStyle Spaces = getLLVMStyle();
14586 
14587   Spaces.SpacesInParentheses = true;
14588   verifyFormat("do_something( ::globalVar );", Spaces);
14589   verifyFormat("call( x, y, z );", Spaces);
14590   verifyFormat("call();", Spaces);
14591   verifyFormat("std::function<void( int, int )> callback;", Spaces);
14592   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
14593                Spaces);
14594   verifyFormat("while ( (bool)1 )\n"
14595                "  continue;",
14596                Spaces);
14597   verifyFormat("for ( ;; )\n"
14598                "  continue;",
14599                Spaces);
14600   verifyFormat("if ( true )\n"
14601                "  f();\n"
14602                "else if ( true )\n"
14603                "  f();",
14604                Spaces);
14605   verifyFormat("do {\n"
14606                "  do_something( (int)i );\n"
14607                "} while ( something() );",
14608                Spaces);
14609   verifyFormat("switch ( x ) {\n"
14610                "default:\n"
14611                "  break;\n"
14612                "}",
14613                Spaces);
14614 
14615   Spaces.SpacesInParentheses = false;
14616   Spaces.SpacesInCStyleCastParentheses = true;
14617   verifyFormat("Type *A = ( Type * )P;", Spaces);
14618   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
14619   verifyFormat("x = ( int32 )y;", Spaces);
14620   verifyFormat("int a = ( int )(2.0f);", Spaces);
14621   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
14622   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
14623   verifyFormat("#define x (( int )-1)", Spaces);
14624 
14625   // Run the first set of tests again with:
14626   Spaces.SpacesInParentheses = false;
14627   Spaces.SpaceInEmptyParentheses = true;
14628   Spaces.SpacesInCStyleCastParentheses = 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 the first set of tests again with:
14654   Spaces.SpaceAfterCStyleCast = true;
14655   verifyFormat("call(x, y, z);", Spaces);
14656   verifyFormat("call( );", Spaces);
14657   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14658   verifyFormat("while (( bool ) 1)\n"
14659                "  continue;",
14660                Spaces);
14661   verifyFormat("for (;;)\n"
14662                "  continue;",
14663                Spaces);
14664   verifyFormat("if (true)\n"
14665                "  f( );\n"
14666                "else if (true)\n"
14667                "  f( );",
14668                Spaces);
14669   verifyFormat("do {\n"
14670                "  do_something(( int ) i);\n"
14671                "} while (something( ));",
14672                Spaces);
14673   verifyFormat("switch (x) {\n"
14674                "default:\n"
14675                "  break;\n"
14676                "}",
14677                Spaces);
14678   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
14679   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
14680   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
14681   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
14682   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
14683 
14684   // Run subset of tests again with:
14685   Spaces.SpacesInCStyleCastParentheses = false;
14686   Spaces.SpaceAfterCStyleCast = true;
14687   verifyFormat("while ((bool) 1)\n"
14688                "  continue;",
14689                Spaces);
14690   verifyFormat("do {\n"
14691                "  do_something((int) i);\n"
14692                "} while (something( ));",
14693                Spaces);
14694 
14695   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
14696   verifyFormat("size_t idx = (size_t) a;", Spaces);
14697   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
14698   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14699   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14700   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14701   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14702   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
14703   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
14704   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
14705   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
14706   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
14707   Spaces.ColumnLimit = 80;
14708   Spaces.IndentWidth = 4;
14709   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14710   verifyFormat("void foo( ) {\n"
14711                "    size_t foo = (*(function))(\n"
14712                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14713                "BarrrrrrrrrrrrLong,\n"
14714                "        FoooooooooLooooong);\n"
14715                "}",
14716                Spaces);
14717   Spaces.SpaceAfterCStyleCast = false;
14718   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
14719   verifyFormat("size_t idx = (size_t)a;", Spaces);
14720   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
14721   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14722   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14723   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14724   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14725 
14726   verifyFormat("void foo( ) {\n"
14727                "    size_t foo = (*(function))(\n"
14728                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14729                "BarrrrrrrrrrrrLong,\n"
14730                "        FoooooooooLooooong);\n"
14731                "}",
14732                Spaces);
14733 }
14734 
14735 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
14736   verifyFormat("int a[5];");
14737   verifyFormat("a[3] += 42;");
14738 
14739   FormatStyle Spaces = getLLVMStyle();
14740   Spaces.SpacesInSquareBrackets = true;
14741   // Not lambdas.
14742   verifyFormat("int a[ 5 ];", Spaces);
14743   verifyFormat("a[ 3 ] += 42;", Spaces);
14744   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
14745   verifyFormat("double &operator[](int i) { return 0; }\n"
14746                "int i;",
14747                Spaces);
14748   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
14749   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
14750   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
14751   // Lambdas.
14752   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
14753   verifyFormat("return [ i, args... ] {};", Spaces);
14754   verifyFormat("int foo = [ &bar ]() {};", Spaces);
14755   verifyFormat("int foo = [ = ]() {};", Spaces);
14756   verifyFormat("int foo = [ & ]() {};", Spaces);
14757   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
14758   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
14759 }
14760 
14761 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
14762   FormatStyle NoSpaceStyle = getLLVMStyle();
14763   verifyFormat("int a[5];", NoSpaceStyle);
14764   verifyFormat("a[3] += 42;", NoSpaceStyle);
14765 
14766   verifyFormat("int a[1];", NoSpaceStyle);
14767   verifyFormat("int 1 [a];", NoSpaceStyle);
14768   verifyFormat("int a[1][2];", NoSpaceStyle);
14769   verifyFormat("a[7] = 5;", NoSpaceStyle);
14770   verifyFormat("int a = (f())[23];", NoSpaceStyle);
14771   verifyFormat("f([] {})", NoSpaceStyle);
14772 
14773   FormatStyle Space = getLLVMStyle();
14774   Space.SpaceBeforeSquareBrackets = true;
14775   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
14776   verifyFormat("return [i, args...] {};", Space);
14777 
14778   verifyFormat("int a [5];", Space);
14779   verifyFormat("a [3] += 42;", Space);
14780   verifyFormat("constexpr char hello []{\"hello\"};", Space);
14781   verifyFormat("double &operator[](int i) { return 0; }\n"
14782                "int i;",
14783                Space);
14784   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
14785   verifyFormat("int i = a [a][a]->f();", Space);
14786   verifyFormat("int i = (*b) [a]->f();", Space);
14787 
14788   verifyFormat("int a [1];", Space);
14789   verifyFormat("int 1 [a];", Space);
14790   verifyFormat("int a [1][2];", Space);
14791   verifyFormat("a [7] = 5;", Space);
14792   verifyFormat("int a = (f()) [23];", Space);
14793   verifyFormat("f([] {})", Space);
14794 }
14795 
14796 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
14797   verifyFormat("int a = 5;");
14798   verifyFormat("a += 42;");
14799   verifyFormat("a or_eq 8;");
14800 
14801   FormatStyle Spaces = getLLVMStyle();
14802   Spaces.SpaceBeforeAssignmentOperators = false;
14803   verifyFormat("int a= 5;", Spaces);
14804   verifyFormat("a+= 42;", Spaces);
14805   verifyFormat("a or_eq 8;", Spaces);
14806 }
14807 
14808 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
14809   verifyFormat("class Foo : public Bar {};");
14810   verifyFormat("Foo::Foo() : foo(1) {}");
14811   verifyFormat("for (auto a : b) {\n}");
14812   verifyFormat("int x = a ? b : c;");
14813   verifyFormat("{\n"
14814                "label0:\n"
14815                "  int x = 0;\n"
14816                "}");
14817   verifyFormat("switch (x) {\n"
14818                "case 1:\n"
14819                "default:\n"
14820                "}");
14821   verifyFormat("switch (allBraces) {\n"
14822                "case 1: {\n"
14823                "  break;\n"
14824                "}\n"
14825                "case 2: {\n"
14826                "  [[fallthrough]];\n"
14827                "}\n"
14828                "default: {\n"
14829                "  break;\n"
14830                "}\n"
14831                "}");
14832 
14833   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
14834   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
14835   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
14836   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
14837   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
14838   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
14839   verifyFormat("{\n"
14840                "label1:\n"
14841                "  int x = 0;\n"
14842                "}",
14843                CtorInitializerStyle);
14844   verifyFormat("switch (x) {\n"
14845                "case 1:\n"
14846                "default:\n"
14847                "}",
14848                CtorInitializerStyle);
14849   verifyFormat("switch (allBraces) {\n"
14850                "case 1: {\n"
14851                "  break;\n"
14852                "}\n"
14853                "case 2: {\n"
14854                "  [[fallthrough]];\n"
14855                "}\n"
14856                "default: {\n"
14857                "  break;\n"
14858                "}\n"
14859                "}",
14860                CtorInitializerStyle);
14861   CtorInitializerStyle.BreakConstructorInitializers =
14862       FormatStyle::BCIS_AfterColon;
14863   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
14864                "    aaaaaaaaaaaaaaaa(1),\n"
14865                "    bbbbbbbbbbbbbbbb(2) {}",
14866                CtorInitializerStyle);
14867   CtorInitializerStyle.BreakConstructorInitializers =
14868       FormatStyle::BCIS_BeforeComma;
14869   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14870                "    : aaaaaaaaaaaaaaaa(1)\n"
14871                "    , bbbbbbbbbbbbbbbb(2) {}",
14872                CtorInitializerStyle);
14873   CtorInitializerStyle.BreakConstructorInitializers =
14874       FormatStyle::BCIS_BeforeColon;
14875   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14876                "    : aaaaaaaaaaaaaaaa(1),\n"
14877                "      bbbbbbbbbbbbbbbb(2) {}",
14878                CtorInitializerStyle);
14879   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
14880   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14881                ": aaaaaaaaaaaaaaaa(1),\n"
14882                "  bbbbbbbbbbbbbbbb(2) {}",
14883                CtorInitializerStyle);
14884 
14885   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
14886   InheritanceStyle.SpaceBeforeInheritanceColon = false;
14887   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
14888   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
14889   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
14890   verifyFormat("int x = a ? b : c;", InheritanceStyle);
14891   verifyFormat("{\n"
14892                "label2:\n"
14893                "  int x = 0;\n"
14894                "}",
14895                InheritanceStyle);
14896   verifyFormat("switch (x) {\n"
14897                "case 1:\n"
14898                "default:\n"
14899                "}",
14900                InheritanceStyle);
14901   verifyFormat("switch (allBraces) {\n"
14902                "case 1: {\n"
14903                "  break;\n"
14904                "}\n"
14905                "case 2: {\n"
14906                "  [[fallthrough]];\n"
14907                "}\n"
14908                "default: {\n"
14909                "  break;\n"
14910                "}\n"
14911                "}",
14912                InheritanceStyle);
14913   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
14914   verifyFormat("class Foooooooooooooooooooooo\n"
14915                "    : public aaaaaaaaaaaaaaaaaa,\n"
14916                "      public bbbbbbbbbbbbbbbbbb {\n"
14917                "}",
14918                InheritanceStyle);
14919   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
14920   verifyFormat("class Foooooooooooooooooooooo:\n"
14921                "    public aaaaaaaaaaaaaaaaaa,\n"
14922                "    public bbbbbbbbbbbbbbbbbb {\n"
14923                "}",
14924                InheritanceStyle);
14925   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
14926   verifyFormat("class Foooooooooooooooooooooo\n"
14927                "    : public aaaaaaaaaaaaaaaaaa\n"
14928                "    , public bbbbbbbbbbbbbbbbbb {\n"
14929                "}",
14930                InheritanceStyle);
14931   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
14932   verifyFormat("class Foooooooooooooooooooooo\n"
14933                "    : public aaaaaaaaaaaaaaaaaa,\n"
14934                "      public bbbbbbbbbbbbbbbbbb {\n"
14935                "}",
14936                InheritanceStyle);
14937   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
14938   verifyFormat("class Foooooooooooooooooooooo\n"
14939                ": public aaaaaaaaaaaaaaaaaa,\n"
14940                "  public bbbbbbbbbbbbbbbbbb {}",
14941                InheritanceStyle);
14942 
14943   FormatStyle ForLoopStyle = getLLVMStyle();
14944   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
14945   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
14946   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
14947   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
14948   verifyFormat("int x = a ? b : c;", ForLoopStyle);
14949   verifyFormat("{\n"
14950                "label2:\n"
14951                "  int x = 0;\n"
14952                "}",
14953                ForLoopStyle);
14954   verifyFormat("switch (x) {\n"
14955                "case 1:\n"
14956                "default:\n"
14957                "}",
14958                ForLoopStyle);
14959   verifyFormat("switch (allBraces) {\n"
14960                "case 1: {\n"
14961                "  break;\n"
14962                "}\n"
14963                "case 2: {\n"
14964                "  [[fallthrough]];\n"
14965                "}\n"
14966                "default: {\n"
14967                "  break;\n"
14968                "}\n"
14969                "}",
14970                ForLoopStyle);
14971 
14972   FormatStyle CaseStyle = getLLVMStyle();
14973   CaseStyle.SpaceBeforeCaseColon = true;
14974   verifyFormat("class Foo : public Bar {};", CaseStyle);
14975   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
14976   verifyFormat("for (auto a : b) {\n}", CaseStyle);
14977   verifyFormat("int x = a ? b : c;", CaseStyle);
14978   verifyFormat("switch (x) {\n"
14979                "case 1 :\n"
14980                "default :\n"
14981                "}",
14982                CaseStyle);
14983   verifyFormat("switch (allBraces) {\n"
14984                "case 1 : {\n"
14985                "  break;\n"
14986                "}\n"
14987                "case 2 : {\n"
14988                "  [[fallthrough]];\n"
14989                "}\n"
14990                "default : {\n"
14991                "  break;\n"
14992                "}\n"
14993                "}",
14994                CaseStyle);
14995 
14996   FormatStyle NoSpaceStyle = getLLVMStyle();
14997   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
14998   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
14999   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
15000   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15001   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
15002   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
15003   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
15004   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
15005   verifyFormat("{\n"
15006                "label3:\n"
15007                "  int x = 0;\n"
15008                "}",
15009                NoSpaceStyle);
15010   verifyFormat("switch (x) {\n"
15011                "case 1:\n"
15012                "default:\n"
15013                "}",
15014                NoSpaceStyle);
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                NoSpaceStyle);
15027 
15028   FormatStyle InvertedSpaceStyle = getLLVMStyle();
15029   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
15030   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
15031   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
15032   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
15033   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
15034   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
15035   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
15036   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
15037   verifyFormat("{\n"
15038                "label3:\n"
15039                "  int x = 0;\n"
15040                "}",
15041                InvertedSpaceStyle);
15042   verifyFormat("switch (x) {\n"
15043                "case 1 :\n"
15044                "case 2 : {\n"
15045                "  break;\n"
15046                "}\n"
15047                "default :\n"
15048                "  break;\n"
15049                "}",
15050                InvertedSpaceStyle);
15051   verifyFormat("switch (allBraces) {\n"
15052                "case 1 : {\n"
15053                "  break;\n"
15054                "}\n"
15055                "case 2 : {\n"
15056                "  [[fallthrough]];\n"
15057                "}\n"
15058                "default : {\n"
15059                "  break;\n"
15060                "}\n"
15061                "}",
15062                InvertedSpaceStyle);
15063 }
15064 
15065 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
15066   FormatStyle Style = getLLVMStyle();
15067 
15068   Style.PointerAlignment = FormatStyle::PAS_Left;
15069   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15070   verifyFormat("void* const* x = NULL;", Style);
15071 
15072 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
15073   do {                                                                         \
15074     Style.PointerAlignment = FormatStyle::Pointers;                            \
15075     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
15076     verifyFormat(Code, Style);                                                 \
15077   } while (false)
15078 
15079   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
15080   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
15081   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
15082 
15083   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
15084   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
15085   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
15086 
15087   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
15088   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
15089   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
15090 
15091   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
15092   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
15093   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
15094 
15095   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
15096   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15097                         SAPQ_Default);
15098   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15099                         SAPQ_Default);
15100 
15101   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
15102   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
15103                         SAPQ_Before);
15104   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15105                         SAPQ_Before);
15106 
15107   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
15108   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
15109   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
15110                         SAPQ_After);
15111 
15112   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
15113   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
15114   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
15115 
15116 #undef verifyQualifierSpaces
15117 
15118   FormatStyle Spaces = getLLVMStyle();
15119   Spaces.AttributeMacros.push_back("qualified");
15120   Spaces.PointerAlignment = FormatStyle::PAS_Right;
15121   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
15122   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
15123   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
15124   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
15125   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
15126   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15127   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15128   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
15129   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
15130   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15131   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15132   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15133 
15134   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
15135   Spaces.PointerAlignment = FormatStyle::PAS_Left;
15136   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
15137   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
15138   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
15139   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
15140   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
15141   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15142   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
15143   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15144   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
15145   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
15146   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
15147   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
15148   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15149 
15150   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
15151   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
15152   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
15153   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
15154   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
15155   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
15156   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
15157   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
15158 }
15159 
15160 TEST_F(FormatTest, AlignConsecutiveMacros) {
15161   FormatStyle Style = getLLVMStyle();
15162   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15163   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15164   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15165 
15166   verifyFormat("#define a 3\n"
15167                "#define bbbb 4\n"
15168                "#define ccc (5)",
15169                Style);
15170 
15171   verifyFormat("#define f(x) (x * x)\n"
15172                "#define fff(x, y, z) (x * y + z)\n"
15173                "#define ffff(x, y) (x - y)",
15174                Style);
15175 
15176   verifyFormat("#define foo(x, y) (x + y)\n"
15177                "#define bar (5, 6)(2 + 2)",
15178                Style);
15179 
15180   verifyFormat("#define a 3\n"
15181                "#define bbbb 4\n"
15182                "#define ccc (5)\n"
15183                "#define f(x) (x * x)\n"
15184                "#define fff(x, y, z) (x * y + z)\n"
15185                "#define ffff(x, y) (x - y)",
15186                Style);
15187 
15188   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15189   verifyFormat("#define a    3\n"
15190                "#define bbbb 4\n"
15191                "#define ccc  (5)",
15192                Style);
15193 
15194   verifyFormat("#define f(x)         (x * x)\n"
15195                "#define fff(x, y, z) (x * y + z)\n"
15196                "#define ffff(x, y)   (x - y)",
15197                Style);
15198 
15199   verifyFormat("#define foo(x, y) (x + y)\n"
15200                "#define bar       (5, 6)(2 + 2)",
15201                Style);
15202 
15203   verifyFormat("#define a            3\n"
15204                "#define bbbb         4\n"
15205                "#define ccc          (5)\n"
15206                "#define f(x)         (x * x)\n"
15207                "#define fff(x, y, z) (x * y + z)\n"
15208                "#define ffff(x, y)   (x - y)",
15209                Style);
15210 
15211   verifyFormat("#define a         5\n"
15212                "#define foo(x, y) (x + y)\n"
15213                "#define CCC       (6)\n"
15214                "auto lambda = []() {\n"
15215                "  auto  ii = 0;\n"
15216                "  float j  = 0;\n"
15217                "  return 0;\n"
15218                "};\n"
15219                "int   i  = 0;\n"
15220                "float i2 = 0;\n"
15221                "auto  v  = type{\n"
15222                "    i = 1,   //\n"
15223                "    (i = 2), //\n"
15224                "    i = 3    //\n"
15225                "};",
15226                Style);
15227 
15228   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
15229   Style.ColumnLimit = 20;
15230 
15231   verifyFormat("#define a          \\\n"
15232                "  \"aabbbbbbbbbbbb\"\n"
15233                "#define D          \\\n"
15234                "  \"aabbbbbbbbbbbb\" \\\n"
15235                "  \"ccddeeeeeeeee\"\n"
15236                "#define B          \\\n"
15237                "  \"QQQQQQQQQQQQQ\"  \\\n"
15238                "  \"FFFFFFFFFFFFF\"  \\\n"
15239                "  \"LLLLLLLL\"\n",
15240                Style);
15241 
15242   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15243   verifyFormat("#define a          \\\n"
15244                "  \"aabbbbbbbbbbbb\"\n"
15245                "#define D          \\\n"
15246                "  \"aabbbbbbbbbbbb\" \\\n"
15247                "  \"ccddeeeeeeeee\"\n"
15248                "#define B          \\\n"
15249                "  \"QQQQQQQQQQQQQ\"  \\\n"
15250                "  \"FFFFFFFFFFFFF\"  \\\n"
15251                "  \"LLLLLLLL\"\n",
15252                Style);
15253 
15254   // Test across comments
15255   Style.MaxEmptyLinesToKeep = 10;
15256   Style.ReflowComments = false;
15257   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
15258   EXPECT_EQ("#define a    3\n"
15259             "// line comment\n"
15260             "#define bbbb 4\n"
15261             "#define ccc  (5)",
15262             format("#define a 3\n"
15263                    "// line comment\n"
15264                    "#define bbbb 4\n"
15265                    "#define ccc (5)",
15266                    Style));
15267 
15268   EXPECT_EQ("#define a    3\n"
15269             "/* block comment */\n"
15270             "#define bbbb 4\n"
15271             "#define ccc  (5)",
15272             format("#define a  3\n"
15273                    "/* block comment */\n"
15274                    "#define bbbb 4\n"
15275                    "#define ccc (5)",
15276                    Style));
15277 
15278   EXPECT_EQ("#define a    3\n"
15279             "/* multi-line *\n"
15280             " * block comment */\n"
15281             "#define bbbb 4\n"
15282             "#define ccc  (5)",
15283             format("#define a 3\n"
15284                    "/* multi-line *\n"
15285                    " * block comment */\n"
15286                    "#define bbbb 4\n"
15287                    "#define ccc (5)",
15288                    Style));
15289 
15290   EXPECT_EQ("#define a    3\n"
15291             "// multi-line line comment\n"
15292             "//\n"
15293             "#define bbbb 4\n"
15294             "#define ccc  (5)",
15295             format("#define a  3\n"
15296                    "// multi-line line comment\n"
15297                    "//\n"
15298                    "#define bbbb 4\n"
15299                    "#define ccc (5)",
15300                    Style));
15301 
15302   EXPECT_EQ("#define a 3\n"
15303             "// empty lines still break.\n"
15304             "\n"
15305             "#define bbbb 4\n"
15306             "#define ccc  (5)",
15307             format("#define a     3\n"
15308                    "// empty lines still break.\n"
15309                    "\n"
15310                    "#define bbbb     4\n"
15311                    "#define ccc  (5)",
15312                    Style));
15313 
15314   // Test across empty lines
15315   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
15316   EXPECT_EQ("#define a    3\n"
15317             "\n"
15318             "#define bbbb 4\n"
15319             "#define ccc  (5)",
15320             format("#define a 3\n"
15321                    "\n"
15322                    "#define bbbb 4\n"
15323                    "#define ccc (5)",
15324                    Style));
15325 
15326   EXPECT_EQ("#define a    3\n"
15327             "\n"
15328             "\n"
15329             "\n"
15330             "#define bbbb 4\n"
15331             "#define ccc  (5)",
15332             format("#define a        3\n"
15333                    "\n"
15334                    "\n"
15335                    "\n"
15336                    "#define bbbb 4\n"
15337                    "#define ccc (5)",
15338                    Style));
15339 
15340   EXPECT_EQ("#define a 3\n"
15341             "// comments should break alignment\n"
15342             "//\n"
15343             "#define bbbb 4\n"
15344             "#define ccc  (5)",
15345             format("#define a        3\n"
15346                    "// comments should break alignment\n"
15347                    "//\n"
15348                    "#define bbbb 4\n"
15349                    "#define ccc (5)",
15350                    Style));
15351 
15352   // Test across empty lines and comments
15353   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
15354   verifyFormat("#define a    3\n"
15355                "\n"
15356                "// line comment\n"
15357                "#define bbbb 4\n"
15358                "#define ccc  (5)",
15359                Style);
15360 
15361   EXPECT_EQ("#define a    3\n"
15362             "\n"
15363             "\n"
15364             "/* multi-line *\n"
15365             " * block comment */\n"
15366             "\n"
15367             "\n"
15368             "#define bbbb 4\n"
15369             "#define ccc  (5)",
15370             format("#define a 3\n"
15371                    "\n"
15372                    "\n"
15373                    "/* multi-line *\n"
15374                    " * block comment */\n"
15375                    "\n"
15376                    "\n"
15377                    "#define bbbb 4\n"
15378                    "#define ccc (5)",
15379                    Style));
15380 
15381   EXPECT_EQ("#define a    3\n"
15382             "\n"
15383             "\n"
15384             "/* multi-line *\n"
15385             " * block comment */\n"
15386             "\n"
15387             "\n"
15388             "#define bbbb 4\n"
15389             "#define ccc  (5)",
15390             format("#define a 3\n"
15391                    "\n"
15392                    "\n"
15393                    "/* multi-line *\n"
15394                    " * block comment */\n"
15395                    "\n"
15396                    "\n"
15397                    "#define bbbb 4\n"
15398                    "#define ccc       (5)",
15399                    Style));
15400 }
15401 
15402 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
15403   FormatStyle Alignment = getLLVMStyle();
15404   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15405   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
15406 
15407   Alignment.MaxEmptyLinesToKeep = 10;
15408   /* Test alignment across empty lines */
15409   EXPECT_EQ("int a           = 5;\n"
15410             "\n"
15411             "int oneTwoThree = 123;",
15412             format("int a       = 5;\n"
15413                    "\n"
15414                    "int oneTwoThree= 123;",
15415                    Alignment));
15416   EXPECT_EQ("int a           = 5;\n"
15417             "int one         = 1;\n"
15418             "\n"
15419             "int oneTwoThree = 123;",
15420             format("int a = 5;\n"
15421                    "int one = 1;\n"
15422                    "\n"
15423                    "int oneTwoThree = 123;",
15424                    Alignment));
15425   EXPECT_EQ("int a           = 5;\n"
15426             "int one         = 1;\n"
15427             "\n"
15428             "int oneTwoThree = 123;\n"
15429             "int oneTwo      = 12;",
15430             format("int a = 5;\n"
15431                    "int one = 1;\n"
15432                    "\n"
15433                    "int oneTwoThree = 123;\n"
15434                    "int oneTwo = 12;",
15435                    Alignment));
15436 
15437   /* Test across comments */
15438   EXPECT_EQ("int a = 5;\n"
15439             "/* block comment */\n"
15440             "int oneTwoThree = 123;",
15441             format("int a = 5;\n"
15442                    "/* block comment */\n"
15443                    "int oneTwoThree=123;",
15444                    Alignment));
15445 
15446   EXPECT_EQ("int a = 5;\n"
15447             "// line comment\n"
15448             "int oneTwoThree = 123;",
15449             format("int a = 5;\n"
15450                    "// line comment\n"
15451                    "int oneTwoThree=123;",
15452                    Alignment));
15453 
15454   /* Test across comments and newlines */
15455   EXPECT_EQ("int a = 5;\n"
15456             "\n"
15457             "/* block comment */\n"
15458             "int oneTwoThree = 123;",
15459             format("int a = 5;\n"
15460                    "\n"
15461                    "/* block comment */\n"
15462                    "int oneTwoThree=123;",
15463                    Alignment));
15464 
15465   EXPECT_EQ("int a = 5;\n"
15466             "\n"
15467             "// line comment\n"
15468             "int oneTwoThree = 123;",
15469             format("int a = 5;\n"
15470                    "\n"
15471                    "// line comment\n"
15472                    "int oneTwoThree=123;",
15473                    Alignment));
15474 }
15475 
15476 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
15477   FormatStyle Alignment = getLLVMStyle();
15478   Alignment.AlignConsecutiveDeclarations =
15479       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15480   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15481 
15482   Alignment.MaxEmptyLinesToKeep = 10;
15483   /* Test alignment across empty lines */
15484   EXPECT_EQ("int         a = 5;\n"
15485             "\n"
15486             "float const oneTwoThree = 123;",
15487             format("int a = 5;\n"
15488                    "\n"
15489                    "float const oneTwoThree = 123;",
15490                    Alignment));
15491   EXPECT_EQ("int         a = 5;\n"
15492             "float const one = 1;\n"
15493             "\n"
15494             "int         oneTwoThree = 123;",
15495             format("int a = 5;\n"
15496                    "float const one = 1;\n"
15497                    "\n"
15498                    "int oneTwoThree = 123;",
15499                    Alignment));
15500 
15501   /* Test across comments */
15502   EXPECT_EQ("float const a = 5;\n"
15503             "/* block comment */\n"
15504             "int         oneTwoThree = 123;",
15505             format("float const a = 5;\n"
15506                    "/* block comment */\n"
15507                    "int oneTwoThree=123;",
15508                    Alignment));
15509 
15510   EXPECT_EQ("float const a = 5;\n"
15511             "// line comment\n"
15512             "int         oneTwoThree = 123;",
15513             format("float const a = 5;\n"
15514                    "// line comment\n"
15515                    "int oneTwoThree=123;",
15516                    Alignment));
15517 
15518   /* Test across comments and newlines */
15519   EXPECT_EQ("float const a = 5;\n"
15520             "\n"
15521             "/* block comment */\n"
15522             "int         oneTwoThree = 123;",
15523             format("float const a = 5;\n"
15524                    "\n"
15525                    "/* block comment */\n"
15526                    "int         oneTwoThree=123;",
15527                    Alignment));
15528 
15529   EXPECT_EQ("float const a = 5;\n"
15530             "\n"
15531             "// line comment\n"
15532             "int         oneTwoThree = 123;",
15533             format("float const a = 5;\n"
15534                    "\n"
15535                    "// line comment\n"
15536                    "int oneTwoThree=123;",
15537                    Alignment));
15538 }
15539 
15540 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
15541   FormatStyle Alignment = getLLVMStyle();
15542   Alignment.AlignConsecutiveBitFields =
15543       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15544 
15545   Alignment.MaxEmptyLinesToKeep = 10;
15546   /* Test alignment across empty lines */
15547   EXPECT_EQ("int a            : 5;\n"
15548             "\n"
15549             "int longbitfield : 6;",
15550             format("int a : 5;\n"
15551                    "\n"
15552                    "int longbitfield : 6;",
15553                    Alignment));
15554   EXPECT_EQ("int a            : 5;\n"
15555             "int one          : 1;\n"
15556             "\n"
15557             "int longbitfield : 6;",
15558             format("int a : 5;\n"
15559                    "int one : 1;\n"
15560                    "\n"
15561                    "int longbitfield : 6;",
15562                    Alignment));
15563 
15564   /* Test across comments */
15565   EXPECT_EQ("int a            : 5;\n"
15566             "/* block comment */\n"
15567             "int longbitfield : 6;",
15568             format("int a : 5;\n"
15569                    "/* block comment */\n"
15570                    "int longbitfield : 6;",
15571                    Alignment));
15572   EXPECT_EQ("int a            : 5;\n"
15573             "int one          : 1;\n"
15574             "// line comment\n"
15575             "int longbitfield : 6;",
15576             format("int a : 5;\n"
15577                    "int one : 1;\n"
15578                    "// line comment\n"
15579                    "int longbitfield : 6;",
15580                    Alignment));
15581 
15582   /* Test across comments and newlines */
15583   EXPECT_EQ("int a            : 5;\n"
15584             "/* block comment */\n"
15585             "\n"
15586             "int longbitfield : 6;",
15587             format("int a : 5;\n"
15588                    "/* block comment */\n"
15589                    "\n"
15590                    "int longbitfield : 6;",
15591                    Alignment));
15592   EXPECT_EQ("int a            : 5;\n"
15593             "int one          : 1;\n"
15594             "\n"
15595             "// line comment\n"
15596             "\n"
15597             "int longbitfield : 6;",
15598             format("int a : 5;\n"
15599                    "int one : 1;\n"
15600                    "\n"
15601                    "// line comment \n"
15602                    "\n"
15603                    "int longbitfield : 6;",
15604                    Alignment));
15605 }
15606 
15607 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
15608   FormatStyle Alignment = getLLVMStyle();
15609   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15610   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
15611 
15612   Alignment.MaxEmptyLinesToKeep = 10;
15613   /* Test alignment across empty lines */
15614   EXPECT_EQ("int a = 5;\n"
15615             "\n"
15616             "int oneTwoThree = 123;",
15617             format("int a       = 5;\n"
15618                    "\n"
15619                    "int oneTwoThree= 123;",
15620                    Alignment));
15621   EXPECT_EQ("int a   = 5;\n"
15622             "int one = 1;\n"
15623             "\n"
15624             "int oneTwoThree = 123;",
15625             format("int a = 5;\n"
15626                    "int one = 1;\n"
15627                    "\n"
15628                    "int oneTwoThree = 123;",
15629                    Alignment));
15630 
15631   /* Test across comments */
15632   EXPECT_EQ("int a           = 5;\n"
15633             "/* block comment */\n"
15634             "int oneTwoThree = 123;",
15635             format("int a = 5;\n"
15636                    "/* block comment */\n"
15637                    "int oneTwoThree=123;",
15638                    Alignment));
15639 
15640   EXPECT_EQ("int a           = 5;\n"
15641             "// line comment\n"
15642             "int oneTwoThree = 123;",
15643             format("int a = 5;\n"
15644                    "// line comment\n"
15645                    "int oneTwoThree=123;",
15646                    Alignment));
15647 
15648   EXPECT_EQ("int a           = 5;\n"
15649             "/*\n"
15650             " * multi-line block comment\n"
15651             " */\n"
15652             "int oneTwoThree = 123;",
15653             format("int a = 5;\n"
15654                    "/*\n"
15655                    " * multi-line block comment\n"
15656                    " */\n"
15657                    "int oneTwoThree=123;",
15658                    Alignment));
15659 
15660   EXPECT_EQ("int a           = 5;\n"
15661             "//\n"
15662             "// multi-line line comment\n"
15663             "//\n"
15664             "int oneTwoThree = 123;",
15665             format("int a = 5;\n"
15666                    "//\n"
15667                    "// multi-line line comment\n"
15668                    "//\n"
15669                    "int oneTwoThree=123;",
15670                    Alignment));
15671 
15672   /* Test across comments and newlines */
15673   EXPECT_EQ("int a = 5;\n"
15674             "\n"
15675             "/* block comment */\n"
15676             "int oneTwoThree = 123;",
15677             format("int a = 5;\n"
15678                    "\n"
15679                    "/* block comment */\n"
15680                    "int oneTwoThree=123;",
15681                    Alignment));
15682 
15683   EXPECT_EQ("int a = 5;\n"
15684             "\n"
15685             "// line comment\n"
15686             "int oneTwoThree = 123;",
15687             format("int a = 5;\n"
15688                    "\n"
15689                    "// line comment\n"
15690                    "int oneTwoThree=123;",
15691                    Alignment));
15692 }
15693 
15694 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
15695   FormatStyle Alignment = getLLVMStyle();
15696   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15697   Alignment.AlignConsecutiveAssignments =
15698       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15699   verifyFormat("int a           = 5;\n"
15700                "int oneTwoThree = 123;",
15701                Alignment);
15702   verifyFormat("int a           = method();\n"
15703                "int oneTwoThree = 133;",
15704                Alignment);
15705   verifyFormat("a &= 5;\n"
15706                "bcd *= 5;\n"
15707                "ghtyf += 5;\n"
15708                "dvfvdb -= 5;\n"
15709                "a /= 5;\n"
15710                "vdsvsv %= 5;\n"
15711                "sfdbddfbdfbb ^= 5;\n"
15712                "dvsdsv |= 5;\n"
15713                "int dsvvdvsdvvv = 123;",
15714                Alignment);
15715   verifyFormat("int i = 1, j = 10;\n"
15716                "something = 2000;",
15717                Alignment);
15718   verifyFormat("something = 2000;\n"
15719                "int i = 1, j = 10;\n",
15720                Alignment);
15721   verifyFormat("something = 2000;\n"
15722                "another   = 911;\n"
15723                "int i = 1, j = 10;\n"
15724                "oneMore = 1;\n"
15725                "i       = 2;",
15726                Alignment);
15727   verifyFormat("int a   = 5;\n"
15728                "int one = 1;\n"
15729                "method();\n"
15730                "int oneTwoThree = 123;\n"
15731                "int oneTwo      = 12;",
15732                Alignment);
15733   verifyFormat("int oneTwoThree = 123;\n"
15734                "int oneTwo      = 12;\n"
15735                "method();\n",
15736                Alignment);
15737   verifyFormat("int oneTwoThree = 123; // comment\n"
15738                "int oneTwo      = 12;  // comment",
15739                Alignment);
15740 
15741   // Bug 25167
15742   /* Uncomment when fixed
15743     verifyFormat("#if A\n"
15744                  "#else\n"
15745                  "int aaaaaaaa = 12;\n"
15746                  "#endif\n"
15747                  "#if B\n"
15748                  "#else\n"
15749                  "int a = 12;\n"
15750                  "#endif\n",
15751                  Alignment);
15752     verifyFormat("enum foo {\n"
15753                  "#if A\n"
15754                  "#else\n"
15755                  "  aaaaaaaa = 12;\n"
15756                  "#endif\n"
15757                  "#if B\n"
15758                  "#else\n"
15759                  "  a = 12;\n"
15760                  "#endif\n"
15761                  "};\n",
15762                  Alignment);
15763   */
15764 
15765   Alignment.MaxEmptyLinesToKeep = 10;
15766   /* Test alignment across empty lines */
15767   EXPECT_EQ("int a           = 5;\n"
15768             "\n"
15769             "int oneTwoThree = 123;",
15770             format("int a       = 5;\n"
15771                    "\n"
15772                    "int oneTwoThree= 123;",
15773                    Alignment));
15774   EXPECT_EQ("int a           = 5;\n"
15775             "int one         = 1;\n"
15776             "\n"
15777             "int oneTwoThree = 123;",
15778             format("int a = 5;\n"
15779                    "int one = 1;\n"
15780                    "\n"
15781                    "int oneTwoThree = 123;",
15782                    Alignment));
15783   EXPECT_EQ("int a           = 5;\n"
15784             "int one         = 1;\n"
15785             "\n"
15786             "int oneTwoThree = 123;\n"
15787             "int oneTwo      = 12;",
15788             format("int a = 5;\n"
15789                    "int one = 1;\n"
15790                    "\n"
15791                    "int oneTwoThree = 123;\n"
15792                    "int oneTwo = 12;",
15793                    Alignment));
15794 
15795   /* Test across comments */
15796   EXPECT_EQ("int a           = 5;\n"
15797             "/* block comment */\n"
15798             "int oneTwoThree = 123;",
15799             format("int a = 5;\n"
15800                    "/* block comment */\n"
15801                    "int oneTwoThree=123;",
15802                    Alignment));
15803 
15804   EXPECT_EQ("int a           = 5;\n"
15805             "// line comment\n"
15806             "int oneTwoThree = 123;",
15807             format("int a = 5;\n"
15808                    "// line comment\n"
15809                    "int oneTwoThree=123;",
15810                    Alignment));
15811 
15812   /* Test across comments and newlines */
15813   EXPECT_EQ("int a           = 5;\n"
15814             "\n"
15815             "/* block comment */\n"
15816             "int oneTwoThree = 123;",
15817             format("int a = 5;\n"
15818                    "\n"
15819                    "/* block comment */\n"
15820                    "int oneTwoThree=123;",
15821                    Alignment));
15822 
15823   EXPECT_EQ("int a           = 5;\n"
15824             "\n"
15825             "// line comment\n"
15826             "int oneTwoThree = 123;",
15827             format("int a = 5;\n"
15828                    "\n"
15829                    "// line comment\n"
15830                    "int oneTwoThree=123;",
15831                    Alignment));
15832 
15833   EXPECT_EQ("int a           = 5;\n"
15834             "//\n"
15835             "// multi-line line comment\n"
15836             "//\n"
15837             "int oneTwoThree = 123;",
15838             format("int a = 5;\n"
15839                    "//\n"
15840                    "// multi-line line comment\n"
15841                    "//\n"
15842                    "int oneTwoThree=123;",
15843                    Alignment));
15844 
15845   EXPECT_EQ("int a           = 5;\n"
15846             "/*\n"
15847             " *  multi-line block comment\n"
15848             " */\n"
15849             "int oneTwoThree = 123;",
15850             format("int a = 5;\n"
15851                    "/*\n"
15852                    " *  multi-line block comment\n"
15853                    " */\n"
15854                    "int oneTwoThree=123;",
15855                    Alignment));
15856 
15857   EXPECT_EQ("int a           = 5;\n"
15858             "\n"
15859             "/* block comment */\n"
15860             "\n"
15861             "\n"
15862             "\n"
15863             "int oneTwoThree = 123;",
15864             format("int a = 5;\n"
15865                    "\n"
15866                    "/* block comment */\n"
15867                    "\n"
15868                    "\n"
15869                    "\n"
15870                    "int oneTwoThree=123;",
15871                    Alignment));
15872 
15873   EXPECT_EQ("int a           = 5;\n"
15874             "\n"
15875             "// line comment\n"
15876             "\n"
15877             "\n"
15878             "\n"
15879             "int oneTwoThree = 123;",
15880             format("int a = 5;\n"
15881                    "\n"
15882                    "// line comment\n"
15883                    "\n"
15884                    "\n"
15885                    "\n"
15886                    "int oneTwoThree=123;",
15887                    Alignment));
15888 
15889   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
15890   verifyFormat("#define A \\\n"
15891                "  int aaaa       = 12; \\\n"
15892                "  int b          = 23; \\\n"
15893                "  int ccc        = 234; \\\n"
15894                "  int dddddddddd = 2345;",
15895                Alignment);
15896   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
15897   verifyFormat("#define A               \\\n"
15898                "  int aaaa       = 12;  \\\n"
15899                "  int b          = 23;  \\\n"
15900                "  int ccc        = 234; \\\n"
15901                "  int dddddddddd = 2345;",
15902                Alignment);
15903   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
15904   verifyFormat("#define A                                                      "
15905                "                \\\n"
15906                "  int aaaa       = 12;                                         "
15907                "                \\\n"
15908                "  int b          = 23;                                         "
15909                "                \\\n"
15910                "  int ccc        = 234;                                        "
15911                "                \\\n"
15912                "  int dddddddddd = 2345;",
15913                Alignment);
15914   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
15915                "k = 4, int l = 5,\n"
15916                "                  int m = 6) {\n"
15917                "  int j      = 10;\n"
15918                "  otherThing = 1;\n"
15919                "}",
15920                Alignment);
15921   verifyFormat("void SomeFunction(int parameter = 0) {\n"
15922                "  int i   = 1;\n"
15923                "  int j   = 2;\n"
15924                "  int big = 10000;\n"
15925                "}",
15926                Alignment);
15927   verifyFormat("class C {\n"
15928                "public:\n"
15929                "  int i            = 1;\n"
15930                "  virtual void f() = 0;\n"
15931                "};",
15932                Alignment);
15933   verifyFormat("int i = 1;\n"
15934                "if (SomeType t = getSomething()) {\n"
15935                "}\n"
15936                "int j   = 2;\n"
15937                "int big = 10000;",
15938                Alignment);
15939   verifyFormat("int j = 7;\n"
15940                "for (int k = 0; k < N; ++k) {\n"
15941                "}\n"
15942                "int j   = 2;\n"
15943                "int big = 10000;\n"
15944                "}",
15945                Alignment);
15946   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15947   verifyFormat("int i = 1;\n"
15948                "LooooooooooongType loooooooooooooooooooooongVariable\n"
15949                "    = someLooooooooooooooooongFunction();\n"
15950                "int j = 2;",
15951                Alignment);
15952   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
15953   verifyFormat("int i = 1;\n"
15954                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
15955                "    someLooooooooooooooooongFunction();\n"
15956                "int j = 2;",
15957                Alignment);
15958 
15959   verifyFormat("auto lambda = []() {\n"
15960                "  auto i = 0;\n"
15961                "  return 0;\n"
15962                "};\n"
15963                "int i  = 0;\n"
15964                "auto v = type{\n"
15965                "    i = 1,   //\n"
15966                "    (i = 2), //\n"
15967                "    i = 3    //\n"
15968                "};",
15969                Alignment);
15970 
15971   verifyFormat(
15972       "int i      = 1;\n"
15973       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
15974       "                          loooooooooooooooooooooongParameterB);\n"
15975       "int j      = 2;",
15976       Alignment);
15977 
15978   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
15979                "          typename B   = very_long_type_name_1,\n"
15980                "          typename T_2 = very_long_type_name_2>\n"
15981                "auto foo() {}\n",
15982                Alignment);
15983   verifyFormat("int a, b = 1;\n"
15984                "int c  = 2;\n"
15985                "int dd = 3;\n",
15986                Alignment);
15987   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
15988                "float b[1][] = {{3.f}};\n",
15989                Alignment);
15990   verifyFormat("for (int i = 0; i < 1; i++)\n"
15991                "  int x = 1;\n",
15992                Alignment);
15993   verifyFormat("for (i = 0; i < 1; i++)\n"
15994                "  x = 1;\n"
15995                "y = 1;\n",
15996                Alignment);
15997 
15998   Alignment.ReflowComments = true;
15999   Alignment.ColumnLimit = 50;
16000   EXPECT_EQ("int x   = 0;\n"
16001             "int yy  = 1; /// specificlennospace\n"
16002             "int zzz = 2;\n",
16003             format("int x   = 0;\n"
16004                    "int yy  = 1; ///specificlennospace\n"
16005                    "int zzz = 2;\n",
16006                    Alignment));
16007 }
16008 
16009 TEST_F(FormatTest, AlignConsecutiveAssignments) {
16010   FormatStyle Alignment = getLLVMStyle();
16011   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16012   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16013   verifyFormat("int a = 5;\n"
16014                "int oneTwoThree = 123;",
16015                Alignment);
16016   verifyFormat("int a = 5;\n"
16017                "int oneTwoThree = 123;",
16018                Alignment);
16019 
16020   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16021   verifyFormat("int a           = 5;\n"
16022                "int oneTwoThree = 123;",
16023                Alignment);
16024   verifyFormat("int a           = method();\n"
16025                "int oneTwoThree = 133;",
16026                Alignment);
16027   verifyFormat("a &= 5;\n"
16028                "bcd *= 5;\n"
16029                "ghtyf += 5;\n"
16030                "dvfvdb -= 5;\n"
16031                "a /= 5;\n"
16032                "vdsvsv %= 5;\n"
16033                "sfdbddfbdfbb ^= 5;\n"
16034                "dvsdsv |= 5;\n"
16035                "int dsvvdvsdvvv = 123;",
16036                Alignment);
16037   verifyFormat("int i = 1, j = 10;\n"
16038                "something = 2000;",
16039                Alignment);
16040   verifyFormat("something = 2000;\n"
16041                "int i = 1, j = 10;\n",
16042                Alignment);
16043   verifyFormat("something = 2000;\n"
16044                "another   = 911;\n"
16045                "int i = 1, j = 10;\n"
16046                "oneMore = 1;\n"
16047                "i       = 2;",
16048                Alignment);
16049   verifyFormat("int a   = 5;\n"
16050                "int one = 1;\n"
16051                "method();\n"
16052                "int oneTwoThree = 123;\n"
16053                "int oneTwo      = 12;",
16054                Alignment);
16055   verifyFormat("int oneTwoThree = 123;\n"
16056                "int oneTwo      = 12;\n"
16057                "method();\n",
16058                Alignment);
16059   verifyFormat("int oneTwoThree = 123; // comment\n"
16060                "int oneTwo      = 12;  // comment",
16061                Alignment);
16062 
16063   // Bug 25167
16064   /* Uncomment when fixed
16065     verifyFormat("#if A\n"
16066                  "#else\n"
16067                  "int aaaaaaaa = 12;\n"
16068                  "#endif\n"
16069                  "#if B\n"
16070                  "#else\n"
16071                  "int a = 12;\n"
16072                  "#endif\n",
16073                  Alignment);
16074     verifyFormat("enum foo {\n"
16075                  "#if A\n"
16076                  "#else\n"
16077                  "  aaaaaaaa = 12;\n"
16078                  "#endif\n"
16079                  "#if B\n"
16080                  "#else\n"
16081                  "  a = 12;\n"
16082                  "#endif\n"
16083                  "};\n",
16084                  Alignment);
16085   */
16086 
16087   EXPECT_EQ("int a = 5;\n"
16088             "\n"
16089             "int oneTwoThree = 123;",
16090             format("int a       = 5;\n"
16091                    "\n"
16092                    "int oneTwoThree= 123;",
16093                    Alignment));
16094   EXPECT_EQ("int a   = 5;\n"
16095             "int one = 1;\n"
16096             "\n"
16097             "int oneTwoThree = 123;",
16098             format("int a = 5;\n"
16099                    "int one = 1;\n"
16100                    "\n"
16101                    "int oneTwoThree = 123;",
16102                    Alignment));
16103   EXPECT_EQ("int a   = 5;\n"
16104             "int one = 1;\n"
16105             "\n"
16106             "int oneTwoThree = 123;\n"
16107             "int oneTwo      = 12;",
16108             format("int a = 5;\n"
16109                    "int one = 1;\n"
16110                    "\n"
16111                    "int oneTwoThree = 123;\n"
16112                    "int oneTwo = 12;",
16113                    Alignment));
16114   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16115   verifyFormat("#define A \\\n"
16116                "  int aaaa       = 12; \\\n"
16117                "  int b          = 23; \\\n"
16118                "  int ccc        = 234; \\\n"
16119                "  int dddddddddd = 2345;",
16120                Alignment);
16121   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16122   verifyFormat("#define A               \\\n"
16123                "  int aaaa       = 12;  \\\n"
16124                "  int b          = 23;  \\\n"
16125                "  int ccc        = 234; \\\n"
16126                "  int dddddddddd = 2345;",
16127                Alignment);
16128   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16129   verifyFormat("#define A                                                      "
16130                "                \\\n"
16131                "  int aaaa       = 12;                                         "
16132                "                \\\n"
16133                "  int b          = 23;                                         "
16134                "                \\\n"
16135                "  int ccc        = 234;                                        "
16136                "                \\\n"
16137                "  int dddddddddd = 2345;",
16138                Alignment);
16139   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16140                "k = 4, int l = 5,\n"
16141                "                  int m = 6) {\n"
16142                "  int j      = 10;\n"
16143                "  otherThing = 1;\n"
16144                "}",
16145                Alignment);
16146   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16147                "  int i   = 1;\n"
16148                "  int j   = 2;\n"
16149                "  int big = 10000;\n"
16150                "}",
16151                Alignment);
16152   verifyFormat("class C {\n"
16153                "public:\n"
16154                "  int i            = 1;\n"
16155                "  virtual void f() = 0;\n"
16156                "};",
16157                Alignment);
16158   verifyFormat("int i = 1;\n"
16159                "if (SomeType t = getSomething()) {\n"
16160                "}\n"
16161                "int j   = 2;\n"
16162                "int big = 10000;",
16163                Alignment);
16164   verifyFormat("int j = 7;\n"
16165                "for (int k = 0; k < N; ++k) {\n"
16166                "}\n"
16167                "int j   = 2;\n"
16168                "int big = 10000;\n"
16169                "}",
16170                Alignment);
16171   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16172   verifyFormat("int i = 1;\n"
16173                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16174                "    = someLooooooooooooooooongFunction();\n"
16175                "int j = 2;",
16176                Alignment);
16177   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16178   verifyFormat("int i = 1;\n"
16179                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16180                "    someLooooooooooooooooongFunction();\n"
16181                "int j = 2;",
16182                Alignment);
16183 
16184   verifyFormat("auto lambda = []() {\n"
16185                "  auto i = 0;\n"
16186                "  return 0;\n"
16187                "};\n"
16188                "int i  = 0;\n"
16189                "auto v = type{\n"
16190                "    i = 1,   //\n"
16191                "    (i = 2), //\n"
16192                "    i = 3    //\n"
16193                "};",
16194                Alignment);
16195 
16196   verifyFormat(
16197       "int i      = 1;\n"
16198       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16199       "                          loooooooooooooooooooooongParameterB);\n"
16200       "int j      = 2;",
16201       Alignment);
16202 
16203   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
16204                "          typename B   = very_long_type_name_1,\n"
16205                "          typename T_2 = very_long_type_name_2>\n"
16206                "auto foo() {}\n",
16207                Alignment);
16208   verifyFormat("int a, b = 1;\n"
16209                "int c  = 2;\n"
16210                "int dd = 3;\n",
16211                Alignment);
16212   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
16213                "float b[1][] = {{3.f}};\n",
16214                Alignment);
16215   verifyFormat("for (int i = 0; i < 1; i++)\n"
16216                "  int x = 1;\n",
16217                Alignment);
16218   verifyFormat("for (i = 0; i < 1; i++)\n"
16219                "  x = 1;\n"
16220                "y = 1;\n",
16221                Alignment);
16222 
16223   Alignment.ReflowComments = true;
16224   Alignment.ColumnLimit = 50;
16225   EXPECT_EQ("int x   = 0;\n"
16226             "int yy  = 1; /// specificlennospace\n"
16227             "int zzz = 2;\n",
16228             format("int x   = 0;\n"
16229                    "int yy  = 1; ///specificlennospace\n"
16230                    "int zzz = 2;\n",
16231                    Alignment));
16232 }
16233 
16234 TEST_F(FormatTest, AlignConsecutiveBitFields) {
16235   FormatStyle Alignment = getLLVMStyle();
16236   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
16237   verifyFormat("int const a     : 5;\n"
16238                "int oneTwoThree : 23;",
16239                Alignment);
16240 
16241   // Initializers are allowed starting with c++2a
16242   verifyFormat("int const a     : 5 = 1;\n"
16243                "int oneTwoThree : 23 = 0;",
16244                Alignment);
16245 
16246   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16247   verifyFormat("int const a           : 5;\n"
16248                "int       oneTwoThree : 23;",
16249                Alignment);
16250 
16251   verifyFormat("int const a           : 5;  // comment\n"
16252                "int       oneTwoThree : 23; // comment",
16253                Alignment);
16254 
16255   verifyFormat("int const a           : 5 = 1;\n"
16256                "int       oneTwoThree : 23 = 0;",
16257                Alignment);
16258 
16259   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16260   verifyFormat("int const a           : 5  = 1;\n"
16261                "int       oneTwoThree : 23 = 0;",
16262                Alignment);
16263   verifyFormat("int const a           : 5  = {1};\n"
16264                "int       oneTwoThree : 23 = 0;",
16265                Alignment);
16266 
16267   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
16268   verifyFormat("int const a          :5;\n"
16269                "int       oneTwoThree:23;",
16270                Alignment);
16271 
16272   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
16273   verifyFormat("int const a           :5;\n"
16274                "int       oneTwoThree :23;",
16275                Alignment);
16276 
16277   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
16278   verifyFormat("int const a          : 5;\n"
16279                "int       oneTwoThree: 23;",
16280                Alignment);
16281 
16282   // Known limitations: ':' is only recognized as a bitfield colon when
16283   // followed by a number.
16284   /*
16285   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
16286                "int a           : 5;",
16287                Alignment);
16288   */
16289 }
16290 
16291 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
16292   FormatStyle Alignment = getLLVMStyle();
16293   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16294   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16295   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16296   verifyFormat("float const a = 5;\n"
16297                "int oneTwoThree = 123;",
16298                Alignment);
16299   verifyFormat("int a = 5;\n"
16300                "float const oneTwoThree = 123;",
16301                Alignment);
16302 
16303   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16304   verifyFormat("float const a = 5;\n"
16305                "int         oneTwoThree = 123;",
16306                Alignment);
16307   verifyFormat("int         a = method();\n"
16308                "float const oneTwoThree = 133;",
16309                Alignment);
16310   verifyFormat("int i = 1, j = 10;\n"
16311                "something = 2000;",
16312                Alignment);
16313   verifyFormat("something = 2000;\n"
16314                "int i = 1, j = 10;\n",
16315                Alignment);
16316   verifyFormat("float      something = 2000;\n"
16317                "double     another = 911;\n"
16318                "int        i = 1, j = 10;\n"
16319                "const int *oneMore = 1;\n"
16320                "unsigned   i = 2;",
16321                Alignment);
16322   verifyFormat("float a = 5;\n"
16323                "int   one = 1;\n"
16324                "method();\n"
16325                "const double       oneTwoThree = 123;\n"
16326                "const unsigned int oneTwo = 12;",
16327                Alignment);
16328   verifyFormat("int      oneTwoThree{0}; // comment\n"
16329                "unsigned oneTwo;         // comment",
16330                Alignment);
16331   verifyFormat("unsigned int       *a;\n"
16332                "int                *b;\n"
16333                "unsigned int Const *c;\n"
16334                "unsigned int const *d;\n"
16335                "unsigned int Const &e;\n"
16336                "unsigned int const &f;",
16337                Alignment);
16338   verifyFormat("Const unsigned int *c;\n"
16339                "const unsigned int *d;\n"
16340                "Const unsigned int &e;\n"
16341                "const unsigned int &f;\n"
16342                "const unsigned      g;\n"
16343                "Const unsigned      h;",
16344                Alignment);
16345   EXPECT_EQ("float const a = 5;\n"
16346             "\n"
16347             "int oneTwoThree = 123;",
16348             format("float const   a = 5;\n"
16349                    "\n"
16350                    "int           oneTwoThree= 123;",
16351                    Alignment));
16352   EXPECT_EQ("float a = 5;\n"
16353             "int   one = 1;\n"
16354             "\n"
16355             "unsigned oneTwoThree = 123;",
16356             format("float    a = 5;\n"
16357                    "int      one = 1;\n"
16358                    "\n"
16359                    "unsigned oneTwoThree = 123;",
16360                    Alignment));
16361   EXPECT_EQ("float a = 5;\n"
16362             "int   one = 1;\n"
16363             "\n"
16364             "unsigned oneTwoThree = 123;\n"
16365             "int      oneTwo = 12;",
16366             format("float    a = 5;\n"
16367                    "int one = 1;\n"
16368                    "\n"
16369                    "unsigned oneTwoThree = 123;\n"
16370                    "int oneTwo = 12;",
16371                    Alignment));
16372   // Function prototype alignment
16373   verifyFormat("int    a();\n"
16374                "double b();",
16375                Alignment);
16376   verifyFormat("int    a(int x);\n"
16377                "double b();",
16378                Alignment);
16379   unsigned OldColumnLimit = Alignment.ColumnLimit;
16380   // We need to set ColumnLimit to zero, in order to stress nested alignments,
16381   // otherwise the function parameters will be re-flowed onto a single line.
16382   Alignment.ColumnLimit = 0;
16383   EXPECT_EQ("int    a(int   x,\n"
16384             "         float y);\n"
16385             "double b(int    x,\n"
16386             "         double y);",
16387             format("int a(int x,\n"
16388                    " float y);\n"
16389                    "double b(int x,\n"
16390                    " double y);",
16391                    Alignment));
16392   // This ensures that function parameters of function declarations are
16393   // correctly indented when their owning functions are indented.
16394   // The failure case here is for 'double y' to not be indented enough.
16395   EXPECT_EQ("double a(int x);\n"
16396             "int    b(int    y,\n"
16397             "         double z);",
16398             format("double a(int x);\n"
16399                    "int b(int y,\n"
16400                    " double z);",
16401                    Alignment));
16402   // Set ColumnLimit low so that we induce wrapping immediately after
16403   // the function name and opening paren.
16404   Alignment.ColumnLimit = 13;
16405   verifyFormat("int function(\n"
16406                "    int  x,\n"
16407                "    bool y);",
16408                Alignment);
16409   Alignment.ColumnLimit = OldColumnLimit;
16410   // Ensure function pointers don't screw up recursive alignment
16411   verifyFormat("int    a(int x, void (*fp)(int y));\n"
16412                "double b();",
16413                Alignment);
16414   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16415   // Ensure recursive alignment is broken by function braces, so that the
16416   // "a = 1" does not align with subsequent assignments inside the function
16417   // body.
16418   verifyFormat("int func(int a = 1) {\n"
16419                "  int b  = 2;\n"
16420                "  int cc = 3;\n"
16421                "}",
16422                Alignment);
16423   verifyFormat("float      something = 2000;\n"
16424                "double     another   = 911;\n"
16425                "int        i = 1, j = 10;\n"
16426                "const int *oneMore = 1;\n"
16427                "unsigned   i       = 2;",
16428                Alignment);
16429   verifyFormat("int      oneTwoThree = {0}; // comment\n"
16430                "unsigned oneTwo      = 0;   // comment",
16431                Alignment);
16432   // Make sure that scope is correctly tracked, in the absence of braces
16433   verifyFormat("for (int i = 0; i < n; i++)\n"
16434                "  j = i;\n"
16435                "double x = 1;\n",
16436                Alignment);
16437   verifyFormat("if (int i = 0)\n"
16438                "  j = i;\n"
16439                "double x = 1;\n",
16440                Alignment);
16441   // Ensure operator[] and operator() are comprehended
16442   verifyFormat("struct test {\n"
16443                "  long long int foo();\n"
16444                "  int           operator[](int a);\n"
16445                "  double        bar();\n"
16446                "};\n",
16447                Alignment);
16448   verifyFormat("struct test {\n"
16449                "  long long int foo();\n"
16450                "  int           operator()(int a);\n"
16451                "  double        bar();\n"
16452                "};\n",
16453                Alignment);
16454   // http://llvm.org/PR52914
16455   verifyFormat("char *a[]     = {\"a\", // comment\n"
16456                "                 \"bb\"};\n"
16457                "int   bbbbbbb = 0;",
16458                Alignment);
16459 
16460   // PAS_Right
16461   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16462             "  int const i   = 1;\n"
16463             "  int      *j   = 2;\n"
16464             "  int       big = 10000;\n"
16465             "\n"
16466             "  unsigned oneTwoThree = 123;\n"
16467             "  int      oneTwo      = 12;\n"
16468             "  method();\n"
16469             "  float k  = 2;\n"
16470             "  int   ll = 10000;\n"
16471             "}",
16472             format("void SomeFunction(int parameter= 0) {\n"
16473                    " int const  i= 1;\n"
16474                    "  int *j=2;\n"
16475                    " int big  =  10000;\n"
16476                    "\n"
16477                    "unsigned oneTwoThree  =123;\n"
16478                    "int oneTwo = 12;\n"
16479                    "  method();\n"
16480                    "float k= 2;\n"
16481                    "int ll=10000;\n"
16482                    "}",
16483                    Alignment));
16484   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16485             "  int const i   = 1;\n"
16486             "  int     **j   = 2, ***k;\n"
16487             "  int      &k   = i;\n"
16488             "  int     &&l   = i + j;\n"
16489             "  int       big = 10000;\n"
16490             "\n"
16491             "  unsigned oneTwoThree = 123;\n"
16492             "  int      oneTwo      = 12;\n"
16493             "  method();\n"
16494             "  float k  = 2;\n"
16495             "  int   ll = 10000;\n"
16496             "}",
16497             format("void SomeFunction(int parameter= 0) {\n"
16498                    " int const  i= 1;\n"
16499                    "  int **j=2,***k;\n"
16500                    "int &k=i;\n"
16501                    "int &&l=i+j;\n"
16502                    " int big  =  10000;\n"
16503                    "\n"
16504                    "unsigned oneTwoThree  =123;\n"
16505                    "int oneTwo = 12;\n"
16506                    "  method();\n"
16507                    "float k= 2;\n"
16508                    "int ll=10000;\n"
16509                    "}",
16510                    Alignment));
16511   // variables are aligned at their name, pointers are at the right most
16512   // position
16513   verifyFormat("int   *a;\n"
16514                "int  **b;\n"
16515                "int ***c;\n"
16516                "int    foobar;\n",
16517                Alignment);
16518 
16519   // PAS_Left
16520   FormatStyle AlignmentLeft = Alignment;
16521   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
16522   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16523             "  int const i   = 1;\n"
16524             "  int*      j   = 2;\n"
16525             "  int       big = 10000;\n"
16526             "\n"
16527             "  unsigned oneTwoThree = 123;\n"
16528             "  int      oneTwo      = 12;\n"
16529             "  method();\n"
16530             "  float k  = 2;\n"
16531             "  int   ll = 10000;\n"
16532             "}",
16533             format("void SomeFunction(int parameter= 0) {\n"
16534                    " int const  i= 1;\n"
16535                    "  int *j=2;\n"
16536                    " int big  =  10000;\n"
16537                    "\n"
16538                    "unsigned oneTwoThree  =123;\n"
16539                    "int oneTwo = 12;\n"
16540                    "  method();\n"
16541                    "float k= 2;\n"
16542                    "int ll=10000;\n"
16543                    "}",
16544                    AlignmentLeft));
16545   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16546             "  int const i   = 1;\n"
16547             "  int**     j   = 2;\n"
16548             "  int&      k   = i;\n"
16549             "  int&&     l   = i + j;\n"
16550             "  int       big = 10000;\n"
16551             "\n"
16552             "  unsigned oneTwoThree = 123;\n"
16553             "  int      oneTwo      = 12;\n"
16554             "  method();\n"
16555             "  float k  = 2;\n"
16556             "  int   ll = 10000;\n"
16557             "}",
16558             format("void SomeFunction(int parameter= 0) {\n"
16559                    " int const  i= 1;\n"
16560                    "  int **j=2;\n"
16561                    "int &k=i;\n"
16562                    "int &&l=i+j;\n"
16563                    " int big  =  10000;\n"
16564                    "\n"
16565                    "unsigned oneTwoThree  =123;\n"
16566                    "int oneTwo = 12;\n"
16567                    "  method();\n"
16568                    "float k= 2;\n"
16569                    "int ll=10000;\n"
16570                    "}",
16571                    AlignmentLeft));
16572   // variables are aligned at their name, pointers are at the left most position
16573   verifyFormat("int*   a;\n"
16574                "int**  b;\n"
16575                "int*** c;\n"
16576                "int    foobar;\n",
16577                AlignmentLeft);
16578 
16579   // PAS_Middle
16580   FormatStyle AlignmentMiddle = Alignment;
16581   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
16582   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16583             "  int const i   = 1;\n"
16584             "  int *     j   = 2;\n"
16585             "  int       big = 10000;\n"
16586             "\n"
16587             "  unsigned oneTwoThree = 123;\n"
16588             "  int      oneTwo      = 12;\n"
16589             "  method();\n"
16590             "  float k  = 2;\n"
16591             "  int   ll = 10000;\n"
16592             "}",
16593             format("void SomeFunction(int parameter= 0) {\n"
16594                    " int const  i= 1;\n"
16595                    "  int *j=2;\n"
16596                    " int big  =  10000;\n"
16597                    "\n"
16598                    "unsigned oneTwoThree  =123;\n"
16599                    "int oneTwo = 12;\n"
16600                    "  method();\n"
16601                    "float k= 2;\n"
16602                    "int ll=10000;\n"
16603                    "}",
16604                    AlignmentMiddle));
16605   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16606             "  int const i   = 1;\n"
16607             "  int **    j   = 2, ***k;\n"
16608             "  int &     k   = i;\n"
16609             "  int &&    l   = i + j;\n"
16610             "  int       big = 10000;\n"
16611             "\n"
16612             "  unsigned oneTwoThree = 123;\n"
16613             "  int      oneTwo      = 12;\n"
16614             "  method();\n"
16615             "  float k  = 2;\n"
16616             "  int   ll = 10000;\n"
16617             "}",
16618             format("void SomeFunction(int parameter= 0) {\n"
16619                    " int const  i= 1;\n"
16620                    "  int **j=2,***k;\n"
16621                    "int &k=i;\n"
16622                    "int &&l=i+j;\n"
16623                    " int big  =  10000;\n"
16624                    "\n"
16625                    "unsigned oneTwoThree  =123;\n"
16626                    "int oneTwo = 12;\n"
16627                    "  method();\n"
16628                    "float k= 2;\n"
16629                    "int ll=10000;\n"
16630                    "}",
16631                    AlignmentMiddle));
16632   // variables are aligned at their name, pointers are in the middle
16633   verifyFormat("int *   a;\n"
16634                "int *   b;\n"
16635                "int *** c;\n"
16636                "int     foobar;\n",
16637                AlignmentMiddle);
16638 
16639   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16640   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16641   verifyFormat("#define A \\\n"
16642                "  int       aaaa = 12; \\\n"
16643                "  float     b = 23; \\\n"
16644                "  const int ccc = 234; \\\n"
16645                "  unsigned  dddddddddd = 2345;",
16646                Alignment);
16647   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16648   verifyFormat("#define A              \\\n"
16649                "  int       aaaa = 12; \\\n"
16650                "  float     b = 23;    \\\n"
16651                "  const int ccc = 234; \\\n"
16652                "  unsigned  dddddddddd = 2345;",
16653                Alignment);
16654   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16655   Alignment.ColumnLimit = 30;
16656   verifyFormat("#define A                    \\\n"
16657                "  int       aaaa = 12;       \\\n"
16658                "  float     b = 23;          \\\n"
16659                "  const int ccc = 234;       \\\n"
16660                "  int       dddddddddd = 2345;",
16661                Alignment);
16662   Alignment.ColumnLimit = 80;
16663   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16664                "k = 4, int l = 5,\n"
16665                "                  int m = 6) {\n"
16666                "  const int j = 10;\n"
16667                "  otherThing = 1;\n"
16668                "}",
16669                Alignment);
16670   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16671                "  int const i = 1;\n"
16672                "  int      *j = 2;\n"
16673                "  int       big = 10000;\n"
16674                "}",
16675                Alignment);
16676   verifyFormat("class C {\n"
16677                "public:\n"
16678                "  int          i = 1;\n"
16679                "  virtual void f() = 0;\n"
16680                "};",
16681                Alignment);
16682   verifyFormat("float i = 1;\n"
16683                "if (SomeType t = getSomething()) {\n"
16684                "}\n"
16685                "const unsigned j = 2;\n"
16686                "int            big = 10000;",
16687                Alignment);
16688   verifyFormat("float j = 7;\n"
16689                "for (int k = 0; k < N; ++k) {\n"
16690                "}\n"
16691                "unsigned j = 2;\n"
16692                "int      big = 10000;\n"
16693                "}",
16694                Alignment);
16695   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16696   verifyFormat("float              i = 1;\n"
16697                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16698                "    = someLooooooooooooooooongFunction();\n"
16699                "int j = 2;",
16700                Alignment);
16701   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16702   verifyFormat("int                i = 1;\n"
16703                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16704                "    someLooooooooooooooooongFunction();\n"
16705                "int j = 2;",
16706                Alignment);
16707 
16708   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16709   verifyFormat("auto lambda = []() {\n"
16710                "  auto  ii = 0;\n"
16711                "  float j  = 0;\n"
16712                "  return 0;\n"
16713                "};\n"
16714                "int   i  = 0;\n"
16715                "float i2 = 0;\n"
16716                "auto  v  = type{\n"
16717                "    i = 1,   //\n"
16718                "    (i = 2), //\n"
16719                "    i = 3    //\n"
16720                "};",
16721                Alignment);
16722   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16723 
16724   verifyFormat(
16725       "int      i = 1;\n"
16726       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16727       "                          loooooooooooooooooooooongParameterB);\n"
16728       "int      j = 2;",
16729       Alignment);
16730 
16731   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
16732   // We expect declarations and assignments to align, as long as it doesn't
16733   // exceed the column limit, starting a new alignment sequence whenever it
16734   // happens.
16735   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16736   Alignment.ColumnLimit = 30;
16737   verifyFormat("float    ii              = 1;\n"
16738                "unsigned j               = 2;\n"
16739                "int someVerylongVariable = 1;\n"
16740                "AnotherLongType  ll = 123456;\n"
16741                "VeryVeryLongType k  = 2;\n"
16742                "int              myvar = 1;",
16743                Alignment);
16744   Alignment.ColumnLimit = 80;
16745   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16746 
16747   verifyFormat(
16748       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
16749       "          typename LongType, typename B>\n"
16750       "auto foo() {}\n",
16751       Alignment);
16752   verifyFormat("float a, b = 1;\n"
16753                "int   c = 2;\n"
16754                "int   dd = 3;\n",
16755                Alignment);
16756   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
16757                "float b[1][] = {{3.f}};\n",
16758                Alignment);
16759   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16760   verifyFormat("float a, b = 1;\n"
16761                "int   c  = 2;\n"
16762                "int   dd = 3;\n",
16763                Alignment);
16764   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
16765                "float b[1][] = {{3.f}};\n",
16766                Alignment);
16767   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16768 
16769   Alignment.ColumnLimit = 30;
16770   Alignment.BinPackParameters = false;
16771   verifyFormat("void foo(float     a,\n"
16772                "         float     b,\n"
16773                "         int       c,\n"
16774                "         uint32_t *d) {\n"
16775                "  int   *e = 0;\n"
16776                "  float  f = 0;\n"
16777                "  double g = 0;\n"
16778                "}\n"
16779                "void bar(ino_t     a,\n"
16780                "         int       b,\n"
16781                "         uint32_t *c,\n"
16782                "         bool      d) {}\n",
16783                Alignment);
16784   Alignment.BinPackParameters = true;
16785   Alignment.ColumnLimit = 80;
16786 
16787   // Bug 33507
16788   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16789   verifyFormat(
16790       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
16791       "  static const Version verVs2017;\n"
16792       "  return true;\n"
16793       "});\n",
16794       Alignment);
16795   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16796 
16797   // See llvm.org/PR35641
16798   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16799   verifyFormat("int func() { //\n"
16800                "  int      b;\n"
16801                "  unsigned c;\n"
16802                "}",
16803                Alignment);
16804 
16805   // See PR37175
16806   FormatStyle Style = getMozillaStyle();
16807   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16808   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
16809             "foo(int a);",
16810             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
16811 
16812   Alignment.PointerAlignment = FormatStyle::PAS_Left;
16813   verifyFormat("unsigned int*       a;\n"
16814                "int*                b;\n"
16815                "unsigned int Const* c;\n"
16816                "unsigned int const* d;\n"
16817                "unsigned int Const& e;\n"
16818                "unsigned int const& f;",
16819                Alignment);
16820   verifyFormat("Const unsigned int* c;\n"
16821                "const unsigned int* d;\n"
16822                "Const unsigned int& e;\n"
16823                "const unsigned int& f;\n"
16824                "const unsigned      g;\n"
16825                "Const unsigned      h;",
16826                Alignment);
16827 
16828   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16829   verifyFormat("unsigned int *       a;\n"
16830                "int *                b;\n"
16831                "unsigned int Const * c;\n"
16832                "unsigned int const * d;\n"
16833                "unsigned int Const & e;\n"
16834                "unsigned int const & f;",
16835                Alignment);
16836   verifyFormat("Const unsigned int * c;\n"
16837                "const unsigned int * d;\n"
16838                "Const unsigned int & e;\n"
16839                "const unsigned int & f;\n"
16840                "const unsigned       g;\n"
16841                "Const unsigned       h;",
16842                Alignment);
16843 }
16844 
16845 TEST_F(FormatTest, AlignWithLineBreaks) {
16846   auto Style = getLLVMStyleWithColumns(120);
16847 
16848   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
16849   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16850   verifyFormat("void foo() {\n"
16851                "  int myVar = 5;\n"
16852                "  double x = 3.14;\n"
16853                "  auto str = \"Hello \"\n"
16854                "             \"World\";\n"
16855                "  auto s = \"Hello \"\n"
16856                "           \"Again\";\n"
16857                "}",
16858                Style);
16859 
16860   // clang-format off
16861   verifyFormat("void foo() {\n"
16862                "  const int capacityBefore = Entries.capacity();\n"
16863                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16864                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16865                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16866                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16867                "}",
16868                Style);
16869   // clang-format on
16870 
16871   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16872   verifyFormat("void foo() {\n"
16873                "  int myVar = 5;\n"
16874                "  double x  = 3.14;\n"
16875                "  auto str  = \"Hello \"\n"
16876                "              \"World\";\n"
16877                "  auto s    = \"Hello \"\n"
16878                "              \"Again\";\n"
16879                "}",
16880                Style);
16881 
16882   // clang-format off
16883   verifyFormat("void foo() {\n"
16884                "  const int capacityBefore = Entries.capacity();\n"
16885                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16886                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16887                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16888                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16889                "}",
16890                Style);
16891   // clang-format on
16892 
16893   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16894   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16895   verifyFormat("void foo() {\n"
16896                "  int    myVar = 5;\n"
16897                "  double x = 3.14;\n"
16898                "  auto   str = \"Hello \"\n"
16899                "               \"World\";\n"
16900                "  auto   s = \"Hello \"\n"
16901                "             \"Again\";\n"
16902                "}",
16903                Style);
16904 
16905   // clang-format off
16906   verifyFormat("void foo() {\n"
16907                "  const int  capacityBefore = Entries.capacity();\n"
16908                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16909                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16910                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16911                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16912                "}",
16913                Style);
16914   // clang-format on
16915 
16916   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16917   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16918 
16919   verifyFormat("void foo() {\n"
16920                "  int    myVar = 5;\n"
16921                "  double x     = 3.14;\n"
16922                "  auto   str   = \"Hello \"\n"
16923                "                 \"World\";\n"
16924                "  auto   s     = \"Hello \"\n"
16925                "                 \"Again\";\n"
16926                "}",
16927                Style);
16928 
16929   // clang-format off
16930   verifyFormat("void foo() {\n"
16931                "  const int  capacityBefore = Entries.capacity();\n"
16932                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16933                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16934                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16935                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16936                "}",
16937                Style);
16938   // clang-format on
16939 
16940   Style = getLLVMStyleWithColumns(120);
16941   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16942   Style.ContinuationIndentWidth = 4;
16943   Style.IndentWidth = 4;
16944 
16945   // clang-format off
16946   verifyFormat("void SomeFunc() {\n"
16947                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16948                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16949                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16950                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16951                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16952                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16953                "}",
16954                Style);
16955   // clang-format on
16956 
16957   Style.BinPackArguments = false;
16958 
16959   // clang-format off
16960   verifyFormat("void SomeFunc() {\n"
16961                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
16962                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16963                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
16964                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16965                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
16966                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16967                "}",
16968                Style);
16969   // clang-format on
16970 }
16971 
16972 TEST_F(FormatTest, AlignWithInitializerPeriods) {
16973   auto Style = getLLVMStyleWithColumns(60);
16974 
16975   verifyFormat("void foo1(void) {\n"
16976                "  BYTE p[1] = 1;\n"
16977                "  A B = {.one_foooooooooooooooo = 2,\n"
16978                "         .two_fooooooooooooo = 3,\n"
16979                "         .three_fooooooooooooo = 4};\n"
16980                "  BYTE payload = 2;\n"
16981                "}",
16982                Style);
16983 
16984   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16985   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16986   verifyFormat("void foo2(void) {\n"
16987                "  BYTE p[1]    = 1;\n"
16988                "  A B          = {.one_foooooooooooooooo = 2,\n"
16989                "                  .two_fooooooooooooo    = 3,\n"
16990                "                  .three_fooooooooooooo  = 4};\n"
16991                "  BYTE payload = 2;\n"
16992                "}",
16993                Style);
16994 
16995   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16996   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16997   verifyFormat("void foo3(void) {\n"
16998                "  BYTE p[1] = 1;\n"
16999                "  A    B = {.one_foooooooooooooooo = 2,\n"
17000                "            .two_fooooooooooooo = 3,\n"
17001                "            .three_fooooooooooooo = 4};\n"
17002                "  BYTE payload = 2;\n"
17003                "}",
17004                Style);
17005 
17006   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17007   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17008   verifyFormat("void foo4(void) {\n"
17009                "  BYTE p[1]    = 1;\n"
17010                "  A    B       = {.one_foooooooooooooooo = 2,\n"
17011                "                  .two_fooooooooooooo    = 3,\n"
17012                "                  .three_fooooooooooooo  = 4};\n"
17013                "  BYTE payload = 2;\n"
17014                "}",
17015                Style);
17016 }
17017 
17018 TEST_F(FormatTest, LinuxBraceBreaking) {
17019   FormatStyle LinuxBraceStyle = getLLVMStyle();
17020   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
17021   verifyFormat("namespace a\n"
17022                "{\n"
17023                "class A\n"
17024                "{\n"
17025                "  void f()\n"
17026                "  {\n"
17027                "    if (true) {\n"
17028                "      a();\n"
17029                "      b();\n"
17030                "    } else {\n"
17031                "      a();\n"
17032                "    }\n"
17033                "  }\n"
17034                "  void g() { return; }\n"
17035                "};\n"
17036                "struct B {\n"
17037                "  int x;\n"
17038                "};\n"
17039                "} // namespace a\n",
17040                LinuxBraceStyle);
17041   verifyFormat("enum X {\n"
17042                "  Y = 0,\n"
17043                "}\n",
17044                LinuxBraceStyle);
17045   verifyFormat("struct S {\n"
17046                "  int Type;\n"
17047                "  union {\n"
17048                "    int x;\n"
17049                "    double y;\n"
17050                "  } Value;\n"
17051                "  class C\n"
17052                "  {\n"
17053                "    MyFavoriteType Value;\n"
17054                "  } Class;\n"
17055                "}\n",
17056                LinuxBraceStyle);
17057 }
17058 
17059 TEST_F(FormatTest, MozillaBraceBreaking) {
17060   FormatStyle MozillaBraceStyle = getLLVMStyle();
17061   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
17062   MozillaBraceStyle.FixNamespaceComments = false;
17063   verifyFormat("namespace a {\n"
17064                "class A\n"
17065                "{\n"
17066                "  void f()\n"
17067                "  {\n"
17068                "    if (true) {\n"
17069                "      a();\n"
17070                "      b();\n"
17071                "    }\n"
17072                "  }\n"
17073                "  void g() { return; }\n"
17074                "};\n"
17075                "enum E\n"
17076                "{\n"
17077                "  A,\n"
17078                "  // foo\n"
17079                "  B,\n"
17080                "  C\n"
17081                "};\n"
17082                "struct B\n"
17083                "{\n"
17084                "  int x;\n"
17085                "};\n"
17086                "}\n",
17087                MozillaBraceStyle);
17088   verifyFormat("struct S\n"
17089                "{\n"
17090                "  int Type;\n"
17091                "  union\n"
17092                "  {\n"
17093                "    int x;\n"
17094                "    double y;\n"
17095                "  } Value;\n"
17096                "  class C\n"
17097                "  {\n"
17098                "    MyFavoriteType Value;\n"
17099                "  } Class;\n"
17100                "}\n",
17101                MozillaBraceStyle);
17102 }
17103 
17104 TEST_F(FormatTest, StroustrupBraceBreaking) {
17105   FormatStyle StroustrupBraceStyle = getLLVMStyle();
17106   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
17107   verifyFormat("namespace a {\n"
17108                "class A {\n"
17109                "  void f()\n"
17110                "  {\n"
17111                "    if (true) {\n"
17112                "      a();\n"
17113                "      b();\n"
17114                "    }\n"
17115                "  }\n"
17116                "  void g() { return; }\n"
17117                "};\n"
17118                "struct B {\n"
17119                "  int x;\n"
17120                "};\n"
17121                "} // namespace a\n",
17122                StroustrupBraceStyle);
17123 
17124   verifyFormat("void foo()\n"
17125                "{\n"
17126                "  if (a) {\n"
17127                "    a();\n"
17128                "  }\n"
17129                "  else {\n"
17130                "    b();\n"
17131                "  }\n"
17132                "}\n",
17133                StroustrupBraceStyle);
17134 
17135   verifyFormat("#ifdef _DEBUG\n"
17136                "int foo(int i = 0)\n"
17137                "#else\n"
17138                "int foo(int i = 5)\n"
17139                "#endif\n"
17140                "{\n"
17141                "  return i;\n"
17142                "}",
17143                StroustrupBraceStyle);
17144 
17145   verifyFormat("void foo() {}\n"
17146                "void bar()\n"
17147                "#ifdef _DEBUG\n"
17148                "{\n"
17149                "  foo();\n"
17150                "}\n"
17151                "#else\n"
17152                "{\n"
17153                "}\n"
17154                "#endif",
17155                StroustrupBraceStyle);
17156 
17157   verifyFormat("void foobar() { int i = 5; }\n"
17158                "#ifdef _DEBUG\n"
17159                "void bar() {}\n"
17160                "#else\n"
17161                "void bar() { foobar(); }\n"
17162                "#endif",
17163                StroustrupBraceStyle);
17164 }
17165 
17166 TEST_F(FormatTest, AllmanBraceBreaking) {
17167   FormatStyle AllmanBraceStyle = getLLVMStyle();
17168   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
17169 
17170   EXPECT_EQ("namespace a\n"
17171             "{\n"
17172             "void f();\n"
17173             "void g();\n"
17174             "} // namespace a\n",
17175             format("namespace a\n"
17176                    "{\n"
17177                    "void f();\n"
17178                    "void g();\n"
17179                    "}\n",
17180                    AllmanBraceStyle));
17181 
17182   verifyFormat("namespace a\n"
17183                "{\n"
17184                "class A\n"
17185                "{\n"
17186                "  void f()\n"
17187                "  {\n"
17188                "    if (true)\n"
17189                "    {\n"
17190                "      a();\n"
17191                "      b();\n"
17192                "    }\n"
17193                "  }\n"
17194                "  void g() { return; }\n"
17195                "};\n"
17196                "struct B\n"
17197                "{\n"
17198                "  int x;\n"
17199                "};\n"
17200                "union C\n"
17201                "{\n"
17202                "};\n"
17203                "} // namespace a",
17204                AllmanBraceStyle);
17205 
17206   verifyFormat("void f()\n"
17207                "{\n"
17208                "  if (true)\n"
17209                "  {\n"
17210                "    a();\n"
17211                "  }\n"
17212                "  else if (false)\n"
17213                "  {\n"
17214                "    b();\n"
17215                "  }\n"
17216                "  else\n"
17217                "  {\n"
17218                "    c();\n"
17219                "  }\n"
17220                "}\n",
17221                AllmanBraceStyle);
17222 
17223   verifyFormat("void f()\n"
17224                "{\n"
17225                "  for (int i = 0; i < 10; ++i)\n"
17226                "  {\n"
17227                "    a();\n"
17228                "  }\n"
17229                "  while (false)\n"
17230                "  {\n"
17231                "    b();\n"
17232                "  }\n"
17233                "  do\n"
17234                "  {\n"
17235                "    c();\n"
17236                "  } while (false)\n"
17237                "}\n",
17238                AllmanBraceStyle);
17239 
17240   verifyFormat("void f(int a)\n"
17241                "{\n"
17242                "  switch (a)\n"
17243                "  {\n"
17244                "  case 0:\n"
17245                "    break;\n"
17246                "  case 1:\n"
17247                "  {\n"
17248                "    break;\n"
17249                "  }\n"
17250                "  case 2:\n"
17251                "  {\n"
17252                "  }\n"
17253                "  break;\n"
17254                "  default:\n"
17255                "    break;\n"
17256                "  }\n"
17257                "}\n",
17258                AllmanBraceStyle);
17259 
17260   verifyFormat("enum X\n"
17261                "{\n"
17262                "  Y = 0,\n"
17263                "}\n",
17264                AllmanBraceStyle);
17265   verifyFormat("enum X\n"
17266                "{\n"
17267                "  Y = 0\n"
17268                "}\n",
17269                AllmanBraceStyle);
17270 
17271   verifyFormat("@interface BSApplicationController ()\n"
17272                "{\n"
17273                "@private\n"
17274                "  id _extraIvar;\n"
17275                "}\n"
17276                "@end\n",
17277                AllmanBraceStyle);
17278 
17279   verifyFormat("#ifdef _DEBUG\n"
17280                "int foo(int i = 0)\n"
17281                "#else\n"
17282                "int foo(int i = 5)\n"
17283                "#endif\n"
17284                "{\n"
17285                "  return i;\n"
17286                "}",
17287                AllmanBraceStyle);
17288 
17289   verifyFormat("void foo() {}\n"
17290                "void bar()\n"
17291                "#ifdef _DEBUG\n"
17292                "{\n"
17293                "  foo();\n"
17294                "}\n"
17295                "#else\n"
17296                "{\n"
17297                "}\n"
17298                "#endif",
17299                AllmanBraceStyle);
17300 
17301   verifyFormat("void foobar() { int i = 5; }\n"
17302                "#ifdef _DEBUG\n"
17303                "void bar() {}\n"
17304                "#else\n"
17305                "void bar() { foobar(); }\n"
17306                "#endif",
17307                AllmanBraceStyle);
17308 
17309   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
17310             FormatStyle::SLS_All);
17311 
17312   verifyFormat("[](int i) { return i + 2; };\n"
17313                "[](int i, int j)\n"
17314                "{\n"
17315                "  auto x = i + j;\n"
17316                "  auto y = i * j;\n"
17317                "  return x ^ y;\n"
17318                "};\n"
17319                "void foo()\n"
17320                "{\n"
17321                "  auto shortLambda = [](int i) { return i + 2; };\n"
17322                "  auto longLambda = [](int i, int j)\n"
17323                "  {\n"
17324                "    auto x = i + j;\n"
17325                "    auto y = i * j;\n"
17326                "    return x ^ y;\n"
17327                "  };\n"
17328                "}",
17329                AllmanBraceStyle);
17330 
17331   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17332 
17333   verifyFormat("[](int i)\n"
17334                "{\n"
17335                "  return i + 2;\n"
17336                "};\n"
17337                "[](int i, int j)\n"
17338                "{\n"
17339                "  auto x = i + j;\n"
17340                "  auto y = i * j;\n"
17341                "  return x ^ y;\n"
17342                "};\n"
17343                "void foo()\n"
17344                "{\n"
17345                "  auto shortLambda = [](int i)\n"
17346                "  {\n"
17347                "    return i + 2;\n"
17348                "  };\n"
17349                "  auto longLambda = [](int i, int j)\n"
17350                "  {\n"
17351                "    auto x = i + j;\n"
17352                "    auto y = i * j;\n"
17353                "    return x ^ y;\n"
17354                "  };\n"
17355                "}",
17356                AllmanBraceStyle);
17357 
17358   // Reset
17359   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
17360 
17361   // This shouldn't affect ObjC blocks..
17362   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17363                "  // ...\n"
17364                "  int i;\n"
17365                "}];",
17366                AllmanBraceStyle);
17367   verifyFormat("void (^block)(void) = ^{\n"
17368                "  // ...\n"
17369                "  int i;\n"
17370                "};",
17371                AllmanBraceStyle);
17372   // .. or dict literals.
17373   verifyFormat("void f()\n"
17374                "{\n"
17375                "  // ...\n"
17376                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
17377                "}",
17378                AllmanBraceStyle);
17379   verifyFormat("void f()\n"
17380                "{\n"
17381                "  // ...\n"
17382                "  [object someMethod:@{a : @\"b\"}];\n"
17383                "}",
17384                AllmanBraceStyle);
17385   verifyFormat("int f()\n"
17386                "{ // comment\n"
17387                "  return 42;\n"
17388                "}",
17389                AllmanBraceStyle);
17390 
17391   AllmanBraceStyle.ColumnLimit = 19;
17392   verifyFormat("void f() { int i; }", AllmanBraceStyle);
17393   AllmanBraceStyle.ColumnLimit = 18;
17394   verifyFormat("void f()\n"
17395                "{\n"
17396                "  int i;\n"
17397                "}",
17398                AllmanBraceStyle);
17399   AllmanBraceStyle.ColumnLimit = 80;
17400 
17401   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
17402   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17403       FormatStyle::SIS_WithoutElse;
17404   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17405   verifyFormat("void f(bool b)\n"
17406                "{\n"
17407                "  if (b)\n"
17408                "  {\n"
17409                "    return;\n"
17410                "  }\n"
17411                "}\n",
17412                BreakBeforeBraceShortIfs);
17413   verifyFormat("void f(bool b)\n"
17414                "{\n"
17415                "  if constexpr (b)\n"
17416                "  {\n"
17417                "    return;\n"
17418                "  }\n"
17419                "}\n",
17420                BreakBeforeBraceShortIfs);
17421   verifyFormat("void f(bool b)\n"
17422                "{\n"
17423                "  if CONSTEXPR (b)\n"
17424                "  {\n"
17425                "    return;\n"
17426                "  }\n"
17427                "}\n",
17428                BreakBeforeBraceShortIfs);
17429   verifyFormat("void f(bool b)\n"
17430                "{\n"
17431                "  if (b) return;\n"
17432                "}\n",
17433                BreakBeforeBraceShortIfs);
17434   verifyFormat("void f(bool b)\n"
17435                "{\n"
17436                "  if constexpr (b) return;\n"
17437                "}\n",
17438                BreakBeforeBraceShortIfs);
17439   verifyFormat("void f(bool b)\n"
17440                "{\n"
17441                "  if CONSTEXPR (b) return;\n"
17442                "}\n",
17443                BreakBeforeBraceShortIfs);
17444   verifyFormat("void f(bool b)\n"
17445                "{\n"
17446                "  while (b)\n"
17447                "  {\n"
17448                "    return;\n"
17449                "  }\n"
17450                "}\n",
17451                BreakBeforeBraceShortIfs);
17452 }
17453 
17454 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
17455   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
17456   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
17457 
17458   // Make a few changes to the style for testing purposes
17459   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
17460       FormatStyle::SFS_Empty;
17461   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17462 
17463   // FIXME: this test case can't decide whether there should be a blank line
17464   // after the ~D() line or not. It adds one if one doesn't exist in the test
17465   // and it removes the line if one exists.
17466   /*
17467   verifyFormat("class A;\n"
17468                "namespace B\n"
17469                "  {\n"
17470                "class C;\n"
17471                "// Comment\n"
17472                "class D\n"
17473                "  {\n"
17474                "public:\n"
17475                "  D();\n"
17476                "  ~D() {}\n"
17477                "private:\n"
17478                "  enum E\n"
17479                "    {\n"
17480                "    F\n"
17481                "    }\n"
17482                "  };\n"
17483                "  } // namespace B\n",
17484                WhitesmithsBraceStyle);
17485   */
17486 
17487   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
17488   verifyFormat("namespace a\n"
17489                "  {\n"
17490                "class A\n"
17491                "  {\n"
17492                "  void f()\n"
17493                "    {\n"
17494                "    if (true)\n"
17495                "      {\n"
17496                "      a();\n"
17497                "      b();\n"
17498                "      }\n"
17499                "    }\n"
17500                "  void g()\n"
17501                "    {\n"
17502                "    return;\n"
17503                "    }\n"
17504                "  };\n"
17505                "struct B\n"
17506                "  {\n"
17507                "  int x;\n"
17508                "  };\n"
17509                "  } // namespace a",
17510                WhitesmithsBraceStyle);
17511 
17512   verifyFormat("namespace a\n"
17513                "  {\n"
17514                "namespace b\n"
17515                "  {\n"
17516                "class A\n"
17517                "  {\n"
17518                "  void f()\n"
17519                "    {\n"
17520                "    if (true)\n"
17521                "      {\n"
17522                "      a();\n"
17523                "      b();\n"
17524                "      }\n"
17525                "    }\n"
17526                "  void g()\n"
17527                "    {\n"
17528                "    return;\n"
17529                "    }\n"
17530                "  };\n"
17531                "struct B\n"
17532                "  {\n"
17533                "  int x;\n"
17534                "  };\n"
17535                "  } // namespace b\n"
17536                "  } // namespace a",
17537                WhitesmithsBraceStyle);
17538 
17539   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
17540   verifyFormat("namespace a\n"
17541                "  {\n"
17542                "namespace b\n"
17543                "  {\n"
17544                "  class A\n"
17545                "    {\n"
17546                "    void f()\n"
17547                "      {\n"
17548                "      if (true)\n"
17549                "        {\n"
17550                "        a();\n"
17551                "        b();\n"
17552                "        }\n"
17553                "      }\n"
17554                "    void g()\n"
17555                "      {\n"
17556                "      return;\n"
17557                "      }\n"
17558                "    };\n"
17559                "  struct B\n"
17560                "    {\n"
17561                "    int x;\n"
17562                "    };\n"
17563                "  } // namespace b\n"
17564                "  } // namespace a",
17565                WhitesmithsBraceStyle);
17566 
17567   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
17568   verifyFormat("namespace a\n"
17569                "  {\n"
17570                "  namespace b\n"
17571                "    {\n"
17572                "    class A\n"
17573                "      {\n"
17574                "      void f()\n"
17575                "        {\n"
17576                "        if (true)\n"
17577                "          {\n"
17578                "          a();\n"
17579                "          b();\n"
17580                "          }\n"
17581                "        }\n"
17582                "      void g()\n"
17583                "        {\n"
17584                "        return;\n"
17585                "        }\n"
17586                "      };\n"
17587                "    struct B\n"
17588                "      {\n"
17589                "      int x;\n"
17590                "      };\n"
17591                "    } // namespace b\n"
17592                "  }   // namespace a",
17593                WhitesmithsBraceStyle);
17594 
17595   verifyFormat("void f()\n"
17596                "  {\n"
17597                "  if (true)\n"
17598                "    {\n"
17599                "    a();\n"
17600                "    }\n"
17601                "  else if (false)\n"
17602                "    {\n"
17603                "    b();\n"
17604                "    }\n"
17605                "  else\n"
17606                "    {\n"
17607                "    c();\n"
17608                "    }\n"
17609                "  }\n",
17610                WhitesmithsBraceStyle);
17611 
17612   verifyFormat("void f()\n"
17613                "  {\n"
17614                "  for (int i = 0; i < 10; ++i)\n"
17615                "    {\n"
17616                "    a();\n"
17617                "    }\n"
17618                "  while (false)\n"
17619                "    {\n"
17620                "    b();\n"
17621                "    }\n"
17622                "  do\n"
17623                "    {\n"
17624                "    c();\n"
17625                "    } while (false)\n"
17626                "  }\n",
17627                WhitesmithsBraceStyle);
17628 
17629   WhitesmithsBraceStyle.IndentCaseLabels = true;
17630   verifyFormat("void switchTest1(int a)\n"
17631                "  {\n"
17632                "  switch (a)\n"
17633                "    {\n"
17634                "    case 2:\n"
17635                "      {\n"
17636                "      }\n"
17637                "      break;\n"
17638                "    }\n"
17639                "  }\n",
17640                WhitesmithsBraceStyle);
17641 
17642   verifyFormat("void switchTest2(int a)\n"
17643                "  {\n"
17644                "  switch (a)\n"
17645                "    {\n"
17646                "    case 0:\n"
17647                "      break;\n"
17648                "    case 1:\n"
17649                "      {\n"
17650                "      break;\n"
17651                "      }\n"
17652                "    case 2:\n"
17653                "      {\n"
17654                "      }\n"
17655                "      break;\n"
17656                "    default:\n"
17657                "      break;\n"
17658                "    }\n"
17659                "  }\n",
17660                WhitesmithsBraceStyle);
17661 
17662   verifyFormat("void switchTest3(int a)\n"
17663                "  {\n"
17664                "  switch (a)\n"
17665                "    {\n"
17666                "    case 0:\n"
17667                "      {\n"
17668                "      foo(x);\n"
17669                "      }\n"
17670                "      break;\n"
17671                "    default:\n"
17672                "      {\n"
17673                "      foo(1);\n"
17674                "      }\n"
17675                "      break;\n"
17676                "    }\n"
17677                "  }\n",
17678                WhitesmithsBraceStyle);
17679 
17680   WhitesmithsBraceStyle.IndentCaseLabels = false;
17681 
17682   verifyFormat("void switchTest4(int a)\n"
17683                "  {\n"
17684                "  switch (a)\n"
17685                "    {\n"
17686                "  case 2:\n"
17687                "    {\n"
17688                "    }\n"
17689                "    break;\n"
17690                "    }\n"
17691                "  }\n",
17692                WhitesmithsBraceStyle);
17693 
17694   verifyFormat("void switchTest5(int a)\n"
17695                "  {\n"
17696                "  switch (a)\n"
17697                "    {\n"
17698                "  case 0:\n"
17699                "    break;\n"
17700                "  case 1:\n"
17701                "    {\n"
17702                "    foo();\n"
17703                "    break;\n"
17704                "    }\n"
17705                "  case 2:\n"
17706                "    {\n"
17707                "    }\n"
17708                "    break;\n"
17709                "  default:\n"
17710                "    break;\n"
17711                "    }\n"
17712                "  }\n",
17713                WhitesmithsBraceStyle);
17714 
17715   verifyFormat("void switchTest6(int a)\n"
17716                "  {\n"
17717                "  switch (a)\n"
17718                "    {\n"
17719                "  case 0:\n"
17720                "    {\n"
17721                "    foo(x);\n"
17722                "    }\n"
17723                "    break;\n"
17724                "  default:\n"
17725                "    {\n"
17726                "    foo(1);\n"
17727                "    }\n"
17728                "    break;\n"
17729                "    }\n"
17730                "  }\n",
17731                WhitesmithsBraceStyle);
17732 
17733   verifyFormat("enum X\n"
17734                "  {\n"
17735                "  Y = 0, // testing\n"
17736                "  }\n",
17737                WhitesmithsBraceStyle);
17738 
17739   verifyFormat("enum X\n"
17740                "  {\n"
17741                "  Y = 0\n"
17742                "  }\n",
17743                WhitesmithsBraceStyle);
17744   verifyFormat("enum X\n"
17745                "  {\n"
17746                "  Y = 0,\n"
17747                "  Z = 1\n"
17748                "  };\n",
17749                WhitesmithsBraceStyle);
17750 
17751   verifyFormat("@interface BSApplicationController ()\n"
17752                "  {\n"
17753                "@private\n"
17754                "  id _extraIvar;\n"
17755                "  }\n"
17756                "@end\n",
17757                WhitesmithsBraceStyle);
17758 
17759   verifyFormat("#ifdef _DEBUG\n"
17760                "int foo(int i = 0)\n"
17761                "#else\n"
17762                "int foo(int i = 5)\n"
17763                "#endif\n"
17764                "  {\n"
17765                "  return i;\n"
17766                "  }",
17767                WhitesmithsBraceStyle);
17768 
17769   verifyFormat("void foo() {}\n"
17770                "void bar()\n"
17771                "#ifdef _DEBUG\n"
17772                "  {\n"
17773                "  foo();\n"
17774                "  }\n"
17775                "#else\n"
17776                "  {\n"
17777                "  }\n"
17778                "#endif",
17779                WhitesmithsBraceStyle);
17780 
17781   verifyFormat("void foobar()\n"
17782                "  {\n"
17783                "  int i = 5;\n"
17784                "  }\n"
17785                "#ifdef _DEBUG\n"
17786                "void bar()\n"
17787                "  {\n"
17788                "  }\n"
17789                "#else\n"
17790                "void bar()\n"
17791                "  {\n"
17792                "  foobar();\n"
17793                "  }\n"
17794                "#endif",
17795                WhitesmithsBraceStyle);
17796 
17797   // This shouldn't affect ObjC blocks..
17798   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17799                "  // ...\n"
17800                "  int i;\n"
17801                "}];",
17802                WhitesmithsBraceStyle);
17803   verifyFormat("void (^block)(void) = ^{\n"
17804                "  // ...\n"
17805                "  int i;\n"
17806                "};",
17807                WhitesmithsBraceStyle);
17808   // .. or dict literals.
17809   verifyFormat("void f()\n"
17810                "  {\n"
17811                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
17812                "  }",
17813                WhitesmithsBraceStyle);
17814 
17815   verifyFormat("int f()\n"
17816                "  { // comment\n"
17817                "  return 42;\n"
17818                "  }",
17819                WhitesmithsBraceStyle);
17820 
17821   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
17822   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17823       FormatStyle::SIS_OnlyFirstIf;
17824   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17825   verifyFormat("void f(bool b)\n"
17826                "  {\n"
17827                "  if (b)\n"
17828                "    {\n"
17829                "    return;\n"
17830                "    }\n"
17831                "  }\n",
17832                BreakBeforeBraceShortIfs);
17833   verifyFormat("void f(bool b)\n"
17834                "  {\n"
17835                "  if (b) return;\n"
17836                "  }\n",
17837                BreakBeforeBraceShortIfs);
17838   verifyFormat("void f(bool b)\n"
17839                "  {\n"
17840                "  while (b)\n"
17841                "    {\n"
17842                "    return;\n"
17843                "    }\n"
17844                "  }\n",
17845                BreakBeforeBraceShortIfs);
17846 }
17847 
17848 TEST_F(FormatTest, GNUBraceBreaking) {
17849   FormatStyle GNUBraceStyle = getLLVMStyle();
17850   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
17851   verifyFormat("namespace a\n"
17852                "{\n"
17853                "class A\n"
17854                "{\n"
17855                "  void f()\n"
17856                "  {\n"
17857                "    int a;\n"
17858                "    {\n"
17859                "      int b;\n"
17860                "    }\n"
17861                "    if (true)\n"
17862                "      {\n"
17863                "        a();\n"
17864                "        b();\n"
17865                "      }\n"
17866                "  }\n"
17867                "  void g() { return; }\n"
17868                "}\n"
17869                "} // namespace a",
17870                GNUBraceStyle);
17871 
17872   verifyFormat("void f()\n"
17873                "{\n"
17874                "  if (true)\n"
17875                "    {\n"
17876                "      a();\n"
17877                "    }\n"
17878                "  else if (false)\n"
17879                "    {\n"
17880                "      b();\n"
17881                "    }\n"
17882                "  else\n"
17883                "    {\n"
17884                "      c();\n"
17885                "    }\n"
17886                "}\n",
17887                GNUBraceStyle);
17888 
17889   verifyFormat("void f()\n"
17890                "{\n"
17891                "  for (int i = 0; i < 10; ++i)\n"
17892                "    {\n"
17893                "      a();\n"
17894                "    }\n"
17895                "  while (false)\n"
17896                "    {\n"
17897                "      b();\n"
17898                "    }\n"
17899                "  do\n"
17900                "    {\n"
17901                "      c();\n"
17902                "    }\n"
17903                "  while (false);\n"
17904                "}\n",
17905                GNUBraceStyle);
17906 
17907   verifyFormat("void f(int a)\n"
17908                "{\n"
17909                "  switch (a)\n"
17910                "    {\n"
17911                "    case 0:\n"
17912                "      break;\n"
17913                "    case 1:\n"
17914                "      {\n"
17915                "        break;\n"
17916                "      }\n"
17917                "    case 2:\n"
17918                "      {\n"
17919                "      }\n"
17920                "      break;\n"
17921                "    default:\n"
17922                "      break;\n"
17923                "    }\n"
17924                "}\n",
17925                GNUBraceStyle);
17926 
17927   verifyFormat("enum X\n"
17928                "{\n"
17929                "  Y = 0,\n"
17930                "}\n",
17931                GNUBraceStyle);
17932 
17933   verifyFormat("@interface BSApplicationController ()\n"
17934                "{\n"
17935                "@private\n"
17936                "  id _extraIvar;\n"
17937                "}\n"
17938                "@end\n",
17939                GNUBraceStyle);
17940 
17941   verifyFormat("#ifdef _DEBUG\n"
17942                "int foo(int i = 0)\n"
17943                "#else\n"
17944                "int foo(int i = 5)\n"
17945                "#endif\n"
17946                "{\n"
17947                "  return i;\n"
17948                "}",
17949                GNUBraceStyle);
17950 
17951   verifyFormat("void foo() {}\n"
17952                "void bar()\n"
17953                "#ifdef _DEBUG\n"
17954                "{\n"
17955                "  foo();\n"
17956                "}\n"
17957                "#else\n"
17958                "{\n"
17959                "}\n"
17960                "#endif",
17961                GNUBraceStyle);
17962 
17963   verifyFormat("void foobar() { int i = 5; }\n"
17964                "#ifdef _DEBUG\n"
17965                "void bar() {}\n"
17966                "#else\n"
17967                "void bar() { foobar(); }\n"
17968                "#endif",
17969                GNUBraceStyle);
17970 }
17971 
17972 TEST_F(FormatTest, WebKitBraceBreaking) {
17973   FormatStyle WebKitBraceStyle = getLLVMStyle();
17974   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
17975   WebKitBraceStyle.FixNamespaceComments = false;
17976   verifyFormat("namespace a {\n"
17977                "class A {\n"
17978                "  void f()\n"
17979                "  {\n"
17980                "    if (true) {\n"
17981                "      a();\n"
17982                "      b();\n"
17983                "    }\n"
17984                "  }\n"
17985                "  void g() { return; }\n"
17986                "};\n"
17987                "enum E {\n"
17988                "  A,\n"
17989                "  // foo\n"
17990                "  B,\n"
17991                "  C\n"
17992                "};\n"
17993                "struct B {\n"
17994                "  int x;\n"
17995                "};\n"
17996                "}\n",
17997                WebKitBraceStyle);
17998   verifyFormat("struct S {\n"
17999                "  int Type;\n"
18000                "  union {\n"
18001                "    int x;\n"
18002                "    double y;\n"
18003                "  } Value;\n"
18004                "  class C {\n"
18005                "    MyFavoriteType Value;\n"
18006                "  } Class;\n"
18007                "};\n",
18008                WebKitBraceStyle);
18009 }
18010 
18011 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
18012   verifyFormat("void f() {\n"
18013                "  try {\n"
18014                "  } catch (const Exception &e) {\n"
18015                "  }\n"
18016                "}\n",
18017                getLLVMStyle());
18018 }
18019 
18020 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
18021   auto Style = getLLVMStyle();
18022   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18023   Style.AlignConsecutiveAssignments =
18024       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18025   Style.AlignConsecutiveDeclarations =
18026       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18027   verifyFormat("struct test demo[] = {\n"
18028                "    {56,    23, \"hello\"},\n"
18029                "    {-1, 93463, \"world\"},\n"
18030                "    { 7,     5,    \"!!\"}\n"
18031                "};\n",
18032                Style);
18033 
18034   verifyFormat("struct test demo[] = {\n"
18035                "    {56,    23, \"hello\"}, // first line\n"
18036                "    {-1, 93463, \"world\"}, // second line\n"
18037                "    { 7,     5,    \"!!\"}  // third line\n"
18038                "};\n",
18039                Style);
18040 
18041   verifyFormat("struct test demo[4] = {\n"
18042                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18043                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18044                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18045                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18046                "};\n",
18047                Style);
18048 
18049   verifyFormat("struct test demo[3] = {\n"
18050                "    {56,    23, \"hello\"},\n"
18051                "    {-1, 93463, \"world\"},\n"
18052                "    { 7,     5,    \"!!\"}\n"
18053                "};\n",
18054                Style);
18055 
18056   verifyFormat("struct test demo[3] = {\n"
18057                "    {int{56},    23, \"hello\"},\n"
18058                "    {int{-1}, 93463, \"world\"},\n"
18059                "    { int{7},     5,    \"!!\"}\n"
18060                "};\n",
18061                Style);
18062 
18063   verifyFormat("struct test demo[] = {\n"
18064                "    {56,    23, \"hello\"},\n"
18065                "    {-1, 93463, \"world\"},\n"
18066                "    { 7,     5,    \"!!\"},\n"
18067                "};\n",
18068                Style);
18069 
18070   verifyFormat("test demo[] = {\n"
18071                "    {56,    23, \"hello\"},\n"
18072                "    {-1, 93463, \"world\"},\n"
18073                "    { 7,     5,    \"!!\"},\n"
18074                "};\n",
18075                Style);
18076 
18077   verifyFormat("demo = std::array<struct test, 3>{\n"
18078                "    test{56,    23, \"hello\"},\n"
18079                "    test{-1, 93463, \"world\"},\n"
18080                "    test{ 7,     5,    \"!!\"},\n"
18081                "};\n",
18082                Style);
18083 
18084   verifyFormat("test demo[] = {\n"
18085                "    {56,    23, \"hello\"},\n"
18086                "#if X\n"
18087                "    {-1, 93463, \"world\"},\n"
18088                "#endif\n"
18089                "    { 7,     5,    \"!!\"}\n"
18090                "};\n",
18091                Style);
18092 
18093   verifyFormat(
18094       "test demo[] = {\n"
18095       "    { 7,    23,\n"
18096       "     \"hello world i am a very long line that really, in any\"\n"
18097       "     \"just world, ought to be split over multiple lines\"},\n"
18098       "    {-1, 93463,                                  \"world\"},\n"
18099       "    {56,     5,                                     \"!!\"}\n"
18100       "};\n",
18101       Style);
18102 
18103   verifyFormat("return GradForUnaryCwise(g, {\n"
18104                "                                {{\"sign\"}, \"Sign\",  "
18105                "  {\"x\", \"dy\"}},\n"
18106                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
18107                ", \"sign\"}},\n"
18108                "});\n",
18109                Style);
18110 
18111   Style.ColumnLimit = 0;
18112   EXPECT_EQ(
18113       "test demo[] = {\n"
18114       "    {56,    23, \"hello world i am a very long line that really, "
18115       "in any just world, ought to be split over multiple lines\"},\n"
18116       "    {-1, 93463,                                                  "
18117       "                                                 \"world\"},\n"
18118       "    { 7,     5,                                                  "
18119       "                                                    \"!!\"},\n"
18120       "};",
18121       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18122              "that really, in any just world, ought to be split over multiple "
18123              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18124              Style));
18125 
18126   Style.ColumnLimit = 80;
18127   verifyFormat("test demo[] = {\n"
18128                "    {56,    23, /* a comment */ \"hello\"},\n"
18129                "    {-1, 93463,                 \"world\"},\n"
18130                "    { 7,     5,                    \"!!\"}\n"
18131                "};\n",
18132                Style);
18133 
18134   verifyFormat("test demo[] = {\n"
18135                "    {56,    23,                    \"hello\"},\n"
18136                "    {-1, 93463, \"world\" /* comment here */},\n"
18137                "    { 7,     5,                       \"!!\"}\n"
18138                "};\n",
18139                Style);
18140 
18141   verifyFormat("test demo[] = {\n"
18142                "    {56, /* a comment */ 23, \"hello\"},\n"
18143                "    {-1,              93463, \"world\"},\n"
18144                "    { 7,                  5,    \"!!\"}\n"
18145                "};\n",
18146                Style);
18147 
18148   Style.ColumnLimit = 20;
18149   EXPECT_EQ(
18150       "demo = std::array<\n"
18151       "    struct test, 3>{\n"
18152       "    test{\n"
18153       "         56,    23,\n"
18154       "         \"hello \"\n"
18155       "         \"world i \"\n"
18156       "         \"am a very \"\n"
18157       "         \"long line \"\n"
18158       "         \"that \"\n"
18159       "         \"really, \"\n"
18160       "         \"in any \"\n"
18161       "         \"just \"\n"
18162       "         \"world, \"\n"
18163       "         \"ought to \"\n"
18164       "         \"be split \"\n"
18165       "         \"over \"\n"
18166       "         \"multiple \"\n"
18167       "         \"lines\"},\n"
18168       "    test{-1, 93463,\n"
18169       "         \"world\"},\n"
18170       "    test{ 7,     5,\n"
18171       "         \"!!\"   },\n"
18172       "};",
18173       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18174              "i am a very long line that really, in any just world, ought "
18175              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18176              "test{7, 5, \"!!\"},};",
18177              Style));
18178   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18179   Style = getLLVMStyleWithColumns(50);
18180   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18181   verifyFormat("static A x = {\n"
18182                "    {{init1, init2, init3, init4},\n"
18183                "     {init1, init2, init3, init4}}\n"
18184                "};",
18185                Style);
18186   Style.ColumnLimit = 100;
18187   EXPECT_EQ(
18188       "test demo[] = {\n"
18189       "    {56,    23,\n"
18190       "     \"hello world i am a very long line that really, in any just world"
18191       ", ought to be split over \"\n"
18192       "     \"multiple lines\"  },\n"
18193       "    {-1, 93463, \"world\"},\n"
18194       "    { 7,     5,    \"!!\"},\n"
18195       "};",
18196       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18197              "that really, in any just world, ought to be split over multiple "
18198              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18199              Style));
18200 
18201   Style = getLLVMStyleWithColumns(50);
18202   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
18203   Style.AlignConsecutiveAssignments =
18204       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18205   Style.AlignConsecutiveDeclarations =
18206       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
18207   verifyFormat("struct test demo[] = {\n"
18208                "    {56,    23, \"hello\"},\n"
18209                "    {-1, 93463, \"world\"},\n"
18210                "    { 7,     5,    \"!!\"}\n"
18211                "};\n"
18212                "static A x = {\n"
18213                "    {{init1, init2, init3, init4},\n"
18214                "     {init1, init2, init3, init4}}\n"
18215                "};",
18216                Style);
18217   Style.ColumnLimit = 100;
18218   Style.AlignConsecutiveAssignments =
18219       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18220   Style.AlignConsecutiveDeclarations =
18221       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
18222   verifyFormat("struct test demo[] = {\n"
18223                "    {56,    23, \"hello\"},\n"
18224                "    {-1, 93463, \"world\"},\n"
18225                "    { 7,     5,    \"!!\"}\n"
18226                "};\n"
18227                "struct test demo[4] = {\n"
18228                "    { 56,    23, 21,       \"oh\"}, // first line\n"
18229                "    { -1, 93463, 22,       \"my\"}, // second line\n"
18230                "    {  7,     5,  1, \"goodness\"}  // third line\n"
18231                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
18232                "};\n",
18233                Style);
18234   EXPECT_EQ(
18235       "test demo[] = {\n"
18236       "    {56,\n"
18237       "     \"hello world i am a very long line that really, in any just world"
18238       ", ought to be split over \"\n"
18239       "     \"multiple lines\",    23},\n"
18240       "    {-1,      \"world\", 93463},\n"
18241       "    { 7,         \"!!\",     5},\n"
18242       "};",
18243       format("test demo[] = {{56, \"hello world i am a very long line "
18244              "that really, in any just world, ought to be split over multiple "
18245              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
18246              Style));
18247 }
18248 
18249 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
18250   auto Style = getLLVMStyle();
18251   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18252   /* FIXME: This case gets misformatted.
18253   verifyFormat("auto foo = Items{\n"
18254                "    Section{0, bar(), },\n"
18255                "    Section{1, boo()  }\n"
18256                "};\n",
18257                Style);
18258   */
18259   verifyFormat("auto foo = Items{\n"
18260                "    Section{\n"
18261                "            0, bar(),\n"
18262                "            }\n"
18263                "};\n",
18264                Style);
18265   verifyFormat("struct test demo[] = {\n"
18266                "    {56, 23,    \"hello\"},\n"
18267                "    {-1, 93463, \"world\"},\n"
18268                "    {7,  5,     \"!!\"   }\n"
18269                "};\n",
18270                Style);
18271   verifyFormat("struct test demo[] = {\n"
18272                "    {56, 23,    \"hello\"}, // first line\n"
18273                "    {-1, 93463, \"world\"}, // second line\n"
18274                "    {7,  5,     \"!!\"   }  // third line\n"
18275                "};\n",
18276                Style);
18277   verifyFormat("struct test demo[4] = {\n"
18278                "    {56,  23,    21, \"oh\"      }, // first line\n"
18279                "    {-1,  93463, 22, \"my\"      }, // second line\n"
18280                "    {7,   5,     1,  \"goodness\"}  // third line\n"
18281                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
18282                "};\n",
18283                Style);
18284   verifyFormat("struct test demo[3] = {\n"
18285                "    {56, 23,    \"hello\"},\n"
18286                "    {-1, 93463, \"world\"},\n"
18287                "    {7,  5,     \"!!\"   }\n"
18288                "};\n",
18289                Style);
18290 
18291   verifyFormat("struct test demo[3] = {\n"
18292                "    {int{56}, 23,    \"hello\"},\n"
18293                "    {int{-1}, 93463, \"world\"},\n"
18294                "    {int{7},  5,     \"!!\"   }\n"
18295                "};\n",
18296                Style);
18297   verifyFormat("struct test demo[] = {\n"
18298                "    {56, 23,    \"hello\"},\n"
18299                "    {-1, 93463, \"world\"},\n"
18300                "    {7,  5,     \"!!\"   },\n"
18301                "};\n",
18302                Style);
18303   verifyFormat("test demo[] = {\n"
18304                "    {56, 23,    \"hello\"},\n"
18305                "    {-1, 93463, \"world\"},\n"
18306                "    {7,  5,     \"!!\"   },\n"
18307                "};\n",
18308                Style);
18309   verifyFormat("demo = std::array<struct test, 3>{\n"
18310                "    test{56, 23,    \"hello\"},\n"
18311                "    test{-1, 93463, \"world\"},\n"
18312                "    test{7,  5,     \"!!\"   },\n"
18313                "};\n",
18314                Style);
18315   verifyFormat("test demo[] = {\n"
18316                "    {56, 23,    \"hello\"},\n"
18317                "#if X\n"
18318                "    {-1, 93463, \"world\"},\n"
18319                "#endif\n"
18320                "    {7,  5,     \"!!\"   }\n"
18321                "};\n",
18322                Style);
18323   verifyFormat(
18324       "test demo[] = {\n"
18325       "    {7,  23,\n"
18326       "     \"hello world i am a very long line that really, in any\"\n"
18327       "     \"just world, ought to be split over multiple lines\"},\n"
18328       "    {-1, 93463, \"world\"                                 },\n"
18329       "    {56, 5,     \"!!\"                                    }\n"
18330       "};\n",
18331       Style);
18332 
18333   verifyFormat("return GradForUnaryCwise(g, {\n"
18334                "                                {{\"sign\"}, \"Sign\", {\"x\", "
18335                "\"dy\"}   },\n"
18336                "                                {{\"dx\"},   \"Mul\",  "
18337                "{\"dy\", \"sign\"}},\n"
18338                "});\n",
18339                Style);
18340 
18341   Style.ColumnLimit = 0;
18342   EXPECT_EQ(
18343       "test demo[] = {\n"
18344       "    {56, 23,    \"hello world i am a very long line that really, in any "
18345       "just world, ought to be split over multiple lines\"},\n"
18346       "    {-1, 93463, \"world\"                                               "
18347       "                                                   },\n"
18348       "    {7,  5,     \"!!\"                                                  "
18349       "                                                   },\n"
18350       "};",
18351       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18352              "that really, in any just world, ought to be split over multiple "
18353              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18354              Style));
18355 
18356   Style.ColumnLimit = 80;
18357   verifyFormat("test demo[] = {\n"
18358                "    {56, 23,    /* a comment */ \"hello\"},\n"
18359                "    {-1, 93463, \"world\"                },\n"
18360                "    {7,  5,     \"!!\"                   }\n"
18361                "};\n",
18362                Style);
18363 
18364   verifyFormat("test demo[] = {\n"
18365                "    {56, 23,    \"hello\"                   },\n"
18366                "    {-1, 93463, \"world\" /* comment here */},\n"
18367                "    {7,  5,     \"!!\"                      }\n"
18368                "};\n",
18369                Style);
18370 
18371   verifyFormat("test demo[] = {\n"
18372                "    {56, /* a comment */ 23, \"hello\"},\n"
18373                "    {-1, 93463,              \"world\"},\n"
18374                "    {7,  5,                  \"!!\"   }\n"
18375                "};\n",
18376                Style);
18377 
18378   Style.ColumnLimit = 20;
18379   EXPECT_EQ(
18380       "demo = std::array<\n"
18381       "    struct test, 3>{\n"
18382       "    test{\n"
18383       "         56, 23,\n"
18384       "         \"hello \"\n"
18385       "         \"world i \"\n"
18386       "         \"am a very \"\n"
18387       "         \"long line \"\n"
18388       "         \"that \"\n"
18389       "         \"really, \"\n"
18390       "         \"in any \"\n"
18391       "         \"just \"\n"
18392       "         \"world, \"\n"
18393       "         \"ought to \"\n"
18394       "         \"be split \"\n"
18395       "         \"over \"\n"
18396       "         \"multiple \"\n"
18397       "         \"lines\"},\n"
18398       "    test{-1, 93463,\n"
18399       "         \"world\"},\n"
18400       "    test{7,  5,\n"
18401       "         \"!!\"   },\n"
18402       "};",
18403       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
18404              "i am a very long line that really, in any just world, ought "
18405              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
18406              "test{7, 5, \"!!\"},};",
18407              Style));
18408 
18409   // This caused a core dump by enabling Alignment in the LLVMStyle globally
18410   Style = getLLVMStyleWithColumns(50);
18411   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
18412   verifyFormat("static A x = {\n"
18413                "    {{init1, init2, init3, init4},\n"
18414                "     {init1, init2, init3, init4}}\n"
18415                "};",
18416                Style);
18417   Style.ColumnLimit = 100;
18418   EXPECT_EQ(
18419       "test demo[] = {\n"
18420       "    {56, 23,\n"
18421       "     \"hello world i am a very long line that really, in any just world"
18422       ", ought to be split over \"\n"
18423       "     \"multiple lines\"  },\n"
18424       "    {-1, 93463, \"world\"},\n"
18425       "    {7,  5,     \"!!\"   },\n"
18426       "};",
18427       format("test demo[] = {{56, 23, \"hello world i am a very long line "
18428              "that really, in any just world, ought to be split over multiple "
18429              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
18430              Style));
18431 }
18432 
18433 TEST_F(FormatTest, UnderstandsPragmas) {
18434   verifyFormat("#pragma omp reduction(| : var)");
18435   verifyFormat("#pragma omp reduction(+ : var)");
18436 
18437   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
18438             "(including parentheses).",
18439             format("#pragma    mark   Any non-hyphenated or hyphenated string "
18440                    "(including parentheses)."));
18441 }
18442 
18443 TEST_F(FormatTest, UnderstandPragmaOption) {
18444   verifyFormat("#pragma option -C -A");
18445 
18446   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
18447 }
18448 
18449 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
18450   FormatStyle Style = getLLVMStyleWithColumns(20);
18451 
18452   // See PR41213
18453   EXPECT_EQ("/*\n"
18454             " *\t9012345\n"
18455             " * /8901\n"
18456             " */",
18457             format("/*\n"
18458                    " *\t9012345 /8901\n"
18459                    " */",
18460                    Style));
18461   EXPECT_EQ("/*\n"
18462             " *345678\n"
18463             " *\t/8901\n"
18464             " */",
18465             format("/*\n"
18466                    " *345678\t/8901\n"
18467                    " */",
18468                    Style));
18469 
18470   verifyFormat("int a; // the\n"
18471                "       // comment",
18472                Style);
18473   EXPECT_EQ("int a; /* first line\n"
18474             "        * second\n"
18475             "        * line third\n"
18476             "        * line\n"
18477             "        */",
18478             format("int a; /* first line\n"
18479                    "        * second\n"
18480                    "        * line third\n"
18481                    "        * line\n"
18482                    "        */",
18483                    Style));
18484   EXPECT_EQ("int a; // first line\n"
18485             "       // second\n"
18486             "       // line third\n"
18487             "       // line",
18488             format("int a; // first line\n"
18489                    "       // second line\n"
18490                    "       // third line",
18491                    Style));
18492 
18493   Style.PenaltyExcessCharacter = 90;
18494   verifyFormat("int a; // the comment", Style);
18495   EXPECT_EQ("int a; // the comment\n"
18496             "       // aaa",
18497             format("int a; // the comment aaa", Style));
18498   EXPECT_EQ("int a; /* first line\n"
18499             "        * second line\n"
18500             "        * third line\n"
18501             "        */",
18502             format("int a; /* first line\n"
18503                    "        * second line\n"
18504                    "        * third line\n"
18505                    "        */",
18506                    Style));
18507   EXPECT_EQ("int a; // first line\n"
18508             "       // second line\n"
18509             "       // third line",
18510             format("int a; // first line\n"
18511                    "       // second line\n"
18512                    "       // third line",
18513                    Style));
18514   // FIXME: Investigate why this is not getting the same layout as the test
18515   // above.
18516   EXPECT_EQ("int a; /* first line\n"
18517             "        * second line\n"
18518             "        * third line\n"
18519             "        */",
18520             format("int a; /* first line second line third line"
18521                    "\n*/",
18522                    Style));
18523 
18524   EXPECT_EQ("// foo bar baz bazfoo\n"
18525             "// foo bar foo bar\n",
18526             format("// foo bar baz bazfoo\n"
18527                    "// foo bar foo           bar\n",
18528                    Style));
18529   EXPECT_EQ("// foo bar baz bazfoo\n"
18530             "// foo bar foo bar\n",
18531             format("// foo bar baz      bazfoo\n"
18532                    "// foo            bar foo bar\n",
18533                    Style));
18534 
18535   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
18536   // next one.
18537   EXPECT_EQ("// foo bar baz bazfoo\n"
18538             "// bar foo bar\n",
18539             format("// foo bar baz      bazfoo bar\n"
18540                    "// foo            bar\n",
18541                    Style));
18542 
18543   EXPECT_EQ("// foo bar baz bazfoo\n"
18544             "// foo bar baz bazfoo\n"
18545             "// bar foo bar\n",
18546             format("// foo bar baz      bazfoo\n"
18547                    "// foo bar baz      bazfoo bar\n"
18548                    "// foo bar\n",
18549                    Style));
18550 
18551   EXPECT_EQ("// foo bar baz bazfoo\n"
18552             "// foo bar baz bazfoo\n"
18553             "// bar foo bar\n",
18554             format("// foo bar baz      bazfoo\n"
18555                    "// foo bar baz      bazfoo bar\n"
18556                    "// foo           bar\n",
18557                    Style));
18558 
18559   // Make sure we do not keep protruding characters if strict mode reflow is
18560   // cheaper than keeping protruding characters.
18561   Style.ColumnLimit = 21;
18562   EXPECT_EQ(
18563       "// foo foo foo foo\n"
18564       "// foo foo foo foo\n"
18565       "// foo foo foo foo\n",
18566       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
18567 
18568   EXPECT_EQ("int a = /* long block\n"
18569             "           comment */\n"
18570             "    42;",
18571             format("int a = /* long block comment */ 42;", Style));
18572 }
18573 
18574 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
18575   FormatStyle Style = getLLVMStyle();
18576   Style.ColumnLimit = 8;
18577   Style.PenaltyExcessCharacter = 15;
18578   verifyFormat("int foo(\n"
18579                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
18580                Style);
18581   Style.PenaltyBreakOpenParenthesis = 200;
18582   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
18583             format("int foo(\n"
18584                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
18585                    Style));
18586 }
18587 
18588 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
18589   FormatStyle Style = getLLVMStyle();
18590   Style.ColumnLimit = 5;
18591   Style.PenaltyExcessCharacter = 150;
18592   verifyFormat("foo((\n"
18593                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
18594 
18595                Style);
18596   Style.PenaltyBreakOpenParenthesis = 100000;
18597   EXPECT_EQ("foo((int)\n"
18598             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
18599             format("foo((\n"
18600                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
18601                    Style));
18602 }
18603 
18604 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
18605   FormatStyle Style = getLLVMStyle();
18606   Style.ColumnLimit = 4;
18607   Style.PenaltyExcessCharacter = 100;
18608   verifyFormat("for (\n"
18609                "    int iiiiiiiiiiiiiiiii =\n"
18610                "        0;\n"
18611                "    iiiiiiiiiiiiiiiii <\n"
18612                "    2;\n"
18613                "    iiiiiiiiiiiiiiiii++) {\n"
18614                "}",
18615 
18616                Style);
18617   Style.PenaltyBreakOpenParenthesis = 1250;
18618   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
18619             "         0;\n"
18620             "     iiiiiiiiiiiiiiiii <\n"
18621             "     2;\n"
18622             "     iiiiiiiiiiiiiiiii++) {\n"
18623             "}",
18624             format("for (\n"
18625                    "    int iiiiiiiiiiiiiiiii =\n"
18626                    "        0;\n"
18627                    "    iiiiiiiiiiiiiiiii <\n"
18628                    "    2;\n"
18629                    "    iiiiiiiiiiiiiiiii++) {\n"
18630                    "}",
18631                    Style));
18632 }
18633 
18634 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
18635   for (size_t i = 1; i < Styles.size(); ++i)                                   \
18636   EXPECT_EQ(Styles[0], Styles[i])                                              \
18637       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
18638 
18639 TEST_F(FormatTest, GetsPredefinedStyleByName) {
18640   SmallVector<FormatStyle, 3> Styles;
18641   Styles.resize(3);
18642 
18643   Styles[0] = getLLVMStyle();
18644   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
18645   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
18646   EXPECT_ALL_STYLES_EQUAL(Styles);
18647 
18648   Styles[0] = getGoogleStyle();
18649   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
18650   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
18651   EXPECT_ALL_STYLES_EQUAL(Styles);
18652 
18653   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18654   EXPECT_TRUE(
18655       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
18656   EXPECT_TRUE(
18657       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
18658   EXPECT_ALL_STYLES_EQUAL(Styles);
18659 
18660   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
18661   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
18662   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
18663   EXPECT_ALL_STYLES_EQUAL(Styles);
18664 
18665   Styles[0] = getMozillaStyle();
18666   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
18667   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
18668   EXPECT_ALL_STYLES_EQUAL(Styles);
18669 
18670   Styles[0] = getWebKitStyle();
18671   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
18672   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
18673   EXPECT_ALL_STYLES_EQUAL(Styles);
18674 
18675   Styles[0] = getGNUStyle();
18676   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
18677   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
18678   EXPECT_ALL_STYLES_EQUAL(Styles);
18679 
18680   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
18681 }
18682 
18683 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
18684   SmallVector<FormatStyle, 8> Styles;
18685   Styles.resize(2);
18686 
18687   Styles[0] = getGoogleStyle();
18688   Styles[1] = getLLVMStyle();
18689   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18690   EXPECT_ALL_STYLES_EQUAL(Styles);
18691 
18692   Styles.resize(5);
18693   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18694   Styles[1] = getLLVMStyle();
18695   Styles[1].Language = FormatStyle::LK_JavaScript;
18696   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18697 
18698   Styles[2] = getLLVMStyle();
18699   Styles[2].Language = FormatStyle::LK_JavaScript;
18700   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
18701                                   "BasedOnStyle: Google",
18702                                   &Styles[2])
18703                    .value());
18704 
18705   Styles[3] = getLLVMStyle();
18706   Styles[3].Language = FormatStyle::LK_JavaScript;
18707   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
18708                                   "Language: JavaScript",
18709                                   &Styles[3])
18710                    .value());
18711 
18712   Styles[4] = getLLVMStyle();
18713   Styles[4].Language = FormatStyle::LK_JavaScript;
18714   EXPECT_EQ(0, parseConfiguration("---\n"
18715                                   "BasedOnStyle: LLVM\n"
18716                                   "IndentWidth: 123\n"
18717                                   "---\n"
18718                                   "BasedOnStyle: Google\n"
18719                                   "Language: JavaScript",
18720                                   &Styles[4])
18721                    .value());
18722   EXPECT_ALL_STYLES_EQUAL(Styles);
18723 }
18724 
18725 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
18726   Style.FIELD = false;                                                         \
18727   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
18728   EXPECT_TRUE(Style.FIELD);                                                    \
18729   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
18730   EXPECT_FALSE(Style.FIELD);
18731 
18732 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
18733 
18734 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
18735   Style.STRUCT.FIELD = false;                                                  \
18736   EXPECT_EQ(0,                                                                 \
18737             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
18738                 .value());                                                     \
18739   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
18740   EXPECT_EQ(0,                                                                 \
18741             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
18742                 .value());                                                     \
18743   EXPECT_FALSE(Style.STRUCT.FIELD);
18744 
18745 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
18746   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
18747 
18748 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
18749   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
18750   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
18751   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
18752 
18753 TEST_F(FormatTest, ParsesConfigurationBools) {
18754   FormatStyle Style = {};
18755   Style.Language = FormatStyle::LK_Cpp;
18756   CHECK_PARSE_BOOL(AlignTrailingComments);
18757   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
18758   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
18759   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
18760   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
18761   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
18762   CHECK_PARSE_BOOL(BinPackArguments);
18763   CHECK_PARSE_BOOL(BinPackParameters);
18764   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
18765   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
18766   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
18767   CHECK_PARSE_BOOL(BreakStringLiterals);
18768   CHECK_PARSE_BOOL(CompactNamespaces);
18769   CHECK_PARSE_BOOL(DeriveLineEnding);
18770   CHECK_PARSE_BOOL(DerivePointerAlignment);
18771   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
18772   CHECK_PARSE_BOOL(DisableFormat);
18773   CHECK_PARSE_BOOL(IndentAccessModifiers);
18774   CHECK_PARSE_BOOL(IndentCaseLabels);
18775   CHECK_PARSE_BOOL(IndentCaseBlocks);
18776   CHECK_PARSE_BOOL(IndentGotoLabels);
18777   CHECK_PARSE_BOOL(IndentRequires);
18778   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
18779   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
18780   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
18781   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
18782   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
18783   CHECK_PARSE_BOOL(ReflowComments);
18784   CHECK_PARSE_BOOL(SortUsingDeclarations);
18785   CHECK_PARSE_BOOL(SpacesInParentheses);
18786   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
18787   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
18788   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
18789   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
18790   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
18791   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
18792   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
18793   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
18794   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
18795   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
18796   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
18797   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
18798   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
18799   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
18800   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
18801   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
18802   CHECK_PARSE_BOOL(UseCRLF);
18803 
18804   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
18805   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
18806   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
18807   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
18808   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
18809   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
18810   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
18811   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
18812   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
18813   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
18814   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
18815   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
18816   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
18817   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
18818   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
18819   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
18820   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
18821   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
18822   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
18823   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
18824                           AfterFunctionDeclarationName);
18825   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
18826                           AfterFunctionDefinitionName);
18827   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
18828   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
18829   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
18830 }
18831 
18832 #undef CHECK_PARSE_BOOL
18833 
18834 TEST_F(FormatTest, ParsesConfiguration) {
18835   FormatStyle Style = {};
18836   Style.Language = FormatStyle::LK_Cpp;
18837   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
18838   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
18839               ConstructorInitializerIndentWidth, 1234u);
18840   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
18841   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
18842   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
18843   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
18844   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
18845               PenaltyBreakBeforeFirstCallParameter, 1234u);
18846   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
18847               PenaltyBreakTemplateDeclaration, 1234u);
18848   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
18849               1234u);
18850   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
18851   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
18852               PenaltyReturnTypeOnItsOwnLine, 1234u);
18853   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
18854               SpacesBeforeTrailingComments, 1234u);
18855   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
18856   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
18857   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
18858 
18859   Style.QualifierAlignment = FormatStyle::QAS_Right;
18860   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
18861               FormatStyle::QAS_Leave);
18862   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
18863               FormatStyle::QAS_Right);
18864   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
18865               FormatStyle::QAS_Left);
18866   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
18867               FormatStyle::QAS_Custom);
18868 
18869   Style.QualifierOrder.clear();
18870   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
18871               std::vector<std::string>({"const", "volatile", "type"}));
18872   Style.QualifierOrder.clear();
18873   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
18874               std::vector<std::string>({"const", "type"}));
18875   Style.QualifierOrder.clear();
18876   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
18877               std::vector<std::string>({"volatile", "type"}));
18878 
18879   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
18880   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
18881               FormatStyle::ACS_None);
18882   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
18883               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
18884   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
18885               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
18886   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
18887               AlignConsecutiveAssignments,
18888               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18889   // For backwards compability, false / true should still parse
18890   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
18891               FormatStyle::ACS_None);
18892   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
18893               FormatStyle::ACS_Consecutive);
18894 
18895   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
18896   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
18897               FormatStyle::ACS_None);
18898   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
18899               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
18900   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
18901               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
18902   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
18903               AlignConsecutiveBitFields,
18904               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18905   // For backwards compability, false / true should still parse
18906   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
18907               FormatStyle::ACS_None);
18908   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
18909               FormatStyle::ACS_Consecutive);
18910 
18911   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
18912   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
18913               FormatStyle::ACS_None);
18914   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
18915               FormatStyle::ACS_Consecutive);
18916   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
18917               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
18918   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
18919               AlignConsecutiveMacros,
18920               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18921   // For backwards compability, false / true should still parse
18922   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
18923               FormatStyle::ACS_None);
18924   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
18925               FormatStyle::ACS_Consecutive);
18926 
18927   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
18928   CHECK_PARSE("AlignConsecutiveDeclarations: None",
18929               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
18930   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
18931               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
18932   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
18933               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
18934   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
18935               AlignConsecutiveDeclarations,
18936               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18937   // For backwards compability, false / true should still parse
18938   CHECK_PARSE("AlignConsecutiveDeclarations: false",
18939               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
18940   CHECK_PARSE("AlignConsecutiveDeclarations: true",
18941               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
18942 
18943   Style.PointerAlignment = FormatStyle::PAS_Middle;
18944   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
18945               FormatStyle::PAS_Left);
18946   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
18947               FormatStyle::PAS_Right);
18948   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
18949               FormatStyle::PAS_Middle);
18950   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
18951   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
18952               FormatStyle::RAS_Pointer);
18953   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
18954               FormatStyle::RAS_Left);
18955   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
18956               FormatStyle::RAS_Right);
18957   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
18958               FormatStyle::RAS_Middle);
18959   // For backward compatibility:
18960   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
18961               FormatStyle::PAS_Left);
18962   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
18963               FormatStyle::PAS_Right);
18964   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
18965               FormatStyle::PAS_Middle);
18966 
18967   Style.Standard = FormatStyle::LS_Auto;
18968   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
18969   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
18970   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
18971   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
18972   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
18973   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
18974   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
18975   // Legacy aliases:
18976   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
18977   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
18978   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
18979   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
18980 
18981   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
18982   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
18983               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
18984   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
18985               FormatStyle::BOS_None);
18986   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
18987               FormatStyle::BOS_All);
18988   // For backward compatibility:
18989   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
18990               FormatStyle::BOS_None);
18991   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
18992               FormatStyle::BOS_All);
18993 
18994   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
18995   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
18996               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
18997   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
18998               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
18999   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
19000               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
19001   // For backward compatibility:
19002   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
19003               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
19004 
19005   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
19006   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
19007               FormatStyle::BILS_AfterComma);
19008   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
19009               FormatStyle::BILS_BeforeComma);
19010   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
19011               FormatStyle::BILS_AfterColon);
19012   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
19013               FormatStyle::BILS_BeforeColon);
19014   // For backward compatibility:
19015   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
19016               FormatStyle::BILS_BeforeComma);
19017 
19018   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19019   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
19020               FormatStyle::PCIS_Never);
19021   CHECK_PARSE("PackConstructorInitializers: BinPack",
19022               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19023   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
19024               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19025   CHECK_PARSE("PackConstructorInitializers: NextLine",
19026               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19027   // For backward compatibility:
19028   CHECK_PARSE("BasedOnStyle: Google\n"
19029               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19030               "AllowAllConstructorInitializersOnNextLine: false",
19031               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19032   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19033   CHECK_PARSE("BasedOnStyle: Google\n"
19034               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
19035               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
19036   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19037               "AllowAllConstructorInitializersOnNextLine: true",
19038               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
19039   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
19040   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
19041               "AllowAllConstructorInitializersOnNextLine: false",
19042               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
19043 
19044   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
19045   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
19046               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
19047   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
19048               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
19049   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
19050               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
19051   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
19052               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
19053 
19054   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19055   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
19056               FormatStyle::BAS_Align);
19057   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
19058               FormatStyle::BAS_DontAlign);
19059   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
19060               FormatStyle::BAS_AlwaysBreak);
19061   // For backward compatibility:
19062   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
19063               FormatStyle::BAS_DontAlign);
19064   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
19065               FormatStyle::BAS_Align);
19066 
19067   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
19068   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
19069               FormatStyle::ENAS_DontAlign);
19070   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
19071               FormatStyle::ENAS_Left);
19072   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
19073               FormatStyle::ENAS_Right);
19074   // For backward compatibility:
19075   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
19076               FormatStyle::ENAS_Left);
19077   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
19078               FormatStyle::ENAS_Right);
19079 
19080   Style.AlignOperands = FormatStyle::OAS_Align;
19081   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
19082               FormatStyle::OAS_DontAlign);
19083   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
19084   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
19085               FormatStyle::OAS_AlignAfterOperator);
19086   // For backward compatibility:
19087   CHECK_PARSE("AlignOperands: false", AlignOperands,
19088               FormatStyle::OAS_DontAlign);
19089   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
19090 
19091   Style.UseTab = FormatStyle::UT_ForIndentation;
19092   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
19093   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
19094   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
19095   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
19096               FormatStyle::UT_ForContinuationAndIndentation);
19097   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
19098               FormatStyle::UT_AlignWithSpaces);
19099   // For backward compatibility:
19100   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
19101   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
19102 
19103   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
19104   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
19105               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19106   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
19107               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
19108   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
19109               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19110   // For backward compatibility:
19111   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
19112               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
19113   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
19114               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
19115 
19116   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
19117   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
19118               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19119   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
19120               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
19121   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
19122               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
19123   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
19124               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19125   // For backward compatibility:
19126   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
19127               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
19128   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
19129               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
19130 
19131   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
19132   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
19133               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
19134   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
19135               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
19136   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
19137               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
19138   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
19139               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
19140 
19141   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
19142   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
19143               FormatStyle::SBPO_Never);
19144   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
19145               FormatStyle::SBPO_Always);
19146   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
19147               FormatStyle::SBPO_ControlStatements);
19148   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
19149               SpaceBeforeParens,
19150               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19151   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
19152               FormatStyle::SBPO_NonEmptyParentheses);
19153   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
19154               FormatStyle::SBPO_Custom);
19155   // For backward compatibility:
19156   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
19157               FormatStyle::SBPO_Never);
19158   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
19159               FormatStyle::SBPO_ControlStatements);
19160   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
19161               SpaceBeforeParens,
19162               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
19163 
19164   Style.ColumnLimit = 123;
19165   FormatStyle BaseStyle = getLLVMStyle();
19166   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
19167   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
19168 
19169   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
19170   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
19171               FormatStyle::BS_Attach);
19172   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
19173               FormatStyle::BS_Linux);
19174   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
19175               FormatStyle::BS_Mozilla);
19176   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
19177               FormatStyle::BS_Stroustrup);
19178   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
19179               FormatStyle::BS_Allman);
19180   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
19181               FormatStyle::BS_Whitesmiths);
19182   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
19183   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
19184               FormatStyle::BS_WebKit);
19185   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
19186               FormatStyle::BS_Custom);
19187 
19188   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
19189   CHECK_PARSE("BraceWrapping:\n"
19190               "  AfterControlStatement: MultiLine",
19191               BraceWrapping.AfterControlStatement,
19192               FormatStyle::BWACS_MultiLine);
19193   CHECK_PARSE("BraceWrapping:\n"
19194               "  AfterControlStatement: Always",
19195               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19196   CHECK_PARSE("BraceWrapping:\n"
19197               "  AfterControlStatement: Never",
19198               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19199   // For backward compatibility:
19200   CHECK_PARSE("BraceWrapping:\n"
19201               "  AfterControlStatement: true",
19202               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
19203   CHECK_PARSE("BraceWrapping:\n"
19204               "  AfterControlStatement: false",
19205               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
19206 
19207   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
19208   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
19209               FormatStyle::RTBS_None);
19210   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
19211               FormatStyle::RTBS_All);
19212   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
19213               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
19214   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
19215               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
19216   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
19217               AlwaysBreakAfterReturnType,
19218               FormatStyle::RTBS_TopLevelDefinitions);
19219 
19220   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
19221   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
19222               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
19223   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
19224               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19225   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
19226               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19227   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
19228               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
19229   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
19230               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
19231 
19232   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
19233   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
19234               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
19235   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
19236               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
19237   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
19238               AlwaysBreakAfterDefinitionReturnType,
19239               FormatStyle::DRTBS_TopLevel);
19240 
19241   Style.NamespaceIndentation = FormatStyle::NI_All;
19242   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
19243               FormatStyle::NI_None);
19244   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
19245               FormatStyle::NI_Inner);
19246   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
19247               FormatStyle::NI_All);
19248 
19249   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
19250   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
19251               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19252   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
19253               AllowShortIfStatementsOnASingleLine,
19254               FormatStyle::SIS_WithoutElse);
19255   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
19256               AllowShortIfStatementsOnASingleLine,
19257               FormatStyle::SIS_OnlyFirstIf);
19258   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
19259               AllowShortIfStatementsOnASingleLine,
19260               FormatStyle::SIS_AllIfsAndElse);
19261   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
19262               AllowShortIfStatementsOnASingleLine,
19263               FormatStyle::SIS_OnlyFirstIf);
19264   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
19265               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
19266   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
19267               AllowShortIfStatementsOnASingleLine,
19268               FormatStyle::SIS_WithoutElse);
19269 
19270   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
19271   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
19272               FormatStyle::IEBS_AfterExternBlock);
19273   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
19274               FormatStyle::IEBS_Indent);
19275   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
19276               FormatStyle::IEBS_NoIndent);
19277   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
19278               FormatStyle::IEBS_Indent);
19279   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
19280               FormatStyle::IEBS_NoIndent);
19281 
19282   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
19283   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
19284               FormatStyle::BFCS_Both);
19285   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
19286               FormatStyle::BFCS_None);
19287   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
19288               FormatStyle::BFCS_Before);
19289   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
19290               FormatStyle::BFCS_After);
19291 
19292   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
19293   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
19294               FormatStyle::SJSIO_After);
19295   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
19296               FormatStyle::SJSIO_Before);
19297 
19298   // FIXME: This is required because parsing a configuration simply overwrites
19299   // the first N elements of the list instead of resetting it.
19300   Style.ForEachMacros.clear();
19301   std::vector<std::string> BoostForeach;
19302   BoostForeach.push_back("BOOST_FOREACH");
19303   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
19304   std::vector<std::string> BoostAndQForeach;
19305   BoostAndQForeach.push_back("BOOST_FOREACH");
19306   BoostAndQForeach.push_back("Q_FOREACH");
19307   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
19308               BoostAndQForeach);
19309 
19310   Style.IfMacros.clear();
19311   std::vector<std::string> CustomIfs;
19312   CustomIfs.push_back("MYIF");
19313   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
19314 
19315   Style.AttributeMacros.clear();
19316   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
19317               std::vector<std::string>{"__capability"});
19318   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
19319               std::vector<std::string>({"attr1", "attr2"}));
19320 
19321   Style.StatementAttributeLikeMacros.clear();
19322   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
19323               StatementAttributeLikeMacros,
19324               std::vector<std::string>({"emit", "Q_EMIT"}));
19325 
19326   Style.StatementMacros.clear();
19327   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
19328               std::vector<std::string>{"QUNUSED"});
19329   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
19330               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
19331 
19332   Style.NamespaceMacros.clear();
19333   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
19334               std::vector<std::string>{"TESTSUITE"});
19335   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
19336               std::vector<std::string>({"TESTSUITE", "SUITE"}));
19337 
19338   Style.WhitespaceSensitiveMacros.clear();
19339   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
19340               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
19341   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
19342               WhitespaceSensitiveMacros,
19343               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
19344   Style.WhitespaceSensitiveMacros.clear();
19345   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
19346               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
19347   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
19348               WhitespaceSensitiveMacros,
19349               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
19350 
19351   Style.IncludeStyle.IncludeCategories.clear();
19352   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
19353       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
19354   CHECK_PARSE("IncludeCategories:\n"
19355               "  - Regex: abc/.*\n"
19356               "    Priority: 2\n"
19357               "  - Regex: .*\n"
19358               "    Priority: 1\n"
19359               "    CaseSensitive: true\n",
19360               IncludeStyle.IncludeCategories, ExpectedCategories);
19361   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
19362               "abc$");
19363   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
19364               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
19365 
19366   Style.SortIncludes = FormatStyle::SI_Never;
19367   CHECK_PARSE("SortIncludes: true", SortIncludes,
19368               FormatStyle::SI_CaseSensitive);
19369   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
19370   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
19371               FormatStyle::SI_CaseInsensitive);
19372   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
19373               FormatStyle::SI_CaseSensitive);
19374   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
19375 
19376   Style.RawStringFormats.clear();
19377   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
19378       {
19379           FormatStyle::LK_TextProto,
19380           {"pb", "proto"},
19381           {"PARSE_TEXT_PROTO"},
19382           /*CanonicalDelimiter=*/"",
19383           "llvm",
19384       },
19385       {
19386           FormatStyle::LK_Cpp,
19387           {"cc", "cpp"},
19388           {"C_CODEBLOCK", "CPPEVAL"},
19389           /*CanonicalDelimiter=*/"cc",
19390           /*BasedOnStyle=*/"",
19391       },
19392   };
19393 
19394   CHECK_PARSE("RawStringFormats:\n"
19395               "  - Language: TextProto\n"
19396               "    Delimiters:\n"
19397               "      - 'pb'\n"
19398               "      - 'proto'\n"
19399               "    EnclosingFunctions:\n"
19400               "      - 'PARSE_TEXT_PROTO'\n"
19401               "    BasedOnStyle: llvm\n"
19402               "  - Language: Cpp\n"
19403               "    Delimiters:\n"
19404               "      - 'cc'\n"
19405               "      - 'cpp'\n"
19406               "    EnclosingFunctions:\n"
19407               "      - 'C_CODEBLOCK'\n"
19408               "      - 'CPPEVAL'\n"
19409               "    CanonicalDelimiter: 'cc'",
19410               RawStringFormats, ExpectedRawStringFormats);
19411 
19412   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19413               "  Minimum: 0\n"
19414               "  Maximum: 0",
19415               SpacesInLineCommentPrefix.Minimum, 0u);
19416   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
19417   Style.SpacesInLineCommentPrefix.Minimum = 1;
19418   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19419               "  Minimum: 2",
19420               SpacesInLineCommentPrefix.Minimum, 0u);
19421   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19422               "  Maximum: -1",
19423               SpacesInLineCommentPrefix.Maximum, -1u);
19424   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19425               "  Minimum: 2",
19426               SpacesInLineCommentPrefix.Minimum, 2u);
19427   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
19428               "  Maximum: 1",
19429               SpacesInLineCommentPrefix.Maximum, 1u);
19430   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
19431 
19432   Style.SpacesInAngles = FormatStyle::SIAS_Always;
19433   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
19434   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
19435               FormatStyle::SIAS_Always);
19436   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
19437   // For backward compatibility:
19438   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
19439   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
19440 }
19441 
19442 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
19443   FormatStyle Style = {};
19444   Style.Language = FormatStyle::LK_Cpp;
19445   CHECK_PARSE("Language: Cpp\n"
19446               "IndentWidth: 12",
19447               IndentWidth, 12u);
19448   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
19449                                "IndentWidth: 34",
19450                                &Style),
19451             ParseError::Unsuitable);
19452   FormatStyle BinPackedTCS = {};
19453   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
19454   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
19455                                "InsertTrailingCommas: Wrapped",
19456                                &BinPackedTCS),
19457             ParseError::BinPackTrailingCommaConflict);
19458   EXPECT_EQ(12u, Style.IndentWidth);
19459   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
19460   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19461 
19462   Style.Language = FormatStyle::LK_JavaScript;
19463   CHECK_PARSE("Language: JavaScript\n"
19464               "IndentWidth: 12",
19465               IndentWidth, 12u);
19466   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
19467   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
19468                                "IndentWidth: 34",
19469                                &Style),
19470             ParseError::Unsuitable);
19471   EXPECT_EQ(23u, Style.IndentWidth);
19472   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
19473   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19474 
19475   CHECK_PARSE("BasedOnStyle: LLVM\n"
19476               "IndentWidth: 67",
19477               IndentWidth, 67u);
19478 
19479   CHECK_PARSE("---\n"
19480               "Language: JavaScript\n"
19481               "IndentWidth: 12\n"
19482               "---\n"
19483               "Language: Cpp\n"
19484               "IndentWidth: 34\n"
19485               "...\n",
19486               IndentWidth, 12u);
19487 
19488   Style.Language = FormatStyle::LK_Cpp;
19489   CHECK_PARSE("---\n"
19490               "Language: JavaScript\n"
19491               "IndentWidth: 12\n"
19492               "---\n"
19493               "Language: Cpp\n"
19494               "IndentWidth: 34\n"
19495               "...\n",
19496               IndentWidth, 34u);
19497   CHECK_PARSE("---\n"
19498               "IndentWidth: 78\n"
19499               "---\n"
19500               "Language: JavaScript\n"
19501               "IndentWidth: 56\n"
19502               "...\n",
19503               IndentWidth, 78u);
19504 
19505   Style.ColumnLimit = 123;
19506   Style.IndentWidth = 234;
19507   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
19508   Style.TabWidth = 345;
19509   EXPECT_FALSE(parseConfiguration("---\n"
19510                                   "IndentWidth: 456\n"
19511                                   "BreakBeforeBraces: Allman\n"
19512                                   "---\n"
19513                                   "Language: JavaScript\n"
19514                                   "IndentWidth: 111\n"
19515                                   "TabWidth: 111\n"
19516                                   "---\n"
19517                                   "Language: Cpp\n"
19518                                   "BreakBeforeBraces: Stroustrup\n"
19519                                   "TabWidth: 789\n"
19520                                   "...\n",
19521                                   &Style));
19522   EXPECT_EQ(123u, Style.ColumnLimit);
19523   EXPECT_EQ(456u, Style.IndentWidth);
19524   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
19525   EXPECT_EQ(789u, Style.TabWidth);
19526 
19527   EXPECT_EQ(parseConfiguration("---\n"
19528                                "Language: JavaScript\n"
19529                                "IndentWidth: 56\n"
19530                                "---\n"
19531                                "IndentWidth: 78\n"
19532                                "...\n",
19533                                &Style),
19534             ParseError::Error);
19535   EXPECT_EQ(parseConfiguration("---\n"
19536                                "Language: JavaScript\n"
19537                                "IndentWidth: 56\n"
19538                                "---\n"
19539                                "Language: JavaScript\n"
19540                                "IndentWidth: 78\n"
19541                                "...\n",
19542                                &Style),
19543             ParseError::Error);
19544 
19545   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19546 }
19547 
19548 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
19549   FormatStyle Style = {};
19550   Style.Language = FormatStyle::LK_JavaScript;
19551   Style.BreakBeforeTernaryOperators = true;
19552   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
19553   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19554 
19555   Style.BreakBeforeTernaryOperators = true;
19556   EXPECT_EQ(0, parseConfiguration("---\n"
19557                                   "BasedOnStyle: Google\n"
19558                                   "---\n"
19559                                   "Language: JavaScript\n"
19560                                   "IndentWidth: 76\n"
19561                                   "...\n",
19562                                   &Style)
19563                    .value());
19564   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19565   EXPECT_EQ(76u, Style.IndentWidth);
19566   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19567 }
19568 
19569 TEST_F(FormatTest, ConfigurationRoundTripTest) {
19570   FormatStyle Style = getLLVMStyle();
19571   std::string YAML = configurationAsText(Style);
19572   FormatStyle ParsedStyle = {};
19573   ParsedStyle.Language = FormatStyle::LK_Cpp;
19574   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
19575   EXPECT_EQ(Style, ParsedStyle);
19576 }
19577 
19578 TEST_F(FormatTest, WorksFor8bitEncodings) {
19579   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
19580             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
19581             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
19582             "\"\xef\xee\xf0\xf3...\"",
19583             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
19584                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
19585                    "\xef\xee\xf0\xf3...\"",
19586                    getLLVMStyleWithColumns(12)));
19587 }
19588 
19589 TEST_F(FormatTest, HandlesUTF8BOM) {
19590   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
19591   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
19592             format("\xef\xbb\xbf#include <iostream>"));
19593   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
19594             format("\xef\xbb\xbf\n#include <iostream>"));
19595 }
19596 
19597 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
19598 #if !defined(_MSC_VER)
19599 
19600 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
19601   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
19602                getLLVMStyleWithColumns(35));
19603   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
19604                getLLVMStyleWithColumns(31));
19605   verifyFormat("// Однажды в студёную зимнюю пору...",
19606                getLLVMStyleWithColumns(36));
19607   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
19608   verifyFormat("/* Однажды в студёную зимнюю пору... */",
19609                getLLVMStyleWithColumns(39));
19610   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
19611                getLLVMStyleWithColumns(35));
19612 }
19613 
19614 TEST_F(FormatTest, SplitsUTF8Strings) {
19615   // Non-printable characters' width is currently considered to be the length in
19616   // bytes in UTF8. The characters can be displayed in very different manner
19617   // (zero-width, single width with a substitution glyph, expanded to their code
19618   // (e.g. "<8d>"), so there's no single correct way to handle them.
19619   EXPECT_EQ("\"aaaaÄ\"\n"
19620             "\"\xc2\x8d\";",
19621             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19622   EXPECT_EQ("\"aaaaaaaÄ\"\n"
19623             "\"\xc2\x8d\";",
19624             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19625   EXPECT_EQ("\"Однажды, в \"\n"
19626             "\"студёную \"\n"
19627             "\"зимнюю \"\n"
19628             "\"пору,\"",
19629             format("\"Однажды, в студёную зимнюю пору,\"",
19630                    getLLVMStyleWithColumns(13)));
19631   EXPECT_EQ(
19632       "\"一 二 三 \"\n"
19633       "\"四 五六 \"\n"
19634       "\"七 八 九 \"\n"
19635       "\"十\"",
19636       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
19637   EXPECT_EQ("\"一\t\"\n"
19638             "\"二 \t\"\n"
19639             "\"三 四 \"\n"
19640             "\"五\t\"\n"
19641             "\"六 \t\"\n"
19642             "\"七 \"\n"
19643             "\"八九十\tqq\"",
19644             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
19645                    getLLVMStyleWithColumns(11)));
19646 
19647   // UTF8 character in an escape sequence.
19648   EXPECT_EQ("\"aaaaaa\"\n"
19649             "\"\\\xC2\x8D\"",
19650             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
19651 }
19652 
19653 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
19654   EXPECT_EQ("const char *sssss =\n"
19655             "    \"一二三四五六七八\\\n"
19656             " 九 十\";",
19657             format("const char *sssss = \"一二三四五六七八\\\n"
19658                    " 九 十\";",
19659                    getLLVMStyleWithColumns(30)));
19660 }
19661 
19662 TEST_F(FormatTest, SplitsUTF8LineComments) {
19663   EXPECT_EQ("// aaaaÄ\xc2\x8d",
19664             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
19665   EXPECT_EQ("// Я из лесу\n"
19666             "// вышел; был\n"
19667             "// сильный\n"
19668             "// мороз.",
19669             format("// Я из лесу вышел; был сильный мороз.",
19670                    getLLVMStyleWithColumns(13)));
19671   EXPECT_EQ("// 一二三\n"
19672             "// 四五六七\n"
19673             "// 八  九\n"
19674             "// 十",
19675             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
19676 }
19677 
19678 TEST_F(FormatTest, SplitsUTF8BlockComments) {
19679   EXPECT_EQ("/* Гляжу,\n"
19680             " * поднимается\n"
19681             " * медленно в\n"
19682             " * гору\n"
19683             " * Лошадка,\n"
19684             " * везущая\n"
19685             " * хворосту\n"
19686             " * воз. */",
19687             format("/* Гляжу, поднимается медленно в гору\n"
19688                    " * Лошадка, везущая хворосту воз. */",
19689                    getLLVMStyleWithColumns(13)));
19690   EXPECT_EQ(
19691       "/* 一二三\n"
19692       " * 四五六七\n"
19693       " * 八  九\n"
19694       " * 十  */",
19695       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
19696   EXPECT_EQ("/* �������� ��������\n"
19697             " * ��������\n"
19698             " * ������-�� */",
19699             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
19700 }
19701 
19702 #endif // _MSC_VER
19703 
19704 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
19705   FormatStyle Style = getLLVMStyle();
19706 
19707   Style.ConstructorInitializerIndentWidth = 4;
19708   verifyFormat(
19709       "SomeClass::Constructor()\n"
19710       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19711       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19712       Style);
19713 
19714   Style.ConstructorInitializerIndentWidth = 2;
19715   verifyFormat(
19716       "SomeClass::Constructor()\n"
19717       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19718       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19719       Style);
19720 
19721   Style.ConstructorInitializerIndentWidth = 0;
19722   verifyFormat(
19723       "SomeClass::Constructor()\n"
19724       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19725       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19726       Style);
19727   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19728   verifyFormat(
19729       "SomeLongTemplateVariableName<\n"
19730       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
19731       Style);
19732   verifyFormat("bool smaller = 1 < "
19733                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
19734                "                       "
19735                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
19736                Style);
19737 
19738   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
19739   verifyFormat("SomeClass::Constructor() :\n"
19740                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
19741                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
19742                Style);
19743 }
19744 
19745 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
19746   FormatStyle Style = getLLVMStyle();
19747   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19748   Style.ConstructorInitializerIndentWidth = 4;
19749   verifyFormat("SomeClass::Constructor()\n"
19750                "    : a(a)\n"
19751                "    , b(b)\n"
19752                "    , c(c) {}",
19753                Style);
19754   verifyFormat("SomeClass::Constructor()\n"
19755                "    : a(a) {}",
19756                Style);
19757 
19758   Style.ColumnLimit = 0;
19759   verifyFormat("SomeClass::Constructor()\n"
19760                "    : a(a) {}",
19761                Style);
19762   verifyFormat("SomeClass::Constructor() noexcept\n"
19763                "    : a(a) {}",
19764                Style);
19765   verifyFormat("SomeClass::Constructor()\n"
19766                "    : a(a)\n"
19767                "    , b(b)\n"
19768                "    , c(c) {}",
19769                Style);
19770   verifyFormat("SomeClass::Constructor()\n"
19771                "    : a(a) {\n"
19772                "  foo();\n"
19773                "  bar();\n"
19774                "}",
19775                Style);
19776 
19777   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
19778   verifyFormat("SomeClass::Constructor()\n"
19779                "    : a(a)\n"
19780                "    , b(b)\n"
19781                "    , c(c) {\n}",
19782                Style);
19783   verifyFormat("SomeClass::Constructor()\n"
19784                "    : a(a) {\n}",
19785                Style);
19786 
19787   Style.ColumnLimit = 80;
19788   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
19789   Style.ConstructorInitializerIndentWidth = 2;
19790   verifyFormat("SomeClass::Constructor()\n"
19791                "  : a(a)\n"
19792                "  , b(b)\n"
19793                "  , c(c) {}",
19794                Style);
19795 
19796   Style.ConstructorInitializerIndentWidth = 0;
19797   verifyFormat("SomeClass::Constructor()\n"
19798                ": a(a)\n"
19799                ", b(b)\n"
19800                ", c(c) {}",
19801                Style);
19802 
19803   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19804   Style.ConstructorInitializerIndentWidth = 4;
19805   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
19806   verifyFormat(
19807       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
19808       Style);
19809   verifyFormat(
19810       "SomeClass::Constructor()\n"
19811       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
19812       Style);
19813   Style.ConstructorInitializerIndentWidth = 4;
19814   Style.ColumnLimit = 60;
19815   verifyFormat("SomeClass::Constructor()\n"
19816                "    : aaaaaaaa(aaaaaaaa)\n"
19817                "    , aaaaaaaa(aaaaaaaa)\n"
19818                "    , aaaaaaaa(aaaaaaaa) {}",
19819                Style);
19820 }
19821 
19822 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
19823   FormatStyle Style = getLLVMStyle();
19824   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19825   Style.ConstructorInitializerIndentWidth = 4;
19826   verifyFormat("SomeClass::Constructor()\n"
19827                "    : a{a}\n"
19828                "    , b{b} {}",
19829                Style);
19830   verifyFormat("SomeClass::Constructor()\n"
19831                "    : a{a}\n"
19832                "#if CONDITION\n"
19833                "    , b{b}\n"
19834                "#endif\n"
19835                "{\n}",
19836                Style);
19837   Style.ConstructorInitializerIndentWidth = 2;
19838   verifyFormat("SomeClass::Constructor()\n"
19839                "#if CONDITION\n"
19840                "  : a{a}\n"
19841                "#endif\n"
19842                "  , b{b}\n"
19843                "  , c{c} {\n}",
19844                Style);
19845   Style.ConstructorInitializerIndentWidth = 0;
19846   verifyFormat("SomeClass::Constructor()\n"
19847                ": a{a}\n"
19848                "#ifdef CONDITION\n"
19849                ", b{b}\n"
19850                "#else\n"
19851                ", c{c}\n"
19852                "#endif\n"
19853                ", d{d} {\n}",
19854                Style);
19855   Style.ConstructorInitializerIndentWidth = 4;
19856   verifyFormat("SomeClass::Constructor()\n"
19857                "    : a{a}\n"
19858                "#if WINDOWS\n"
19859                "#if DEBUG\n"
19860                "    , b{0}\n"
19861                "#else\n"
19862                "    , b{1}\n"
19863                "#endif\n"
19864                "#else\n"
19865                "#if DEBUG\n"
19866                "    , b{2}\n"
19867                "#else\n"
19868                "    , b{3}\n"
19869                "#endif\n"
19870                "#endif\n"
19871                "{\n}",
19872                Style);
19873   verifyFormat("SomeClass::Constructor()\n"
19874                "    : a{a}\n"
19875                "#if WINDOWS\n"
19876                "    , b{0}\n"
19877                "#if DEBUG\n"
19878                "    , c{0}\n"
19879                "#else\n"
19880                "    , c{1}\n"
19881                "#endif\n"
19882                "#else\n"
19883                "#if DEBUG\n"
19884                "    , c{2}\n"
19885                "#else\n"
19886                "    , c{3}\n"
19887                "#endif\n"
19888                "    , b{1}\n"
19889                "#endif\n"
19890                "{\n}",
19891                Style);
19892 }
19893 
19894 TEST_F(FormatTest, Destructors) {
19895   verifyFormat("void F(int &i) { i.~int(); }");
19896   verifyFormat("void F(int &i) { i->~int(); }");
19897 }
19898 
19899 TEST_F(FormatTest, FormatsWithWebKitStyle) {
19900   FormatStyle Style = getWebKitStyle();
19901 
19902   // Don't indent in outer namespaces.
19903   verifyFormat("namespace outer {\n"
19904                "int i;\n"
19905                "namespace inner {\n"
19906                "    int i;\n"
19907                "} // namespace inner\n"
19908                "} // namespace outer\n"
19909                "namespace other_outer {\n"
19910                "int i;\n"
19911                "}",
19912                Style);
19913 
19914   // Don't indent case labels.
19915   verifyFormat("switch (variable) {\n"
19916                "case 1:\n"
19917                "case 2:\n"
19918                "    doSomething();\n"
19919                "    break;\n"
19920                "default:\n"
19921                "    ++variable;\n"
19922                "}",
19923                Style);
19924 
19925   // Wrap before binary operators.
19926   EXPECT_EQ("void f()\n"
19927             "{\n"
19928             "    if (aaaaaaaaaaaaaaaa\n"
19929             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
19930             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
19931             "        return;\n"
19932             "}",
19933             format("void f() {\n"
19934                    "if (aaaaaaaaaaaaaaaa\n"
19935                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
19936                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
19937                    "return;\n"
19938                    "}",
19939                    Style));
19940 
19941   // Allow functions on a single line.
19942   verifyFormat("void f() { return; }", Style);
19943 
19944   // Allow empty blocks on a single line and insert a space in empty blocks.
19945   EXPECT_EQ("void f() { }", format("void f() {}", Style));
19946   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
19947   // However, don't merge non-empty short loops.
19948   EXPECT_EQ("while (true) {\n"
19949             "    continue;\n"
19950             "}",
19951             format("while (true) { continue; }", Style));
19952 
19953   // Constructor initializers are formatted one per line with the "," on the
19954   // new line.
19955   verifyFormat("Constructor()\n"
19956                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
19957                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
19958                "          aaaaaaaaaaaaaa)\n"
19959                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
19960                "{\n"
19961                "}",
19962                Style);
19963   verifyFormat("SomeClass::Constructor()\n"
19964                "    : a(a)\n"
19965                "{\n"
19966                "}",
19967                Style);
19968   EXPECT_EQ("SomeClass::Constructor()\n"
19969             "    : a(a)\n"
19970             "{\n"
19971             "}",
19972             format("SomeClass::Constructor():a(a){}", Style));
19973   verifyFormat("SomeClass::Constructor()\n"
19974                "    : a(a)\n"
19975                "    , b(b)\n"
19976                "    , c(c)\n"
19977                "{\n"
19978                "}",
19979                Style);
19980   verifyFormat("SomeClass::Constructor()\n"
19981                "    : a(a)\n"
19982                "{\n"
19983                "    foo();\n"
19984                "    bar();\n"
19985                "}",
19986                Style);
19987 
19988   // Access specifiers should be aligned left.
19989   verifyFormat("class C {\n"
19990                "public:\n"
19991                "    int i;\n"
19992                "};",
19993                Style);
19994 
19995   // Do not align comments.
19996   verifyFormat("int a; // Do not\n"
19997                "double b; // align comments.",
19998                Style);
19999 
20000   // Do not align operands.
20001   EXPECT_EQ("ASSERT(aaaa\n"
20002             "    || bbbb);",
20003             format("ASSERT ( aaaa\n||bbbb);", Style));
20004 
20005   // Accept input's line breaks.
20006   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
20007             "    || bbbbbbbbbbbbbbb) {\n"
20008             "    i++;\n"
20009             "}",
20010             format("if (aaaaaaaaaaaaaaa\n"
20011                    "|| bbbbbbbbbbbbbbb) { i++; }",
20012                    Style));
20013   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
20014             "    i++;\n"
20015             "}",
20016             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
20017 
20018   // Don't automatically break all macro definitions (llvm.org/PR17842).
20019   verifyFormat("#define aNumber 10", Style);
20020   // However, generally keep the line breaks that the user authored.
20021   EXPECT_EQ("#define aNumber \\\n"
20022             "    10",
20023             format("#define aNumber \\\n"
20024                    " 10",
20025                    Style));
20026 
20027   // Keep empty and one-element array literals on a single line.
20028   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
20029             "                                  copyItems:YES];",
20030             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
20031                    "copyItems:YES];",
20032                    Style));
20033   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
20034             "                                  copyItems:YES];",
20035             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
20036                    "             copyItems:YES];",
20037                    Style));
20038   // FIXME: This does not seem right, there should be more indentation before
20039   // the array literal's entries. Nested blocks have the same problem.
20040   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20041             "    @\"a\",\n"
20042             "    @\"a\"\n"
20043             "]\n"
20044             "                                  copyItems:YES];",
20045             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
20046                    "     @\"a\",\n"
20047                    "     @\"a\"\n"
20048                    "     ]\n"
20049                    "       copyItems:YES];",
20050                    Style));
20051   EXPECT_EQ(
20052       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20053       "                                  copyItems:YES];",
20054       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
20055              "   copyItems:YES];",
20056              Style));
20057 
20058   verifyFormat("[self.a b:c c:d];", Style);
20059   EXPECT_EQ("[self.a b:c\n"
20060             "        c:d];",
20061             format("[self.a b:c\n"
20062                    "c:d];",
20063                    Style));
20064 }
20065 
20066 TEST_F(FormatTest, FormatsLambdas) {
20067   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
20068   verifyFormat(
20069       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
20070   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
20071   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
20072   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
20073   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
20074   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
20075   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
20076   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
20077   verifyFormat("int x = f(*+[] {});");
20078   verifyFormat("void f() {\n"
20079                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
20080                "}\n");
20081   verifyFormat("void f() {\n"
20082                "  other(x.begin(), //\n"
20083                "        x.end(),   //\n"
20084                "        [&](int, int) { return 1; });\n"
20085                "}\n");
20086   verifyFormat("void f() {\n"
20087                "  other.other.other.other.other(\n"
20088                "      x.begin(), x.end(),\n"
20089                "      [something, rather](int, int, int, int, int, int, int) { "
20090                "return 1; });\n"
20091                "}\n");
20092   verifyFormat(
20093       "void f() {\n"
20094       "  other.other.other.other.other(\n"
20095       "      x.begin(), x.end(),\n"
20096       "      [something, rather](int, int, int, int, int, int, int) {\n"
20097       "        //\n"
20098       "      });\n"
20099       "}\n");
20100   verifyFormat("SomeFunction([]() { // A cool function...\n"
20101                "  return 43;\n"
20102                "});");
20103   EXPECT_EQ("SomeFunction([]() {\n"
20104             "#define A a\n"
20105             "  return 43;\n"
20106             "});",
20107             format("SomeFunction([](){\n"
20108                    "#define A a\n"
20109                    "return 43;\n"
20110                    "});"));
20111   verifyFormat("void f() {\n"
20112                "  SomeFunction([](decltype(x), A *a) {});\n"
20113                "  SomeFunction([](typeof(x), A *a) {});\n"
20114                "  SomeFunction([](_Atomic(x), A *a) {});\n"
20115                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
20116                "}");
20117   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20118                "    [](const aaaaaaaaaa &a) { return a; });");
20119   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
20120                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
20121                "});");
20122   verifyFormat("Constructor()\n"
20123                "    : Field([] { // comment\n"
20124                "        int i;\n"
20125                "      }) {}");
20126   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
20127                "  return some_parameter.size();\n"
20128                "};");
20129   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
20130                "    [](const string &s) { return s; };");
20131   verifyFormat("int i = aaaaaa ? 1 //\n"
20132                "               : [] {\n"
20133                "                   return 2; //\n"
20134                "                 }();");
20135   verifyFormat("llvm::errs() << \"number of twos is \"\n"
20136                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
20137                "                  return x == 2; // force break\n"
20138                "                });");
20139   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20140                "    [=](int iiiiiiiiiiii) {\n"
20141                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
20142                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
20143                "    });",
20144                getLLVMStyleWithColumns(60));
20145 
20146   verifyFormat("SomeFunction({[&] {\n"
20147                "                // comment\n"
20148                "              },\n"
20149                "              [&] {\n"
20150                "                // comment\n"
20151                "              }});");
20152   verifyFormat("SomeFunction({[&] {\n"
20153                "  // comment\n"
20154                "}});");
20155   verifyFormat(
20156       "virtual aaaaaaaaaaaaaaaa(\n"
20157       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
20158       "    aaaaa aaaaaaaaa);");
20159 
20160   // Lambdas with return types.
20161   verifyFormat("int c = []() -> int { return 2; }();\n");
20162   verifyFormat("int c = []() -> int * { return 2; }();\n");
20163   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
20164   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
20165   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
20166   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
20167   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
20168   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
20169   verifyFormat("[a, a]() -> a<1> {};");
20170   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
20171   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
20172   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
20173   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
20174   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
20175   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
20176   verifyFormat("[]() -> foo<!5> { return {}; };");
20177   verifyFormat("[]() -> foo<~5> { return {}; };");
20178   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
20179   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
20180   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
20181   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
20182   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
20183   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
20184   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
20185   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
20186   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
20187   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
20188   verifyFormat("namespace bar {\n"
20189                "// broken:\n"
20190                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
20191                "} // namespace bar");
20192   verifyFormat("namespace bar {\n"
20193                "// broken:\n"
20194                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
20195                "} // namespace bar");
20196   verifyFormat("namespace bar {\n"
20197                "// broken:\n"
20198                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
20199                "} // namespace bar");
20200   verifyFormat("namespace bar {\n"
20201                "// broken:\n"
20202                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
20203                "} // namespace bar");
20204   verifyFormat("namespace bar {\n"
20205                "// broken:\n"
20206                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
20207                "} // namespace bar");
20208   verifyFormat("namespace bar {\n"
20209                "// broken:\n"
20210                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
20211                "} // namespace bar");
20212   verifyFormat("namespace bar {\n"
20213                "// broken:\n"
20214                "auto foo{[]() -> foo<!5> { return {}; }};\n"
20215                "} // namespace bar");
20216   verifyFormat("namespace bar {\n"
20217                "// broken:\n"
20218                "auto foo{[]() -> foo<~5> { return {}; }};\n"
20219                "} // namespace bar");
20220   verifyFormat("namespace bar {\n"
20221                "// broken:\n"
20222                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
20223                "} // namespace bar");
20224   verifyFormat("namespace bar {\n"
20225                "// broken:\n"
20226                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
20227                "} // namespace bar");
20228   verifyFormat("namespace bar {\n"
20229                "// broken:\n"
20230                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
20231                "} // namespace bar");
20232   verifyFormat("namespace bar {\n"
20233                "// broken:\n"
20234                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
20235                "} // namespace bar");
20236   verifyFormat("namespace bar {\n"
20237                "// broken:\n"
20238                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
20239                "} // namespace bar");
20240   verifyFormat("namespace bar {\n"
20241                "// broken:\n"
20242                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
20243                "} // namespace bar");
20244   verifyFormat("namespace bar {\n"
20245                "// broken:\n"
20246                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
20247                "} // namespace bar");
20248   verifyFormat("namespace bar {\n"
20249                "// broken:\n"
20250                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
20251                "} // namespace bar");
20252   verifyFormat("namespace bar {\n"
20253                "// broken:\n"
20254                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
20255                "} // namespace bar");
20256   verifyFormat("namespace bar {\n"
20257                "// broken:\n"
20258                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
20259                "} // namespace bar");
20260   verifyFormat("[]() -> a<1> {};");
20261   verifyFormat("[]() -> a<1> { ; };");
20262   verifyFormat("[]() -> a<1> { ; }();");
20263   verifyFormat("[a, a]() -> a<true> {};");
20264   verifyFormat("[]() -> a<true> {};");
20265   verifyFormat("[]() -> a<true> { ; };");
20266   verifyFormat("[]() -> a<true> { ; }();");
20267   verifyFormat("[a, a]() -> a<false> {};");
20268   verifyFormat("[]() -> a<false> {};");
20269   verifyFormat("[]() -> a<false> { ; };");
20270   verifyFormat("[]() -> a<false> { ; }();");
20271   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
20272   verifyFormat("namespace bar {\n"
20273                "auto foo{[]() -> foo<false> { ; }};\n"
20274                "} // namespace bar");
20275   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
20276                "                   int j) -> int {\n"
20277                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
20278                "};");
20279   verifyFormat(
20280       "aaaaaaaaaaaaaaaaaaaaaa(\n"
20281       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
20282       "      return aaaaaaaaaaaaaaaaa;\n"
20283       "    });",
20284       getLLVMStyleWithColumns(70));
20285   verifyFormat("[]() //\n"
20286                "    -> int {\n"
20287                "  return 1; //\n"
20288                "};");
20289   verifyFormat("[]() -> Void<T...> {};");
20290   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
20291   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
20292   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
20293   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
20294   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
20295   verifyFormat("return int{[x = x]() { return x; }()};");
20296 
20297   // Lambdas with explicit template argument lists.
20298   verifyFormat(
20299       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
20300 
20301   // Multiple lambdas in the same parentheses change indentation rules. These
20302   // lambdas are forced to start on new lines.
20303   verifyFormat("SomeFunction(\n"
20304                "    []() {\n"
20305                "      //\n"
20306                "    },\n"
20307                "    []() {\n"
20308                "      //\n"
20309                "    });");
20310 
20311   // A lambda passed as arg0 is always pushed to the next line.
20312   verifyFormat("SomeFunction(\n"
20313                "    [this] {\n"
20314                "      //\n"
20315                "    },\n"
20316                "    1);\n");
20317 
20318   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
20319   // the arg0 case above.
20320   auto Style = getGoogleStyle();
20321   Style.BinPackArguments = false;
20322   verifyFormat("SomeFunction(\n"
20323                "    a,\n"
20324                "    [this] {\n"
20325                "      //\n"
20326                "    },\n"
20327                "    b);\n",
20328                Style);
20329   verifyFormat("SomeFunction(\n"
20330                "    a,\n"
20331                "    [this] {\n"
20332                "      //\n"
20333                "    },\n"
20334                "    b);\n");
20335 
20336   // A lambda with a very long line forces arg0 to be pushed out irrespective of
20337   // the BinPackArguments value (as long as the code is wide enough).
20338   verifyFormat(
20339       "something->SomeFunction(\n"
20340       "    a,\n"
20341       "    [this] {\n"
20342       "      "
20343       "D0000000000000000000000000000000000000000000000000000000000001();\n"
20344       "    },\n"
20345       "    b);\n");
20346 
20347   // A multi-line lambda is pulled up as long as the introducer fits on the
20348   // previous line and there are no further args.
20349   verifyFormat("function(1, [this, that] {\n"
20350                "  //\n"
20351                "});\n");
20352   verifyFormat("function([this, that] {\n"
20353                "  //\n"
20354                "});\n");
20355   // FIXME: this format is not ideal and we should consider forcing the first
20356   // arg onto its own line.
20357   verifyFormat("function(a, b, c, //\n"
20358                "         d, [this, that] {\n"
20359                "           //\n"
20360                "         });\n");
20361 
20362   // Multiple lambdas are treated correctly even when there is a short arg0.
20363   verifyFormat("SomeFunction(\n"
20364                "    1,\n"
20365                "    [this] {\n"
20366                "      //\n"
20367                "    },\n"
20368                "    [this] {\n"
20369                "      //\n"
20370                "    },\n"
20371                "    1);\n");
20372 
20373   // More complex introducers.
20374   verifyFormat("return [i, args...] {};");
20375 
20376   // Not lambdas.
20377   verifyFormat("constexpr char hello[]{\"hello\"};");
20378   verifyFormat("double &operator[](int i) { return 0; }\n"
20379                "int i;");
20380   verifyFormat("std::unique_ptr<int[]> foo() {}");
20381   verifyFormat("int i = a[a][a]->f();");
20382   verifyFormat("int i = (*b)[a]->f();");
20383 
20384   // Other corner cases.
20385   verifyFormat("void f() {\n"
20386                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
20387                "  );\n"
20388                "}");
20389 
20390   // Lambdas created through weird macros.
20391   verifyFormat("void f() {\n"
20392                "  MACRO((const AA &a) { return 1; });\n"
20393                "  MACRO((AA &a) { return 1; });\n"
20394                "}");
20395 
20396   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
20397                "      doo_dah();\n"
20398                "      doo_dah();\n"
20399                "    })) {\n"
20400                "}");
20401   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
20402                "                doo_dah();\n"
20403                "                doo_dah();\n"
20404                "              })) {\n"
20405                "}");
20406   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
20407                "                doo_dah();\n"
20408                "                doo_dah();\n"
20409                "              })) {\n"
20410                "}");
20411   verifyFormat("auto lambda = []() {\n"
20412                "  int a = 2\n"
20413                "#if A\n"
20414                "          + 2\n"
20415                "#endif\n"
20416                "      ;\n"
20417                "};");
20418 
20419   // Lambdas with complex multiline introducers.
20420   verifyFormat(
20421       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20422       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
20423       "        -> ::std::unordered_set<\n"
20424       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
20425       "      //\n"
20426       "    });");
20427 
20428   FormatStyle DoNotMerge = getLLVMStyle();
20429   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
20430   verifyFormat("auto c = []() {\n"
20431                "  return b;\n"
20432                "};",
20433                "auto c = []() { return b; };", DoNotMerge);
20434   verifyFormat("auto c = []() {\n"
20435                "};",
20436                " auto c = []() {};", DoNotMerge);
20437 
20438   FormatStyle MergeEmptyOnly = getLLVMStyle();
20439   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
20440   verifyFormat("auto c = []() {\n"
20441                "  return b;\n"
20442                "};",
20443                "auto c = []() {\n"
20444                "  return b;\n"
20445                " };",
20446                MergeEmptyOnly);
20447   verifyFormat("auto c = []() {};",
20448                "auto c = []() {\n"
20449                "};",
20450                MergeEmptyOnly);
20451 
20452   FormatStyle MergeInline = getLLVMStyle();
20453   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
20454   verifyFormat("auto c = []() {\n"
20455                "  return b;\n"
20456                "};",
20457                "auto c = []() { return b; };", MergeInline);
20458   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
20459                MergeInline);
20460   verifyFormat("function([]() { return b; }, a)",
20461                "function([]() { return b; }, a)", MergeInline);
20462   verifyFormat("function(a, []() { return b; })",
20463                "function(a, []() { return b; })", MergeInline);
20464 
20465   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
20466   // AllowShortLambdasOnASingleLine
20467   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20468   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20469   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20470   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20471       FormatStyle::ShortLambdaStyle::SLS_None;
20472   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
20473                "    []()\n"
20474                "    {\n"
20475                "      return 17;\n"
20476                "    });",
20477                LLVMWithBeforeLambdaBody);
20478   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
20479                "    []()\n"
20480                "    {\n"
20481                "    });",
20482                LLVMWithBeforeLambdaBody);
20483   verifyFormat("auto fct_SLS_None = []()\n"
20484                "{\n"
20485                "  return 17;\n"
20486                "};",
20487                LLVMWithBeforeLambdaBody);
20488   verifyFormat("TwoNestedLambdas_SLS_None(\n"
20489                "    []()\n"
20490                "    {\n"
20491                "      return Call(\n"
20492                "          []()\n"
20493                "          {\n"
20494                "            return 17;\n"
20495                "          });\n"
20496                "    });",
20497                LLVMWithBeforeLambdaBody);
20498   verifyFormat("void Fct() {\n"
20499                "  return {[]()\n"
20500                "          {\n"
20501                "            return 17;\n"
20502                "          }};\n"
20503                "}",
20504                LLVMWithBeforeLambdaBody);
20505 
20506   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20507       FormatStyle::ShortLambdaStyle::SLS_Empty;
20508   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
20509                "    []()\n"
20510                "    {\n"
20511                "      return 17;\n"
20512                "    });",
20513                LLVMWithBeforeLambdaBody);
20514   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
20515                LLVMWithBeforeLambdaBody);
20516   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
20517                "ongFunctionName_SLS_Empty(\n"
20518                "    []() {});",
20519                LLVMWithBeforeLambdaBody);
20520   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
20521                "                                []()\n"
20522                "                                {\n"
20523                "                                  return 17;\n"
20524                "                                });",
20525                LLVMWithBeforeLambdaBody);
20526   verifyFormat("auto fct_SLS_Empty = []()\n"
20527                "{\n"
20528                "  return 17;\n"
20529                "};",
20530                LLVMWithBeforeLambdaBody);
20531   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
20532                "    []()\n"
20533                "    {\n"
20534                "      return Call([]() {});\n"
20535                "    });",
20536                LLVMWithBeforeLambdaBody);
20537   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
20538                "                           []()\n"
20539                "                           {\n"
20540                "                             return Call([]() {});\n"
20541                "                           });",
20542                LLVMWithBeforeLambdaBody);
20543   verifyFormat(
20544       "FctWithLongLineInLambda_SLS_Empty(\n"
20545       "    []()\n"
20546       "    {\n"
20547       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20548       "                               AndShouldNotBeConsiderAsInline,\n"
20549       "                               LambdaBodyMustBeBreak);\n"
20550       "    });",
20551       LLVMWithBeforeLambdaBody);
20552 
20553   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20554       FormatStyle::ShortLambdaStyle::SLS_Inline;
20555   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
20556                LLVMWithBeforeLambdaBody);
20557   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
20558                LLVMWithBeforeLambdaBody);
20559   verifyFormat("auto fct_SLS_Inline = []()\n"
20560                "{\n"
20561                "  return 17;\n"
20562                "};",
20563                LLVMWithBeforeLambdaBody);
20564   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
20565                "17; }); });",
20566                LLVMWithBeforeLambdaBody);
20567   verifyFormat(
20568       "FctWithLongLineInLambda_SLS_Inline(\n"
20569       "    []()\n"
20570       "    {\n"
20571       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20572       "                               AndShouldNotBeConsiderAsInline,\n"
20573       "                               LambdaBodyMustBeBreak);\n"
20574       "    });",
20575       LLVMWithBeforeLambdaBody);
20576   verifyFormat("FctWithMultipleParams_SLS_Inline("
20577                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20578                "                                 []() { return 17; });",
20579                LLVMWithBeforeLambdaBody);
20580   verifyFormat(
20581       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
20582       LLVMWithBeforeLambdaBody);
20583 
20584   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20585       FormatStyle::ShortLambdaStyle::SLS_All;
20586   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
20587                LLVMWithBeforeLambdaBody);
20588   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
20589                LLVMWithBeforeLambdaBody);
20590   verifyFormat("auto fct_SLS_All = []() { return 17; };",
20591                LLVMWithBeforeLambdaBody);
20592   verifyFormat("FctWithOneParam_SLS_All(\n"
20593                "    []()\n"
20594                "    {\n"
20595                "      // A cool function...\n"
20596                "      return 43;\n"
20597                "    });",
20598                LLVMWithBeforeLambdaBody);
20599   verifyFormat("FctWithMultipleParams_SLS_All("
20600                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20601                "                              []() { return 17; });",
20602                LLVMWithBeforeLambdaBody);
20603   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
20604                LLVMWithBeforeLambdaBody);
20605   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
20606                LLVMWithBeforeLambdaBody);
20607   verifyFormat(
20608       "FctWithLongLineInLambda_SLS_All(\n"
20609       "    []()\n"
20610       "    {\n"
20611       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20612       "                               AndShouldNotBeConsiderAsInline,\n"
20613       "                               LambdaBodyMustBeBreak);\n"
20614       "    });",
20615       LLVMWithBeforeLambdaBody);
20616   verifyFormat(
20617       "auto fct_SLS_All = []()\n"
20618       "{\n"
20619       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20620       "                           AndShouldNotBeConsiderAsInline,\n"
20621       "                           LambdaBodyMustBeBreak);\n"
20622       "};",
20623       LLVMWithBeforeLambdaBody);
20624   LLVMWithBeforeLambdaBody.BinPackParameters = false;
20625   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
20626                LLVMWithBeforeLambdaBody);
20627   verifyFormat(
20628       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
20629       "                                FirstParam,\n"
20630       "                                SecondParam,\n"
20631       "                                ThirdParam,\n"
20632       "                                FourthParam);",
20633       LLVMWithBeforeLambdaBody);
20634   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20635                "    []() { return "
20636                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
20637                "    FirstParam,\n"
20638                "    SecondParam,\n"
20639                "    ThirdParam,\n"
20640                "    FourthParam);",
20641                LLVMWithBeforeLambdaBody);
20642   verifyFormat(
20643       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
20644       "                                SecondParam,\n"
20645       "                                ThirdParam,\n"
20646       "                                FourthParam,\n"
20647       "                                []() { return SomeValueNotSoLong; });",
20648       LLVMWithBeforeLambdaBody);
20649   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20650                "    []()\n"
20651                "    {\n"
20652                "      return "
20653                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
20654                "eConsiderAsInline;\n"
20655                "    });",
20656                LLVMWithBeforeLambdaBody);
20657   verifyFormat(
20658       "FctWithLongLineInLambda_SLS_All(\n"
20659       "    []()\n"
20660       "    {\n"
20661       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20662       "                               AndShouldNotBeConsiderAsInline,\n"
20663       "                               LambdaBodyMustBeBreak);\n"
20664       "    });",
20665       LLVMWithBeforeLambdaBody);
20666   verifyFormat("FctWithTwoParams_SLS_All(\n"
20667                "    []()\n"
20668                "    {\n"
20669                "      // A cool function...\n"
20670                "      return 43;\n"
20671                "    },\n"
20672                "    87);",
20673                LLVMWithBeforeLambdaBody);
20674   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
20675                LLVMWithBeforeLambdaBody);
20676   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
20677                LLVMWithBeforeLambdaBody);
20678   verifyFormat(
20679       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
20680       LLVMWithBeforeLambdaBody);
20681   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
20682                "}); }, x);",
20683                LLVMWithBeforeLambdaBody);
20684   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20685                "    []()\n"
20686                "    {\n"
20687                "      // A cool function...\n"
20688                "      return Call([]() { return 17; });\n"
20689                "    });",
20690                LLVMWithBeforeLambdaBody);
20691   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20692                "    []()\n"
20693                "    {\n"
20694                "      return Call(\n"
20695                "          []()\n"
20696                "          {\n"
20697                "            // A cool function...\n"
20698                "            return 17;\n"
20699                "          });\n"
20700                "    });",
20701                LLVMWithBeforeLambdaBody);
20702 
20703   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20704       FormatStyle::ShortLambdaStyle::SLS_None;
20705 
20706   verifyFormat("auto select = [this]() -> const Library::Object *\n"
20707                "{\n"
20708                "  return MyAssignment::SelectFromList(this);\n"
20709                "};\n",
20710                LLVMWithBeforeLambdaBody);
20711 
20712   verifyFormat("auto select = [this]() -> const Library::Object &\n"
20713                "{\n"
20714                "  return MyAssignment::SelectFromList(this);\n"
20715                "};\n",
20716                LLVMWithBeforeLambdaBody);
20717 
20718   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
20719                "{\n"
20720                "  return MyAssignment::SelectFromList(this);\n"
20721                "};\n",
20722                LLVMWithBeforeLambdaBody);
20723 
20724   verifyFormat("namespace test {\n"
20725                "class Test {\n"
20726                "public:\n"
20727                "  Test() = default;\n"
20728                "};\n"
20729                "} // namespace test",
20730                LLVMWithBeforeLambdaBody);
20731 
20732   // Lambdas with different indentation styles.
20733   Style = getLLVMStyleWithColumns(100);
20734   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20735             "  return promise.then(\n"
20736             "      [this, &someVariable, someObject = "
20737             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20738             "        return someObject.startAsyncAction().then(\n"
20739             "            [this, &someVariable](AsyncActionResult result) "
20740             "mutable { result.processMore(); });\n"
20741             "      });\n"
20742             "}\n",
20743             format("SomeResult doSomething(SomeObject promise) {\n"
20744                    "  return promise.then([this, &someVariable, someObject = "
20745                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20746                    "    return someObject.startAsyncAction().then([this, "
20747                    "&someVariable](AsyncActionResult result) mutable {\n"
20748                    "      result.processMore();\n"
20749                    "    });\n"
20750                    "  });\n"
20751                    "}\n",
20752                    Style));
20753   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20754   verifyFormat("test() {\n"
20755                "  ([]() -> {\n"
20756                "    int b = 32;\n"
20757                "    return 3;\n"
20758                "  }).foo();\n"
20759                "}",
20760                Style);
20761   verifyFormat("test() {\n"
20762                "  []() -> {\n"
20763                "    int b = 32;\n"
20764                "    return 3;\n"
20765                "  }\n"
20766                "}",
20767                Style);
20768   verifyFormat("std::sort(v.begin(), v.end(),\n"
20769                "          [](const auto &someLongArgumentName, const auto "
20770                "&someOtherLongArgumentName) {\n"
20771                "  return someLongArgumentName.someMemberVariable < "
20772                "someOtherLongArgumentName.someMemberVariable;\n"
20773                "});",
20774                Style);
20775   verifyFormat("test() {\n"
20776                "  (\n"
20777                "      []() -> {\n"
20778                "        int b = 32;\n"
20779                "        return 3;\n"
20780                "      },\n"
20781                "      foo, bar)\n"
20782                "      .foo();\n"
20783                "}",
20784                Style);
20785   verifyFormat("test() {\n"
20786                "  ([]() -> {\n"
20787                "    int b = 32;\n"
20788                "    return 3;\n"
20789                "  })\n"
20790                "      .foo()\n"
20791                "      .bar();\n"
20792                "}",
20793                Style);
20794   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20795             "  return promise.then(\n"
20796             "      [this, &someVariable, someObject = "
20797             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20798             "    return someObject.startAsyncAction().then(\n"
20799             "        [this, &someVariable](AsyncActionResult result) mutable { "
20800             "result.processMore(); });\n"
20801             "  });\n"
20802             "}\n",
20803             format("SomeResult doSomething(SomeObject promise) {\n"
20804                    "  return promise.then([this, &someVariable, someObject = "
20805                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20806                    "    return someObject.startAsyncAction().then([this, "
20807                    "&someVariable](AsyncActionResult result) mutable {\n"
20808                    "      result.processMore();\n"
20809                    "    });\n"
20810                    "  });\n"
20811                    "}\n",
20812                    Style));
20813   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20814             "  return promise.then([this, &someVariable] {\n"
20815             "    return someObject.startAsyncAction().then(\n"
20816             "        [this, &someVariable](AsyncActionResult result) mutable { "
20817             "result.processMore(); });\n"
20818             "  });\n"
20819             "}\n",
20820             format("SomeResult doSomething(SomeObject promise) {\n"
20821                    "  return promise.then([this, &someVariable] {\n"
20822                    "    return someObject.startAsyncAction().then([this, "
20823                    "&someVariable](AsyncActionResult result) mutable {\n"
20824                    "      result.processMore();\n"
20825                    "    });\n"
20826                    "  });\n"
20827                    "}\n",
20828                    Style));
20829   Style = getGoogleStyle();
20830   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20831   EXPECT_EQ("#define A                                       \\\n"
20832             "  [] {                                          \\\n"
20833             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
20834             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
20835             "      }",
20836             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
20837                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
20838                    Style));
20839   // TODO: The current formatting has a minor issue that's not worth fixing
20840   // right now whereby the closing brace is indented relative to the signature
20841   // instead of being aligned. This only happens with macros.
20842 }
20843 
20844 TEST_F(FormatTest, LambdaWithLineComments) {
20845   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20846   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20847   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20848   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20849       FormatStyle::ShortLambdaStyle::SLS_All;
20850 
20851   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
20852   verifyFormat("auto k = []() // comment\n"
20853                "{ return; }",
20854                LLVMWithBeforeLambdaBody);
20855   verifyFormat("auto k = []() /* comment */ { return; }",
20856                LLVMWithBeforeLambdaBody);
20857   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
20858                LLVMWithBeforeLambdaBody);
20859   verifyFormat("auto k = []() // X\n"
20860                "{ return; }",
20861                LLVMWithBeforeLambdaBody);
20862   verifyFormat(
20863       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
20864       "{ return; }",
20865       LLVMWithBeforeLambdaBody);
20866 }
20867 
20868 TEST_F(FormatTest, EmptyLinesInLambdas) {
20869   verifyFormat("auto lambda = []() {\n"
20870                "  x(); //\n"
20871                "};",
20872                "auto lambda = []() {\n"
20873                "\n"
20874                "  x(); //\n"
20875                "\n"
20876                "};");
20877 }
20878 
20879 TEST_F(FormatTest, FormatsBlocks) {
20880   FormatStyle ShortBlocks = getLLVMStyle();
20881   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
20882   verifyFormat("int (^Block)(int, int);", ShortBlocks);
20883   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
20884   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
20885   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
20886   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
20887   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
20888 
20889   verifyFormat("foo(^{ bar(); });", ShortBlocks);
20890   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
20891   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
20892 
20893   verifyFormat("[operation setCompletionBlock:^{\n"
20894                "  [self onOperationDone];\n"
20895                "}];");
20896   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
20897                "  [self onOperationDone];\n"
20898                "}]};");
20899   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
20900                "  f();\n"
20901                "}];");
20902   verifyFormat("int a = [operation block:^int(int *i) {\n"
20903                "  return 1;\n"
20904                "}];");
20905   verifyFormat("[myObject doSomethingWith:arg1\n"
20906                "                      aaa:^int(int *a) {\n"
20907                "                        return 1;\n"
20908                "                      }\n"
20909                "                      bbb:f(a * bbbbbbbb)];");
20910 
20911   verifyFormat("[operation setCompletionBlock:^{\n"
20912                "  [self.delegate newDataAvailable];\n"
20913                "}];",
20914                getLLVMStyleWithColumns(60));
20915   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
20916                "  NSString *path = [self sessionFilePath];\n"
20917                "  if (path) {\n"
20918                "    // ...\n"
20919                "  }\n"
20920                "});");
20921   verifyFormat("[[SessionService sharedService]\n"
20922                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20923                "      if (window) {\n"
20924                "        [self windowDidLoad:window];\n"
20925                "      } else {\n"
20926                "        [self errorLoadingWindow];\n"
20927                "      }\n"
20928                "    }];");
20929   verifyFormat("void (^largeBlock)(void) = ^{\n"
20930                "  // ...\n"
20931                "};\n",
20932                getLLVMStyleWithColumns(40));
20933   verifyFormat("[[SessionService sharedService]\n"
20934                "    loadWindowWithCompletionBlock: //\n"
20935                "        ^(SessionWindow *window) {\n"
20936                "          if (window) {\n"
20937                "            [self windowDidLoad:window];\n"
20938                "          } else {\n"
20939                "            [self errorLoadingWindow];\n"
20940                "          }\n"
20941                "        }];",
20942                getLLVMStyleWithColumns(60));
20943   verifyFormat("[myObject doSomethingWith:arg1\n"
20944                "    firstBlock:^(Foo *a) {\n"
20945                "      // ...\n"
20946                "      int i;\n"
20947                "    }\n"
20948                "    secondBlock:^(Bar *b) {\n"
20949                "      // ...\n"
20950                "      int i;\n"
20951                "    }\n"
20952                "    thirdBlock:^Foo(Bar *b) {\n"
20953                "      // ...\n"
20954                "      int i;\n"
20955                "    }];");
20956   verifyFormat("[myObject doSomethingWith:arg1\n"
20957                "               firstBlock:-1\n"
20958                "              secondBlock:^(Bar *b) {\n"
20959                "                // ...\n"
20960                "                int i;\n"
20961                "              }];");
20962 
20963   verifyFormat("f(^{\n"
20964                "  @autoreleasepool {\n"
20965                "    if (a) {\n"
20966                "      g();\n"
20967                "    }\n"
20968                "  }\n"
20969                "});");
20970   verifyFormat("Block b = ^int *(A *a, B *b) {}");
20971   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
20972                "};");
20973 
20974   FormatStyle FourIndent = getLLVMStyle();
20975   FourIndent.ObjCBlockIndentWidth = 4;
20976   verifyFormat("[operation setCompletionBlock:^{\n"
20977                "    [self onOperationDone];\n"
20978                "}];",
20979                FourIndent);
20980 }
20981 
20982 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
20983   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
20984 
20985   verifyFormat("[[SessionService sharedService] "
20986                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20987                "  if (window) {\n"
20988                "    [self windowDidLoad:window];\n"
20989                "  } else {\n"
20990                "    [self errorLoadingWindow];\n"
20991                "  }\n"
20992                "}];",
20993                ZeroColumn);
20994   EXPECT_EQ("[[SessionService sharedService]\n"
20995             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20996             "      if (window) {\n"
20997             "        [self windowDidLoad:window];\n"
20998             "      } else {\n"
20999             "        [self errorLoadingWindow];\n"
21000             "      }\n"
21001             "    }];",
21002             format("[[SessionService sharedService]\n"
21003                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
21004                    "                if (window) {\n"
21005                    "    [self windowDidLoad:window];\n"
21006                    "  } else {\n"
21007                    "    [self errorLoadingWindow];\n"
21008                    "  }\n"
21009                    "}];",
21010                    ZeroColumn));
21011   verifyFormat("[myObject doSomethingWith:arg1\n"
21012                "    firstBlock:^(Foo *a) {\n"
21013                "      // ...\n"
21014                "      int i;\n"
21015                "    }\n"
21016                "    secondBlock:^(Bar *b) {\n"
21017                "      // ...\n"
21018                "      int i;\n"
21019                "    }\n"
21020                "    thirdBlock:^Foo(Bar *b) {\n"
21021                "      // ...\n"
21022                "      int i;\n"
21023                "    }];",
21024                ZeroColumn);
21025   verifyFormat("f(^{\n"
21026                "  @autoreleasepool {\n"
21027                "    if (a) {\n"
21028                "      g();\n"
21029                "    }\n"
21030                "  }\n"
21031                "});",
21032                ZeroColumn);
21033   verifyFormat("void (^largeBlock)(void) = ^{\n"
21034                "  // ...\n"
21035                "};",
21036                ZeroColumn);
21037 
21038   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
21039   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
21040             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21041   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
21042   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
21043             "  int i;\n"
21044             "};",
21045             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
21046 }
21047 
21048 TEST_F(FormatTest, SupportsCRLF) {
21049   EXPECT_EQ("int a;\r\n"
21050             "int b;\r\n"
21051             "int c;\r\n",
21052             format("int a;\r\n"
21053                    "  int b;\r\n"
21054                    "    int c;\r\n",
21055                    getLLVMStyle()));
21056   EXPECT_EQ("int a;\r\n"
21057             "int b;\r\n"
21058             "int c;\r\n",
21059             format("int a;\r\n"
21060                    "  int b;\n"
21061                    "    int c;\r\n",
21062                    getLLVMStyle()));
21063   EXPECT_EQ("int a;\n"
21064             "int b;\n"
21065             "int c;\n",
21066             format("int a;\r\n"
21067                    "  int b;\n"
21068                    "    int c;\n",
21069                    getLLVMStyle()));
21070   EXPECT_EQ("\"aaaaaaa \"\r\n"
21071             "\"bbbbbbb\";\r\n",
21072             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
21073   EXPECT_EQ("#define A \\\r\n"
21074             "  b;      \\\r\n"
21075             "  c;      \\\r\n"
21076             "  d;\r\n",
21077             format("#define A \\\r\n"
21078                    "  b; \\\r\n"
21079                    "  c; d; \r\n",
21080                    getGoogleStyle()));
21081 
21082   EXPECT_EQ("/*\r\n"
21083             "multi line block comments\r\n"
21084             "should not introduce\r\n"
21085             "an extra carriage return\r\n"
21086             "*/\r\n",
21087             format("/*\r\n"
21088                    "multi line block comments\r\n"
21089                    "should not introduce\r\n"
21090                    "an extra carriage return\r\n"
21091                    "*/\r\n"));
21092   EXPECT_EQ("/*\r\n"
21093             "\r\n"
21094             "*/",
21095             format("/*\r\n"
21096                    "    \r\r\r\n"
21097                    "*/"));
21098 
21099   FormatStyle style = getLLVMStyle();
21100 
21101   style.DeriveLineEnding = true;
21102   style.UseCRLF = false;
21103   EXPECT_EQ("union FooBarBazQux {\n"
21104             "  int foo;\n"
21105             "  int bar;\n"
21106             "  int baz;\n"
21107             "};",
21108             format("union FooBarBazQux {\r\n"
21109                    "  int foo;\n"
21110                    "  int bar;\r\n"
21111                    "  int baz;\n"
21112                    "};",
21113                    style));
21114   style.UseCRLF = true;
21115   EXPECT_EQ("union FooBarBazQux {\r\n"
21116             "  int foo;\r\n"
21117             "  int bar;\r\n"
21118             "  int baz;\r\n"
21119             "};",
21120             format("union FooBarBazQux {\r\n"
21121                    "  int foo;\n"
21122                    "  int bar;\r\n"
21123                    "  int baz;\n"
21124                    "};",
21125                    style));
21126 
21127   style.DeriveLineEnding = false;
21128   style.UseCRLF = false;
21129   EXPECT_EQ("union FooBarBazQux {\n"
21130             "  int foo;\n"
21131             "  int bar;\n"
21132             "  int baz;\n"
21133             "  int qux;\n"
21134             "};",
21135             format("union FooBarBazQux {\r\n"
21136                    "  int foo;\n"
21137                    "  int bar;\r\n"
21138                    "  int baz;\n"
21139                    "  int qux;\r\n"
21140                    "};",
21141                    style));
21142   style.UseCRLF = true;
21143   EXPECT_EQ("union FooBarBazQux {\r\n"
21144             "  int foo;\r\n"
21145             "  int bar;\r\n"
21146             "  int baz;\r\n"
21147             "  int qux;\r\n"
21148             "};",
21149             format("union FooBarBazQux {\r\n"
21150                    "  int foo;\n"
21151                    "  int bar;\r\n"
21152                    "  int baz;\n"
21153                    "  int qux;\n"
21154                    "};",
21155                    style));
21156 
21157   style.DeriveLineEnding = true;
21158   style.UseCRLF = false;
21159   EXPECT_EQ("union FooBarBazQux {\r\n"
21160             "  int foo;\r\n"
21161             "  int bar;\r\n"
21162             "  int baz;\r\n"
21163             "  int qux;\r\n"
21164             "};",
21165             format("union FooBarBazQux {\r\n"
21166                    "  int foo;\n"
21167                    "  int bar;\r\n"
21168                    "  int baz;\n"
21169                    "  int qux;\r\n"
21170                    "};",
21171                    style));
21172   style.UseCRLF = true;
21173   EXPECT_EQ("union FooBarBazQux {\n"
21174             "  int foo;\n"
21175             "  int bar;\n"
21176             "  int baz;\n"
21177             "  int qux;\n"
21178             "};",
21179             format("union FooBarBazQux {\r\n"
21180                    "  int foo;\n"
21181                    "  int bar;\r\n"
21182                    "  int baz;\n"
21183                    "  int qux;\n"
21184                    "};",
21185                    style));
21186 }
21187 
21188 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
21189   verifyFormat("MY_CLASS(C) {\n"
21190                "  int i;\n"
21191                "  int j;\n"
21192                "};");
21193 }
21194 
21195 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
21196   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
21197   TwoIndent.ContinuationIndentWidth = 2;
21198 
21199   EXPECT_EQ("int i =\n"
21200             "  longFunction(\n"
21201             "    arg);",
21202             format("int i = longFunction(arg);", TwoIndent));
21203 
21204   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
21205   SixIndent.ContinuationIndentWidth = 6;
21206 
21207   EXPECT_EQ("int i =\n"
21208             "      longFunction(\n"
21209             "            arg);",
21210             format("int i = longFunction(arg);", SixIndent));
21211 }
21212 
21213 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
21214   FormatStyle Style = getLLVMStyle();
21215   verifyFormat("int Foo::getter(\n"
21216                "    //\n"
21217                ") const {\n"
21218                "  return foo;\n"
21219                "}",
21220                Style);
21221   verifyFormat("void Foo::setter(\n"
21222                "    //\n"
21223                ") {\n"
21224                "  foo = 1;\n"
21225                "}",
21226                Style);
21227 }
21228 
21229 TEST_F(FormatTest, SpacesInAngles) {
21230   FormatStyle Spaces = getLLVMStyle();
21231   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21232 
21233   verifyFormat("vector< ::std::string > x1;", Spaces);
21234   verifyFormat("Foo< int, Bar > x2;", Spaces);
21235   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
21236 
21237   verifyFormat("static_cast< int >(arg);", Spaces);
21238   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
21239   verifyFormat("f< int, float >();", Spaces);
21240   verifyFormat("template <> g() {}", Spaces);
21241   verifyFormat("template < std::vector< int > > f() {}", Spaces);
21242   verifyFormat("std::function< void(int, int) > fct;", Spaces);
21243   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
21244                Spaces);
21245 
21246   Spaces.Standard = FormatStyle::LS_Cpp03;
21247   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21248   verifyFormat("A< A< int > >();", Spaces);
21249 
21250   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
21251   verifyFormat("A<A<int> >();", Spaces);
21252 
21253   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
21254   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
21255                Spaces);
21256   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
21257                Spaces);
21258 
21259   verifyFormat("A<A<int> >();", Spaces);
21260   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
21261   verifyFormat("A< A< int > >();", Spaces);
21262 
21263   Spaces.Standard = FormatStyle::LS_Cpp11;
21264   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21265   verifyFormat("A< A< int > >();", Spaces);
21266 
21267   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
21268   verifyFormat("vector<::std::string> x4;", Spaces);
21269   verifyFormat("vector<int> x5;", Spaces);
21270   verifyFormat("Foo<int, Bar> x6;", Spaces);
21271   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
21272 
21273   verifyFormat("A<A<int>>();", Spaces);
21274 
21275   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
21276   verifyFormat("vector<::std::string> x4;", Spaces);
21277   verifyFormat("vector< ::std::string > x4;", Spaces);
21278   verifyFormat("vector<int> x5;", Spaces);
21279   verifyFormat("vector< int > x5;", Spaces);
21280   verifyFormat("Foo<int, Bar> x6;", Spaces);
21281   verifyFormat("Foo< int, Bar > x6;", Spaces);
21282   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
21283   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
21284 
21285   verifyFormat("A<A<int>>();", Spaces);
21286   verifyFormat("A< A< int > >();", Spaces);
21287   verifyFormat("A<A<int > >();", Spaces);
21288   verifyFormat("A< A< int>>();", Spaces);
21289 
21290   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
21291   verifyFormat("// clang-format off\n"
21292                "foo<<<1, 1>>>();\n"
21293                "// clang-format on\n",
21294                Spaces);
21295   verifyFormat("// clang-format off\n"
21296                "foo< < <1, 1> > >();\n"
21297                "// clang-format on\n",
21298                Spaces);
21299 }
21300 
21301 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
21302   FormatStyle Style = getLLVMStyle();
21303   Style.SpaceAfterTemplateKeyword = false;
21304   verifyFormat("template<int> void foo();", Style);
21305 }
21306 
21307 TEST_F(FormatTest, TripleAngleBrackets) {
21308   verifyFormat("f<<<1, 1>>>();");
21309   verifyFormat("f<<<1, 1, 1, s>>>();");
21310   verifyFormat("f<<<a, b, c, d>>>();");
21311   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
21312   verifyFormat("f<param><<<1, 1>>>();");
21313   verifyFormat("f<1><<<1, 1>>>();");
21314   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
21315   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21316                "aaaaaaaaaaa<<<\n    1, 1>>>();");
21317   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
21318                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
21319 }
21320 
21321 TEST_F(FormatTest, MergeLessLessAtEnd) {
21322   verifyFormat("<<");
21323   EXPECT_EQ("< < <", format("\\\n<<<"));
21324   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21325                "aaallvm::outs() <<");
21326   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
21327                "aaaallvm::outs()\n    <<");
21328 }
21329 
21330 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
21331   std::string code = "#if A\n"
21332                      "#if B\n"
21333                      "a.\n"
21334                      "#endif\n"
21335                      "    a = 1;\n"
21336                      "#else\n"
21337                      "#endif\n"
21338                      "#if C\n"
21339                      "#else\n"
21340                      "#endif\n";
21341   EXPECT_EQ(code, format(code));
21342 }
21343 
21344 TEST_F(FormatTest, HandleConflictMarkers) {
21345   // Git/SVN conflict markers.
21346   EXPECT_EQ("int a;\n"
21347             "void f() {\n"
21348             "  callme(some(parameter1,\n"
21349             "<<<<<<< text by the vcs\n"
21350             "              parameter2),\n"
21351             "||||||| text by the vcs\n"
21352             "              parameter2),\n"
21353             "         parameter3,\n"
21354             "======= text by the vcs\n"
21355             "              parameter2, parameter3),\n"
21356             ">>>>>>> text by the vcs\n"
21357             "         otherparameter);\n",
21358             format("int a;\n"
21359                    "void f() {\n"
21360                    "  callme(some(parameter1,\n"
21361                    "<<<<<<< text by the vcs\n"
21362                    "  parameter2),\n"
21363                    "||||||| text by the vcs\n"
21364                    "  parameter2),\n"
21365                    "  parameter3,\n"
21366                    "======= text by the vcs\n"
21367                    "  parameter2,\n"
21368                    "  parameter3),\n"
21369                    ">>>>>>> text by the vcs\n"
21370                    "  otherparameter);\n"));
21371 
21372   // Perforce markers.
21373   EXPECT_EQ("void f() {\n"
21374             "  function(\n"
21375             ">>>> text by the vcs\n"
21376             "      parameter,\n"
21377             "==== text by the vcs\n"
21378             "      parameter,\n"
21379             "==== text by the vcs\n"
21380             "      parameter,\n"
21381             "<<<< text by the vcs\n"
21382             "      parameter);\n",
21383             format("void f() {\n"
21384                    "  function(\n"
21385                    ">>>> text by the vcs\n"
21386                    "  parameter,\n"
21387                    "==== text by the vcs\n"
21388                    "  parameter,\n"
21389                    "==== text by the vcs\n"
21390                    "  parameter,\n"
21391                    "<<<< text by the vcs\n"
21392                    "  parameter);\n"));
21393 
21394   EXPECT_EQ("<<<<<<<\n"
21395             "|||||||\n"
21396             "=======\n"
21397             ">>>>>>>",
21398             format("<<<<<<<\n"
21399                    "|||||||\n"
21400                    "=======\n"
21401                    ">>>>>>>"));
21402 
21403   EXPECT_EQ("<<<<<<<\n"
21404             "|||||||\n"
21405             "int i;\n"
21406             "=======\n"
21407             ">>>>>>>",
21408             format("<<<<<<<\n"
21409                    "|||||||\n"
21410                    "int i;\n"
21411                    "=======\n"
21412                    ">>>>>>>"));
21413 
21414   // FIXME: Handle parsing of macros around conflict markers correctly:
21415   EXPECT_EQ("#define Macro \\\n"
21416             "<<<<<<<\n"
21417             "Something \\\n"
21418             "|||||||\n"
21419             "Else \\\n"
21420             "=======\n"
21421             "Other \\\n"
21422             ">>>>>>>\n"
21423             "    End int i;\n",
21424             format("#define Macro \\\n"
21425                    "<<<<<<<\n"
21426                    "  Something \\\n"
21427                    "|||||||\n"
21428                    "  Else \\\n"
21429                    "=======\n"
21430                    "  Other \\\n"
21431                    ">>>>>>>\n"
21432                    "  End\n"
21433                    "int i;\n"));
21434 
21435   verifyFormat(R"(====
21436 #ifdef A
21437 a
21438 #else
21439 b
21440 #endif
21441 )");
21442 }
21443 
21444 TEST_F(FormatTest, DisableRegions) {
21445   EXPECT_EQ("int i;\n"
21446             "// clang-format off\n"
21447             "  int j;\n"
21448             "// clang-format on\n"
21449             "int k;",
21450             format(" int  i;\n"
21451                    "   // clang-format off\n"
21452                    "  int j;\n"
21453                    " // clang-format on\n"
21454                    "   int   k;"));
21455   EXPECT_EQ("int i;\n"
21456             "/* clang-format off */\n"
21457             "  int j;\n"
21458             "/* clang-format on */\n"
21459             "int k;",
21460             format(" int  i;\n"
21461                    "   /* clang-format off */\n"
21462                    "  int j;\n"
21463                    " /* clang-format on */\n"
21464                    "   int   k;"));
21465 
21466   // Don't reflow comments within disabled regions.
21467   EXPECT_EQ("// clang-format off\n"
21468             "// long long long long long long line\n"
21469             "/* clang-format on */\n"
21470             "/* long long long\n"
21471             " * long long long\n"
21472             " * line */\n"
21473             "int i;\n"
21474             "/* clang-format off */\n"
21475             "/* long long long long long long line */\n",
21476             format("// clang-format off\n"
21477                    "// long long long long long long line\n"
21478                    "/* clang-format on */\n"
21479                    "/* long long long long long long line */\n"
21480                    "int i;\n"
21481                    "/* clang-format off */\n"
21482                    "/* long long long long long long line */\n",
21483                    getLLVMStyleWithColumns(20)));
21484 }
21485 
21486 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
21487   format("? ) =");
21488   verifyNoCrash("#define a\\\n /**/}");
21489 }
21490 
21491 TEST_F(FormatTest, FormatsTableGenCode) {
21492   FormatStyle Style = getLLVMStyle();
21493   Style.Language = FormatStyle::LK_TableGen;
21494   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
21495 }
21496 
21497 TEST_F(FormatTest, ArrayOfTemplates) {
21498   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
21499             format("auto a = new unique_ptr<int > [ 10];"));
21500 
21501   FormatStyle Spaces = getLLVMStyle();
21502   Spaces.SpacesInSquareBrackets = true;
21503   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
21504             format("auto a = new unique_ptr<int > [10];", Spaces));
21505 }
21506 
21507 TEST_F(FormatTest, ArrayAsTemplateType) {
21508   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
21509             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
21510 
21511   FormatStyle Spaces = getLLVMStyle();
21512   Spaces.SpacesInSquareBrackets = true;
21513   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
21514             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
21515 }
21516 
21517 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
21518 
21519 TEST(FormatStyle, GetStyleWithEmptyFileName) {
21520   llvm::vfs::InMemoryFileSystem FS;
21521   auto Style1 = getStyle("file", "", "Google", "", &FS);
21522   ASSERT_TRUE((bool)Style1);
21523   ASSERT_EQ(*Style1, getGoogleStyle());
21524 }
21525 
21526 TEST(FormatStyle, GetStyleOfFile) {
21527   llvm::vfs::InMemoryFileSystem FS;
21528   // Test 1: format file in the same directory.
21529   ASSERT_TRUE(
21530       FS.addFile("/a/.clang-format", 0,
21531                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
21532   ASSERT_TRUE(
21533       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21534   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
21535   ASSERT_TRUE((bool)Style1);
21536   ASSERT_EQ(*Style1, getLLVMStyle());
21537 
21538   // Test 2.1: fallback to default.
21539   ASSERT_TRUE(
21540       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21541   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
21542   ASSERT_TRUE((bool)Style2);
21543   ASSERT_EQ(*Style2, getMozillaStyle());
21544 
21545   // Test 2.2: no format on 'none' fallback style.
21546   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21547   ASSERT_TRUE((bool)Style2);
21548   ASSERT_EQ(*Style2, getNoStyle());
21549 
21550   // Test 2.3: format if config is found with no based style while fallback is
21551   // 'none'.
21552   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
21553                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
21554   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21555   ASSERT_TRUE((bool)Style2);
21556   ASSERT_EQ(*Style2, getLLVMStyle());
21557 
21558   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
21559   Style2 = getStyle("{}", "a.h", "none", "", &FS);
21560   ASSERT_TRUE((bool)Style2);
21561   ASSERT_EQ(*Style2, getLLVMStyle());
21562 
21563   // Test 3: format file in parent directory.
21564   ASSERT_TRUE(
21565       FS.addFile("/c/.clang-format", 0,
21566                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21567   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
21568                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21569   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21570   ASSERT_TRUE((bool)Style3);
21571   ASSERT_EQ(*Style3, getGoogleStyle());
21572 
21573   // Test 4: error on invalid fallback style
21574   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
21575   ASSERT_FALSE((bool)Style4);
21576   llvm::consumeError(Style4.takeError());
21577 
21578   // Test 5: error on invalid yaml on command line
21579   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
21580   ASSERT_FALSE((bool)Style5);
21581   llvm::consumeError(Style5.takeError());
21582 
21583   // Test 6: error on invalid style
21584   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
21585   ASSERT_FALSE((bool)Style6);
21586   llvm::consumeError(Style6.takeError());
21587 
21588   // Test 7: found config file, error on parsing it
21589   ASSERT_TRUE(
21590       FS.addFile("/d/.clang-format", 0,
21591                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
21592                                                   "InvalidKey: InvalidValue")));
21593   ASSERT_TRUE(
21594       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21595   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
21596   ASSERT_FALSE((bool)Style7a);
21597   llvm::consumeError(Style7a.takeError());
21598 
21599   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
21600   ASSERT_TRUE((bool)Style7b);
21601 
21602   // Test 8: inferred per-language defaults apply.
21603   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
21604   ASSERT_TRUE((bool)StyleTd);
21605   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
21606 
21607   // Test 9.1.1: overwriting a file style, when no parent file exists with no
21608   // fallback style.
21609   ASSERT_TRUE(FS.addFile(
21610       "/e/sub/.clang-format", 0,
21611       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
21612                                        "ColumnLimit: 20")));
21613   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
21614                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21615   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21616   ASSERT_TRUE(static_cast<bool>(Style9));
21617   ASSERT_EQ(*Style9, [] {
21618     auto Style = getNoStyle();
21619     Style.ColumnLimit = 20;
21620     return Style;
21621   }());
21622 
21623   // Test 9.1.2: propagate more than one level with no parent file.
21624   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
21625                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21626   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
21627                          llvm::MemoryBuffer::getMemBuffer(
21628                              "BasedOnStyle: InheritParentConfig\n"
21629                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
21630   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
21631 
21632   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21633   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21634   ASSERT_TRUE(static_cast<bool>(Style9));
21635   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
21636     auto Style = getNoStyle();
21637     Style.ColumnLimit = 20;
21638     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21639     return Style;
21640   }());
21641 
21642   // Test 9.2: with LLVM fallback style
21643   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
21644   ASSERT_TRUE(static_cast<bool>(Style9));
21645   ASSERT_EQ(*Style9, [] {
21646     auto Style = getLLVMStyle();
21647     Style.ColumnLimit = 20;
21648     return Style;
21649   }());
21650 
21651   // Test 9.3: with a parent file
21652   ASSERT_TRUE(
21653       FS.addFile("/e/.clang-format", 0,
21654                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
21655                                                   "UseTab: Always")));
21656   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21657   ASSERT_TRUE(static_cast<bool>(Style9));
21658   ASSERT_EQ(*Style9, [] {
21659     auto Style = getGoogleStyle();
21660     Style.ColumnLimit = 20;
21661     Style.UseTab = FormatStyle::UT_Always;
21662     return Style;
21663   }());
21664 
21665   // Test 9.4: propagate more than one level with a parent file.
21666   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
21667     auto Style = getGoogleStyle();
21668     Style.ColumnLimit = 20;
21669     Style.UseTab = FormatStyle::UT_Always;
21670     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21671     return Style;
21672   }();
21673 
21674   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21675   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21676   ASSERT_TRUE(static_cast<bool>(Style9));
21677   ASSERT_EQ(*Style9, SubSubStyle);
21678 
21679   // Test 9.5: use InheritParentConfig as style name
21680   Style9 =
21681       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
21682   ASSERT_TRUE(static_cast<bool>(Style9));
21683   ASSERT_EQ(*Style9, SubSubStyle);
21684 
21685   // Test 9.6: use command line style with inheritance
21686   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
21687                     "none", "", &FS);
21688   ASSERT_TRUE(static_cast<bool>(Style9));
21689   ASSERT_EQ(*Style9, SubSubStyle);
21690 
21691   // Test 9.7: use command line style with inheritance and own config
21692   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
21693                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
21694                     "/e/sub/code.cpp", "none", "", &FS);
21695   ASSERT_TRUE(static_cast<bool>(Style9));
21696   ASSERT_EQ(*Style9, SubSubStyle);
21697 
21698   // Test 9.8: use inheritance from a file without BasedOnStyle
21699   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
21700                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
21701   ASSERT_TRUE(
21702       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
21703                  llvm::MemoryBuffer::getMemBuffer(
21704                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
21705   // Make sure we do not use the fallback style
21706   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
21707   ASSERT_TRUE(static_cast<bool>(Style9));
21708   ASSERT_EQ(*Style9, [] {
21709     auto Style = getLLVMStyle();
21710     Style.ColumnLimit = 123;
21711     return Style;
21712   }());
21713 
21714   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
21715   ASSERT_TRUE(static_cast<bool>(Style9));
21716   ASSERT_EQ(*Style9, [] {
21717     auto Style = getLLVMStyle();
21718     Style.ColumnLimit = 123;
21719     Style.IndentWidth = 7;
21720     return Style;
21721   }());
21722 
21723   // Test 9.9: use inheritance from a specific config file.
21724   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
21725                     "none", "", &FS);
21726   ASSERT_TRUE(static_cast<bool>(Style9));
21727   ASSERT_EQ(*Style9, SubSubStyle);
21728 }
21729 
21730 TEST(FormatStyle, GetStyleOfSpecificFile) {
21731   llvm::vfs::InMemoryFileSystem FS;
21732   // Specify absolute path to a format file in a parent directory.
21733   ASSERT_TRUE(
21734       FS.addFile("/e/.clang-format", 0,
21735                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
21736   ASSERT_TRUE(
21737       FS.addFile("/e/explicit.clang-format", 0,
21738                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21739   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
21740                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21741   auto Style = getStyle("file:/e/explicit.clang-format",
21742                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21743   ASSERT_TRUE(static_cast<bool>(Style));
21744   ASSERT_EQ(*Style, getGoogleStyle());
21745 
21746   // Specify relative path to a format file.
21747   ASSERT_TRUE(
21748       FS.addFile("../../e/explicit.clang-format", 0,
21749                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21750   Style = getStyle("file:../../e/explicit.clang-format",
21751                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21752   ASSERT_TRUE(static_cast<bool>(Style));
21753   ASSERT_EQ(*Style, getGoogleStyle());
21754 
21755   // Specify path to a format file that does not exist.
21756   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
21757                    "LLVM", "", &FS);
21758   ASSERT_FALSE(static_cast<bool>(Style));
21759   llvm::consumeError(Style.takeError());
21760 
21761   // Specify path to a file on the filesystem.
21762   SmallString<128> FormatFilePath;
21763   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
21764       "FormatFileTest", "tpl", FormatFilePath);
21765   EXPECT_FALSE((bool)ECF);
21766   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
21767   EXPECT_FALSE((bool)ECF);
21768   FormatFileTest << "BasedOnStyle: Google\n";
21769   FormatFileTest.close();
21770 
21771   SmallString<128> TestFilePath;
21772   std::error_code ECT =
21773       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
21774   EXPECT_FALSE((bool)ECT);
21775   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
21776   CodeFileTest << "int i;\n";
21777   CodeFileTest.close();
21778 
21779   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
21780   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
21781 
21782   llvm::sys::fs::remove(FormatFilePath.c_str());
21783   llvm::sys::fs::remove(TestFilePath.c_str());
21784   ASSERT_TRUE(static_cast<bool>(Style));
21785   ASSERT_EQ(*Style, getGoogleStyle());
21786 }
21787 
21788 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
21789   // Column limit is 20.
21790   std::string Code = "Type *a =\n"
21791                      "    new Type();\n"
21792                      "g(iiiii, 0, jjjjj,\n"
21793                      "  0, kkkkk, 0, mm);\n"
21794                      "int  bad     = format   ;";
21795   std::string Expected = "auto a = new Type();\n"
21796                          "g(iiiii, nullptr,\n"
21797                          "  jjjjj, nullptr,\n"
21798                          "  kkkkk, nullptr,\n"
21799                          "  mm);\n"
21800                          "int  bad     = format   ;";
21801   FileID ID = Context.createInMemoryFile("format.cpp", Code);
21802   tooling::Replacements Replaces = toReplacements(
21803       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
21804                             "auto "),
21805        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
21806                             "nullptr"),
21807        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
21808                             "nullptr"),
21809        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
21810                             "nullptr")});
21811 
21812   FormatStyle Style = getLLVMStyle();
21813   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
21814   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21815   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21816       << llvm::toString(FormattedReplaces.takeError()) << "\n";
21817   auto Result = applyAllReplacements(Code, *FormattedReplaces);
21818   EXPECT_TRUE(static_cast<bool>(Result));
21819   EXPECT_EQ(Expected, *Result);
21820 }
21821 
21822 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
21823   std::string Code = "#include \"a.h\"\n"
21824                      "#include \"c.h\"\n"
21825                      "\n"
21826                      "int main() {\n"
21827                      "  return 0;\n"
21828                      "}";
21829   std::string Expected = "#include \"a.h\"\n"
21830                          "#include \"b.h\"\n"
21831                          "#include \"c.h\"\n"
21832                          "\n"
21833                          "int main() {\n"
21834                          "  return 0;\n"
21835                          "}";
21836   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
21837   tooling::Replacements Replaces = toReplacements(
21838       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
21839                             "#include \"b.h\"\n")});
21840 
21841   FormatStyle Style = getLLVMStyle();
21842   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
21843   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21844   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21845       << llvm::toString(FormattedReplaces.takeError()) << "\n";
21846   auto Result = applyAllReplacements(Code, *FormattedReplaces);
21847   EXPECT_TRUE(static_cast<bool>(Result));
21848   EXPECT_EQ(Expected, *Result);
21849 }
21850 
21851 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
21852   EXPECT_EQ("using std::cin;\n"
21853             "using std::cout;",
21854             format("using std::cout;\n"
21855                    "using std::cin;",
21856                    getGoogleStyle()));
21857 }
21858 
21859 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
21860   FormatStyle Style = getLLVMStyle();
21861   Style.Standard = FormatStyle::LS_Cpp03;
21862   // cpp03 recognize this string as identifier u8 and literal character 'a'
21863   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
21864 }
21865 
21866 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
21867   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
21868   // all modes, including C++11, C++14 and C++17
21869   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
21870 }
21871 
21872 TEST_F(FormatTest, DoNotFormatLikelyXml) {
21873   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
21874   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
21875 }
21876 
21877 TEST_F(FormatTest, StructuredBindings) {
21878   // Structured bindings is a C++17 feature.
21879   // all modes, including C++11, C++14 and C++17
21880   verifyFormat("auto [a, b] = f();");
21881   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
21882   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
21883   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
21884   EXPECT_EQ("auto const volatile [a, b] = f();",
21885             format("auto  const   volatile[a, b] = f();"));
21886   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
21887   EXPECT_EQ("auto &[a, b, c] = f();",
21888             format("auto   &[  a  ,  b,c   ] = f();"));
21889   EXPECT_EQ("auto &&[a, b, c] = f();",
21890             format("auto   &&[  a  ,  b,c   ] = f();"));
21891   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
21892   EXPECT_EQ("auto const volatile &&[a, b] = f();",
21893             format("auto  const  volatile  &&[a, b] = f();"));
21894   EXPECT_EQ("auto const &&[a, b] = f();",
21895             format("auto  const   &&  [a, b] = f();"));
21896   EXPECT_EQ("const auto &[a, b] = f();",
21897             format("const  auto  &  [a, b] = f();"));
21898   EXPECT_EQ("const auto volatile &&[a, b] = f();",
21899             format("const  auto   volatile  &&[a, b] = f();"));
21900   EXPECT_EQ("volatile const auto &&[a, b] = f();",
21901             format("volatile  const  auto   &&[a, b] = f();"));
21902   EXPECT_EQ("const auto &&[a, b] = f();",
21903             format("const  auto  &&  [a, b] = f();"));
21904 
21905   // Make sure we don't mistake structured bindings for lambdas.
21906   FormatStyle PointerMiddle = getLLVMStyle();
21907   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
21908   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
21909   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
21910   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
21911   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
21912   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
21913   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
21914   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
21915   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
21916   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
21917   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
21918   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
21919   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
21920 
21921   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
21922             format("for (const auto   &&   [a, b] : some_range) {\n}"));
21923   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
21924             format("for (const auto   &   [a, b] : some_range) {\n}"));
21925   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
21926             format("for (const auto[a, b] : some_range) {\n}"));
21927   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
21928   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
21929   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
21930   EXPECT_EQ("auto const &[x, y](expr);",
21931             format("auto  const  &  [x,y]  (expr);"));
21932   EXPECT_EQ("auto const &&[x, y](expr);",
21933             format("auto  const  &&  [x,y]  (expr);"));
21934   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
21935   EXPECT_EQ("auto const &[x, y]{expr};",
21936             format("auto  const  &  [x,y]  {expr};"));
21937   EXPECT_EQ("auto const &&[x, y]{expr};",
21938             format("auto  const  &&  [x,y]  {expr};"));
21939 
21940   FormatStyle Spaces = getLLVMStyle();
21941   Spaces.SpacesInSquareBrackets = true;
21942   verifyFormat("auto [ a, b ] = f();", Spaces);
21943   verifyFormat("auto &&[ a, b ] = f();", Spaces);
21944   verifyFormat("auto &[ a, b ] = f();", Spaces);
21945   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
21946   verifyFormat("auto const &[ a, b ] = f();", Spaces);
21947 }
21948 
21949 TEST_F(FormatTest, FileAndCode) {
21950   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
21951   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
21952   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
21953   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
21954   EXPECT_EQ(FormatStyle::LK_ObjC,
21955             guessLanguage("foo.h", "@interface Foo\n@end\n"));
21956   EXPECT_EQ(
21957       FormatStyle::LK_ObjC,
21958       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
21959   EXPECT_EQ(FormatStyle::LK_ObjC,
21960             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
21961   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
21962   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
21963   EXPECT_EQ(FormatStyle::LK_ObjC,
21964             guessLanguage("foo", "@interface Foo\n@end\n"));
21965   EXPECT_EQ(FormatStyle::LK_ObjC,
21966             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
21967   EXPECT_EQ(
21968       FormatStyle::LK_ObjC,
21969       guessLanguage("foo.h",
21970                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
21971   EXPECT_EQ(
21972       FormatStyle::LK_Cpp,
21973       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
21974 }
21975 
21976 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
21977   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
21978   EXPECT_EQ(FormatStyle::LK_ObjC,
21979             guessLanguage("foo.h", "array[[calculator getIndex]];"));
21980   EXPECT_EQ(FormatStyle::LK_Cpp,
21981             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
21982   EXPECT_EQ(
21983       FormatStyle::LK_Cpp,
21984       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
21985   EXPECT_EQ(FormatStyle::LK_ObjC,
21986             guessLanguage("foo.h", "[[noreturn foo] bar];"));
21987   EXPECT_EQ(FormatStyle::LK_Cpp,
21988             guessLanguage("foo.h", "[[clang::fallthrough]];"));
21989   EXPECT_EQ(FormatStyle::LK_ObjC,
21990             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
21991   EXPECT_EQ(FormatStyle::LK_Cpp,
21992             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
21993   EXPECT_EQ(FormatStyle::LK_Cpp,
21994             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
21995   EXPECT_EQ(FormatStyle::LK_ObjC,
21996             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
21997   EXPECT_EQ(FormatStyle::LK_Cpp,
21998             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
21999   EXPECT_EQ(
22000       FormatStyle::LK_Cpp,
22001       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
22002   EXPECT_EQ(
22003       FormatStyle::LK_Cpp,
22004       guessLanguage("foo.h",
22005                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
22006   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
22007 }
22008 
22009 TEST_F(FormatTest, GuessLanguageWithCaret) {
22010   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
22011   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
22012   EXPECT_EQ(FormatStyle::LK_ObjC,
22013             guessLanguage("foo.h", "int(^)(char, float);"));
22014   EXPECT_EQ(FormatStyle::LK_ObjC,
22015             guessLanguage("foo.h", "int(^foo)(char, float);"));
22016   EXPECT_EQ(FormatStyle::LK_ObjC,
22017             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
22018   EXPECT_EQ(FormatStyle::LK_ObjC,
22019             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
22020   EXPECT_EQ(
22021       FormatStyle::LK_ObjC,
22022       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
22023 }
22024 
22025 TEST_F(FormatTest, GuessLanguageWithPragmas) {
22026   EXPECT_EQ(FormatStyle::LK_Cpp,
22027             guessLanguage("foo.h", "__pragma(warning(disable:))"));
22028   EXPECT_EQ(FormatStyle::LK_Cpp,
22029             guessLanguage("foo.h", "#pragma(warning(disable:))"));
22030   EXPECT_EQ(FormatStyle::LK_Cpp,
22031             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
22032 }
22033 
22034 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
22035   // ASM symbolic names are identifiers that must be surrounded by [] without
22036   // space in between:
22037   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
22038 
22039   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
22040   verifyFormat(R"(//
22041 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
22042 )");
22043 
22044   // A list of several ASM symbolic names.
22045   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
22046 
22047   // ASM symbolic names in inline ASM with inputs and outputs.
22048   verifyFormat(R"(//
22049 asm("cmoveq %1, %2, %[result]"
22050     : [result] "=r"(result)
22051     : "r"(test), "r"(new), "[result]"(old));
22052 )");
22053 
22054   // ASM symbolic names in inline ASM with no outputs.
22055   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
22056 }
22057 
22058 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
22059   EXPECT_EQ(FormatStyle::LK_Cpp,
22060             guessLanguage("foo.h", "void f() {\n"
22061                                    "  asm (\"mov %[e], %[d]\"\n"
22062                                    "     : [d] \"=rm\" (d)\n"
22063                                    "       [e] \"rm\" (*e));\n"
22064                                    "}"));
22065   EXPECT_EQ(FormatStyle::LK_Cpp,
22066             guessLanguage("foo.h", "void f() {\n"
22067                                    "  _asm (\"mov %[e], %[d]\"\n"
22068                                    "     : [d] \"=rm\" (d)\n"
22069                                    "       [e] \"rm\" (*e));\n"
22070                                    "}"));
22071   EXPECT_EQ(FormatStyle::LK_Cpp,
22072             guessLanguage("foo.h", "void f() {\n"
22073                                    "  __asm (\"mov %[e], %[d]\"\n"
22074                                    "     : [d] \"=rm\" (d)\n"
22075                                    "       [e] \"rm\" (*e));\n"
22076                                    "}"));
22077   EXPECT_EQ(FormatStyle::LK_Cpp,
22078             guessLanguage("foo.h", "void f() {\n"
22079                                    "  __asm__ (\"mov %[e], %[d]\"\n"
22080                                    "     : [d] \"=rm\" (d)\n"
22081                                    "       [e] \"rm\" (*e));\n"
22082                                    "}"));
22083   EXPECT_EQ(FormatStyle::LK_Cpp,
22084             guessLanguage("foo.h", "void f() {\n"
22085                                    "  asm (\"mov %[e], %[d]\"\n"
22086                                    "     : [d] \"=rm\" (d),\n"
22087                                    "       [e] \"rm\" (*e));\n"
22088                                    "}"));
22089   EXPECT_EQ(FormatStyle::LK_Cpp,
22090             guessLanguage("foo.h", "void f() {\n"
22091                                    "  asm volatile (\"mov %[e], %[d]\"\n"
22092                                    "     : [d] \"=rm\" (d)\n"
22093                                    "       [e] \"rm\" (*e));\n"
22094                                    "}"));
22095 }
22096 
22097 TEST_F(FormatTest, GuessLanguageWithChildLines) {
22098   EXPECT_EQ(FormatStyle::LK_Cpp,
22099             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
22100   EXPECT_EQ(FormatStyle::LK_ObjC,
22101             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
22102   EXPECT_EQ(
22103       FormatStyle::LK_Cpp,
22104       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
22105   EXPECT_EQ(
22106       FormatStyle::LK_ObjC,
22107       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
22108 }
22109 
22110 TEST_F(FormatTest, TypenameMacros) {
22111   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
22112 
22113   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
22114   FormatStyle Google = getGoogleStyleWithColumns(0);
22115   Google.TypenameMacros = TypenameMacros;
22116   verifyFormat("struct foo {\n"
22117                "  int bar;\n"
22118                "  TAILQ_ENTRY(a) bleh;\n"
22119                "};",
22120                Google);
22121 
22122   FormatStyle Macros = getLLVMStyle();
22123   Macros.TypenameMacros = TypenameMacros;
22124 
22125   verifyFormat("STACK_OF(int) a;", Macros);
22126   verifyFormat("STACK_OF(int) *a;", Macros);
22127   verifyFormat("STACK_OF(int const *) *a;", Macros);
22128   verifyFormat("STACK_OF(int *const) *a;", Macros);
22129   verifyFormat("STACK_OF(int, string) a;", Macros);
22130   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
22131   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
22132   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
22133   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
22134   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
22135   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
22136 
22137   Macros.PointerAlignment = FormatStyle::PAS_Left;
22138   verifyFormat("STACK_OF(int)* a;", Macros);
22139   verifyFormat("STACK_OF(int*)* a;", Macros);
22140   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
22141   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
22142   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
22143 }
22144 
22145 TEST_F(FormatTest, AtomicQualifier) {
22146   // Check that we treate _Atomic as a type and not a function call
22147   FormatStyle Google = getGoogleStyleWithColumns(0);
22148   verifyFormat("struct foo {\n"
22149                "  int a1;\n"
22150                "  _Atomic(a) a2;\n"
22151                "  _Atomic(_Atomic(int) *const) a3;\n"
22152                "};",
22153                Google);
22154   verifyFormat("_Atomic(uint64_t) a;");
22155   verifyFormat("_Atomic(uint64_t) *a;");
22156   verifyFormat("_Atomic(uint64_t const *) *a;");
22157   verifyFormat("_Atomic(uint64_t *const) *a;");
22158   verifyFormat("_Atomic(const uint64_t *) *a;");
22159   verifyFormat("_Atomic(uint64_t) a;");
22160   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
22161   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
22162   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
22163   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
22164 
22165   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
22166   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
22167   FormatStyle Style = getLLVMStyle();
22168   Style.PointerAlignment = FormatStyle::PAS_Left;
22169   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
22170   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
22171   verifyFormat("_Atomic(int)* a;", Style);
22172   verifyFormat("_Atomic(int*)* a;", Style);
22173   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
22174 
22175   Style.SpacesInCStyleCastParentheses = true;
22176   Style.SpacesInParentheses = false;
22177   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
22178   Style.SpacesInCStyleCastParentheses = false;
22179   Style.SpacesInParentheses = true;
22180   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
22181   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
22182 }
22183 
22184 TEST_F(FormatTest, AmbersandInLamda) {
22185   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
22186   FormatStyle AlignStyle = getLLVMStyle();
22187   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
22188   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22189   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
22190   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
22191 }
22192 
22193 TEST_F(FormatTest, SpacesInConditionalStatement) {
22194   FormatStyle Spaces = getLLVMStyle();
22195   Spaces.IfMacros.clear();
22196   Spaces.IfMacros.push_back("MYIF");
22197   Spaces.SpacesInConditionalStatement = true;
22198   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
22199   verifyFormat("if ( !a )\n  return;", Spaces);
22200   verifyFormat("if ( a )\n  return;", Spaces);
22201   verifyFormat("if constexpr ( a )\n  return;", Spaces);
22202   verifyFormat("MYIF ( a )\n  return;", Spaces);
22203   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
22204   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
22205   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
22206   verifyFormat("while ( a )\n  return;", Spaces);
22207   verifyFormat("while ( (a && b) )\n  return;", Spaces);
22208   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
22209   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
22210   // Check that space on the left of "::" is inserted as expected at beginning
22211   // of condition.
22212   verifyFormat("while ( ::func() )\n  return;", Spaces);
22213 
22214   // Check impact of ControlStatementsExceptControlMacros is honored.
22215   Spaces.SpaceBeforeParens =
22216       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
22217   verifyFormat("MYIF( a )\n  return;", Spaces);
22218   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
22219   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
22220 }
22221 
22222 TEST_F(FormatTest, AlternativeOperators) {
22223   // Test case for ensuring alternate operators are not
22224   // combined with their right most neighbour.
22225   verifyFormat("int a and b;");
22226   verifyFormat("int a and_eq b;");
22227   verifyFormat("int a bitand b;");
22228   verifyFormat("int a bitor b;");
22229   verifyFormat("int a compl b;");
22230   verifyFormat("int a not b;");
22231   verifyFormat("int a not_eq b;");
22232   verifyFormat("int a or b;");
22233   verifyFormat("int a xor b;");
22234   verifyFormat("int a xor_eq b;");
22235   verifyFormat("return this not_eq bitand other;");
22236   verifyFormat("bool operator not_eq(const X bitand other)");
22237 
22238   verifyFormat("int a and 5;");
22239   verifyFormat("int a and_eq 5;");
22240   verifyFormat("int a bitand 5;");
22241   verifyFormat("int a bitor 5;");
22242   verifyFormat("int a compl 5;");
22243   verifyFormat("int a not 5;");
22244   verifyFormat("int a not_eq 5;");
22245   verifyFormat("int a or 5;");
22246   verifyFormat("int a xor 5;");
22247   verifyFormat("int a xor_eq 5;");
22248 
22249   verifyFormat("int a compl(5);");
22250   verifyFormat("int a not(5);");
22251 
22252   /* FIXME handle alternate tokens
22253    * https://en.cppreference.com/w/cpp/language/operator_alternative
22254   // alternative tokens
22255   verifyFormat("compl foo();");     //  ~foo();
22256   verifyFormat("foo() <%%>;");      // foo();
22257   verifyFormat("void foo() <%%>;"); // void foo(){}
22258   verifyFormat("int a <:1:>;");     // int a[1];[
22259   verifyFormat("%:define ABC abc"); // #define ABC abc
22260   verifyFormat("%:%:");             // ##
22261   */
22262 }
22263 
22264 TEST_F(FormatTest, STLWhileNotDefineChed) {
22265   verifyFormat("#if defined(while)\n"
22266                "#define while EMIT WARNING C4005\n"
22267                "#endif // while");
22268 }
22269 
22270 TEST_F(FormatTest, OperatorSpacing) {
22271   FormatStyle Style = getLLVMStyle();
22272   Style.PointerAlignment = FormatStyle::PAS_Right;
22273   verifyFormat("Foo::operator*();", Style);
22274   verifyFormat("Foo::operator void *();", Style);
22275   verifyFormat("Foo::operator void **();", Style);
22276   verifyFormat("Foo::operator void *&();", Style);
22277   verifyFormat("Foo::operator void *&&();", Style);
22278   verifyFormat("Foo::operator void const *();", Style);
22279   verifyFormat("Foo::operator void const **();", Style);
22280   verifyFormat("Foo::operator void const *&();", Style);
22281   verifyFormat("Foo::operator void const *&&();", Style);
22282   verifyFormat("Foo::operator()(void *);", Style);
22283   verifyFormat("Foo::operator*(void *);", Style);
22284   verifyFormat("Foo::operator*();", Style);
22285   verifyFormat("Foo::operator**();", Style);
22286   verifyFormat("Foo::operator&();", Style);
22287   verifyFormat("Foo::operator<int> *();", Style);
22288   verifyFormat("Foo::operator<Foo> *();", Style);
22289   verifyFormat("Foo::operator<int> **();", Style);
22290   verifyFormat("Foo::operator<Foo> **();", Style);
22291   verifyFormat("Foo::operator<int> &();", Style);
22292   verifyFormat("Foo::operator<Foo> &();", Style);
22293   verifyFormat("Foo::operator<int> &&();", Style);
22294   verifyFormat("Foo::operator<Foo> &&();", Style);
22295   verifyFormat("Foo::operator<int> *&();", Style);
22296   verifyFormat("Foo::operator<Foo> *&();", Style);
22297   verifyFormat("Foo::operator<int> *&&();", Style);
22298   verifyFormat("Foo::operator<Foo> *&&();", Style);
22299   verifyFormat("operator*(int (*)(), class Foo);", Style);
22300 
22301   verifyFormat("Foo::operator&();", Style);
22302   verifyFormat("Foo::operator void &();", Style);
22303   verifyFormat("Foo::operator void const &();", Style);
22304   verifyFormat("Foo::operator()(void &);", Style);
22305   verifyFormat("Foo::operator&(void &);", Style);
22306   verifyFormat("Foo::operator&();", Style);
22307   verifyFormat("operator&(int (&)(), class Foo);", Style);
22308   verifyFormat("operator&&(int (&)(), class Foo);", Style);
22309 
22310   verifyFormat("Foo::operator&&();", Style);
22311   verifyFormat("Foo::operator**();", Style);
22312   verifyFormat("Foo::operator void &&();", Style);
22313   verifyFormat("Foo::operator void const &&();", Style);
22314   verifyFormat("Foo::operator()(void &&);", Style);
22315   verifyFormat("Foo::operator&&(void &&);", Style);
22316   verifyFormat("Foo::operator&&();", Style);
22317   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22318   verifyFormat("operator const nsTArrayRight<E> &()", Style);
22319   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
22320                Style);
22321   verifyFormat("operator void **()", Style);
22322   verifyFormat("operator const FooRight<Object> &()", Style);
22323   verifyFormat("operator const FooRight<Object> *()", Style);
22324   verifyFormat("operator const FooRight<Object> **()", Style);
22325   verifyFormat("operator const FooRight<Object> *&()", Style);
22326   verifyFormat("operator const FooRight<Object> *&&()", Style);
22327 
22328   Style.PointerAlignment = FormatStyle::PAS_Left;
22329   verifyFormat("Foo::operator*();", Style);
22330   verifyFormat("Foo::operator**();", Style);
22331   verifyFormat("Foo::operator void*();", Style);
22332   verifyFormat("Foo::operator void**();", Style);
22333   verifyFormat("Foo::operator void*&();", Style);
22334   verifyFormat("Foo::operator void*&&();", Style);
22335   verifyFormat("Foo::operator void const*();", Style);
22336   verifyFormat("Foo::operator void const**();", Style);
22337   verifyFormat("Foo::operator void const*&();", Style);
22338   verifyFormat("Foo::operator void const*&&();", Style);
22339   verifyFormat("Foo::operator/*comment*/ void*();", Style);
22340   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
22341   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
22342   verifyFormat("Foo::operator()(void*);", Style);
22343   verifyFormat("Foo::operator*(void*);", Style);
22344   verifyFormat("Foo::operator*();", Style);
22345   verifyFormat("Foo::operator<int>*();", Style);
22346   verifyFormat("Foo::operator<Foo>*();", Style);
22347   verifyFormat("Foo::operator<int>**();", Style);
22348   verifyFormat("Foo::operator<Foo>**();", Style);
22349   verifyFormat("Foo::operator<Foo>*&();", Style);
22350   verifyFormat("Foo::operator<int>&();", Style);
22351   verifyFormat("Foo::operator<Foo>&();", Style);
22352   verifyFormat("Foo::operator<int>&&();", Style);
22353   verifyFormat("Foo::operator<Foo>&&();", Style);
22354   verifyFormat("Foo::operator<int>*&();", Style);
22355   verifyFormat("Foo::operator<Foo>*&();", Style);
22356   verifyFormat("operator*(int (*)(), class Foo);", Style);
22357 
22358   verifyFormat("Foo::operator&();", Style);
22359   verifyFormat("Foo::operator void&();", Style);
22360   verifyFormat("Foo::operator void const&();", Style);
22361   verifyFormat("Foo::operator/*comment*/ void&();", Style);
22362   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
22363   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
22364   verifyFormat("Foo::operator()(void&);", Style);
22365   verifyFormat("Foo::operator&(void&);", Style);
22366   verifyFormat("Foo::operator&();", Style);
22367   verifyFormat("operator&(int (&)(), class Foo);", Style);
22368   verifyFormat("operator&(int (&&)(), class Foo);", Style);
22369   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22370 
22371   verifyFormat("Foo::operator&&();", Style);
22372   verifyFormat("Foo::operator void&&();", Style);
22373   verifyFormat("Foo::operator void const&&();", Style);
22374   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
22375   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
22376   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
22377   verifyFormat("Foo::operator()(void&&);", Style);
22378   verifyFormat("Foo::operator&&(void&&);", Style);
22379   verifyFormat("Foo::operator&&();", Style);
22380   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22381   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
22382   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
22383                Style);
22384   verifyFormat("operator void**()", Style);
22385   verifyFormat("operator const FooLeft<Object>&()", Style);
22386   verifyFormat("operator const FooLeft<Object>*()", Style);
22387   verifyFormat("operator const FooLeft<Object>**()", Style);
22388   verifyFormat("operator const FooLeft<Object>*&()", Style);
22389   verifyFormat("operator const FooLeft<Object>*&&()", Style);
22390 
22391   // PR45107
22392   verifyFormat("operator Vector<String>&();", Style);
22393   verifyFormat("operator const Vector<String>&();", Style);
22394   verifyFormat("operator foo::Bar*();", Style);
22395   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
22396   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
22397                Style);
22398 
22399   Style.PointerAlignment = FormatStyle::PAS_Middle;
22400   verifyFormat("Foo::operator*();", Style);
22401   verifyFormat("Foo::operator void *();", Style);
22402   verifyFormat("Foo::operator()(void *);", Style);
22403   verifyFormat("Foo::operator*(void *);", Style);
22404   verifyFormat("Foo::operator*();", Style);
22405   verifyFormat("operator*(int (*)(), class Foo);", Style);
22406 
22407   verifyFormat("Foo::operator&();", Style);
22408   verifyFormat("Foo::operator void &();", Style);
22409   verifyFormat("Foo::operator void const &();", Style);
22410   verifyFormat("Foo::operator()(void &);", Style);
22411   verifyFormat("Foo::operator&(void &);", Style);
22412   verifyFormat("Foo::operator&();", Style);
22413   verifyFormat("operator&(int (&)(), class Foo);", Style);
22414 
22415   verifyFormat("Foo::operator&&();", Style);
22416   verifyFormat("Foo::operator void &&();", Style);
22417   verifyFormat("Foo::operator void const &&();", Style);
22418   verifyFormat("Foo::operator()(void &&);", Style);
22419   verifyFormat("Foo::operator&&(void &&);", Style);
22420   verifyFormat("Foo::operator&&();", Style);
22421   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
22422 }
22423 
22424 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
22425   FormatStyle Style = getLLVMStyle();
22426   // PR46157
22427   verifyFormat("foo(operator+, -42);", Style);
22428   verifyFormat("foo(operator++, -42);", Style);
22429   verifyFormat("foo(operator--, -42);", Style);
22430   verifyFormat("foo(-42, operator--);", Style);
22431   verifyFormat("foo(-42, operator, );", Style);
22432   verifyFormat("foo(operator, , -42);", Style);
22433 }
22434 
22435 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
22436   FormatStyle Style = getLLVMStyle();
22437   Style.WhitespaceSensitiveMacros.push_back("FOO");
22438 
22439   // Don't use the helpers here, since 'mess up' will change the whitespace
22440   // and these are all whitespace sensitive by definition
22441   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
22442             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
22443   EXPECT_EQ(
22444       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
22445       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
22446   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
22447             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
22448   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
22449             "       Still=Intentional);",
22450             format("FOO(String-ized&Messy+But,: :\n"
22451                    "       Still=Intentional);",
22452                    Style));
22453   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
22454   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
22455             "       Still=Intentional);",
22456             format("FOO(String-ized=&Messy+But,: :\n"
22457                    "       Still=Intentional);",
22458                    Style));
22459 
22460   Style.ColumnLimit = 21;
22461   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
22462             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
22463 }
22464 
22465 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
22466   // These tests are not in NamespaceFixer because that doesn't
22467   // test its interaction with line wrapping
22468   FormatStyle Style = getLLVMStyleWithColumns(80);
22469   verifyFormat("namespace {\n"
22470                "int i;\n"
22471                "int j;\n"
22472                "} // namespace",
22473                Style);
22474 
22475   verifyFormat("namespace AAA {\n"
22476                "int i;\n"
22477                "int j;\n"
22478                "} // namespace AAA",
22479                Style);
22480 
22481   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
22482             "int i;\n"
22483             "int j;\n"
22484             "} // namespace Averyveryveryverylongnamespace",
22485             format("namespace Averyveryveryverylongnamespace {\n"
22486                    "int i;\n"
22487                    "int j;\n"
22488                    "}",
22489                    Style));
22490 
22491   EXPECT_EQ(
22492       "namespace "
22493       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
22494       "    went::mad::now {\n"
22495       "int i;\n"
22496       "int j;\n"
22497       "} // namespace\n"
22498       "  // "
22499       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
22500       "went::mad::now",
22501       format("namespace "
22502              "would::it::save::you::a::lot::of::time::if_::i::"
22503              "just::gave::up::and_::went::mad::now {\n"
22504              "int i;\n"
22505              "int j;\n"
22506              "}",
22507              Style));
22508 
22509   // This used to duplicate the comment again and again on subsequent runs
22510   EXPECT_EQ(
22511       "namespace "
22512       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
22513       "    went::mad::now {\n"
22514       "int i;\n"
22515       "int j;\n"
22516       "} // namespace\n"
22517       "  // "
22518       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
22519       "went::mad::now",
22520       format("namespace "
22521              "would::it::save::you::a::lot::of::time::if_::i::"
22522              "just::gave::up::and_::went::mad::now {\n"
22523              "int i;\n"
22524              "int j;\n"
22525              "} // namespace\n"
22526              "  // "
22527              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
22528              "and_::went::mad::now",
22529              Style));
22530 }
22531 
22532 TEST_F(FormatTest, LikelyUnlikely) {
22533   FormatStyle Style = getLLVMStyle();
22534 
22535   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22536                "  return 29;\n"
22537                "}",
22538                Style);
22539 
22540   verifyFormat("if (argc > 5) [[likely]] {\n"
22541                "  return 29;\n"
22542                "}",
22543                Style);
22544 
22545   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22546                "  return 29;\n"
22547                "} else [[likely]] {\n"
22548                "  return 42;\n"
22549                "}\n",
22550                Style);
22551 
22552   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22553                "  return 29;\n"
22554                "} else if (argc > 10) [[likely]] {\n"
22555                "  return 99;\n"
22556                "} else {\n"
22557                "  return 42;\n"
22558                "}\n",
22559                Style);
22560 
22561   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
22562                "  return 29;\n"
22563                "}",
22564                Style);
22565 
22566   verifyFormat("if (argc > 5) [[unlikely]]\n"
22567                "  return 29;\n",
22568                Style);
22569   verifyFormat("if (argc > 5) [[likely]]\n"
22570                "  return 29;\n",
22571                Style);
22572 
22573   Style.AttributeMacros.push_back("UNLIKELY");
22574   Style.AttributeMacros.push_back("LIKELY");
22575   verifyFormat("if (argc > 5) UNLIKELY\n"
22576                "  return 29;\n",
22577                Style);
22578 
22579   verifyFormat("if (argc > 5) UNLIKELY {\n"
22580                "  return 29;\n"
22581                "}",
22582                Style);
22583   verifyFormat("if (argc > 5) UNLIKELY {\n"
22584                "  return 29;\n"
22585                "} else [[likely]] {\n"
22586                "  return 42;\n"
22587                "}\n",
22588                Style);
22589   verifyFormat("if (argc > 5) UNLIKELY {\n"
22590                "  return 29;\n"
22591                "} else LIKELY {\n"
22592                "  return 42;\n"
22593                "}\n",
22594                Style);
22595   verifyFormat("if (argc > 5) [[unlikely]] {\n"
22596                "  return 29;\n"
22597                "} else LIKELY {\n"
22598                "  return 42;\n"
22599                "}\n",
22600                Style);
22601 }
22602 
22603 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
22604   verifyFormat("Constructor()\n"
22605                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
22606                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
22607                "aaaaaaaaaaaaaaaaaat))");
22608   verifyFormat("Constructor()\n"
22609                "    : aaaaaaaaaaaaa(aaaaaa), "
22610                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
22611 
22612   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
22613   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
22614   verifyFormat("Constructor()\n"
22615                "    : aaaaaa(aaaaaa),\n"
22616                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
22617                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
22618                StyleWithWhitespacePenalty);
22619   verifyFormat("Constructor()\n"
22620                "    : aaaaaaaaaaaaa(aaaaaa), "
22621                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
22622                StyleWithWhitespacePenalty);
22623 }
22624 
22625 TEST_F(FormatTest, LLVMDefaultStyle) {
22626   FormatStyle Style = getLLVMStyle();
22627   verifyFormat("extern \"C\" {\n"
22628                "int foo();\n"
22629                "}",
22630                Style);
22631 }
22632 TEST_F(FormatTest, GNUDefaultStyle) {
22633   FormatStyle Style = getGNUStyle();
22634   verifyFormat("extern \"C\"\n"
22635                "{\n"
22636                "  int foo ();\n"
22637                "}",
22638                Style);
22639 }
22640 TEST_F(FormatTest, MozillaDefaultStyle) {
22641   FormatStyle Style = getMozillaStyle();
22642   verifyFormat("extern \"C\"\n"
22643                "{\n"
22644                "  int foo();\n"
22645                "}",
22646                Style);
22647 }
22648 TEST_F(FormatTest, GoogleDefaultStyle) {
22649   FormatStyle Style = getGoogleStyle();
22650   verifyFormat("extern \"C\" {\n"
22651                "int foo();\n"
22652                "}",
22653                Style);
22654 }
22655 TEST_F(FormatTest, ChromiumDefaultStyle) {
22656   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
22657   verifyFormat("extern \"C\" {\n"
22658                "int foo();\n"
22659                "}",
22660                Style);
22661 }
22662 TEST_F(FormatTest, MicrosoftDefaultStyle) {
22663   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
22664   verifyFormat("extern \"C\"\n"
22665                "{\n"
22666                "    int foo();\n"
22667                "}",
22668                Style);
22669 }
22670 TEST_F(FormatTest, WebKitDefaultStyle) {
22671   FormatStyle Style = getWebKitStyle();
22672   verifyFormat("extern \"C\" {\n"
22673                "int foo();\n"
22674                "}",
22675                Style);
22676 }
22677 
22678 TEST_F(FormatTest, ConceptsAndRequires) {
22679   FormatStyle Style = getLLVMStyle();
22680   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
22681 
22682   verifyFormat("template <typename T>\n"
22683                "concept Hashable = requires(T a) {\n"
22684                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22685                "};",
22686                Style);
22687   verifyFormat("template <typename T>\n"
22688                "concept EqualityComparable = requires(T a, T b) {\n"
22689                "  { a == b } -> bool;\n"
22690                "};",
22691                Style);
22692   verifyFormat("template <typename T>\n"
22693                "concept EqualityComparable = requires(T a, T b) {\n"
22694                "  { a == b } -> bool;\n"
22695                "  { a != b } -> bool;\n"
22696                "};",
22697                Style);
22698   verifyFormat("template <typename T>\n"
22699                "concept EqualityComparable = requires(T a, T b) {\n"
22700                "  { a == b } -> bool;\n"
22701                "  { a != b } -> bool;\n"
22702                "};",
22703                Style);
22704 
22705   verifyFormat("template <typename It>\n"
22706                "requires Iterator<It>\n"
22707                "void sort(It begin, It end) {\n"
22708                "  //....\n"
22709                "}",
22710                Style);
22711 
22712   verifyFormat("template <typename T>\n"
22713                "concept Large = sizeof(T) > 10;",
22714                Style);
22715 
22716   verifyFormat("template <typename T, typename U>\n"
22717                "concept FooableWith = requires(T t, U u) {\n"
22718                "  typename T::foo_type;\n"
22719                "  { t.foo(u) } -> typename T::foo_type;\n"
22720                "  t++;\n"
22721                "};\n"
22722                "void doFoo(FooableWith<int> auto t) {\n"
22723                "  t.foo(3);\n"
22724                "}",
22725                Style);
22726   verifyFormat("template <typename T>\n"
22727                "concept Context = sizeof(T) == 1;",
22728                Style);
22729   verifyFormat("template <typename T>\n"
22730                "concept Context = is_specialization_of_v<context, T>;",
22731                Style);
22732   verifyFormat("template <typename T>\n"
22733                "concept Node = std::is_object_v<T>;",
22734                Style);
22735   verifyFormat("template <typename T>\n"
22736                "concept Tree = true;",
22737                Style);
22738 
22739   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
22740                "  //...\n"
22741                "}",
22742                Style);
22743 
22744   verifyFormat(
22745       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
22746       "  //...\n"
22747       "}",
22748       Style);
22749 
22750   verifyFormat(
22751       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
22752       "  //...\n"
22753       "}",
22754       Style);
22755 
22756   verifyFormat("template <typename T>\n"
22757                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
22758                "Concept2<I> {\n"
22759                "  //...\n"
22760                "}",
22761                Style);
22762 
22763   verifyFormat("template <typename T>\n"
22764                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
22765                "Concept2<I> {\n"
22766                "  //...\n"
22767                "}",
22768                Style);
22769 
22770   verifyFormat(
22771       "template <typename T>\n"
22772       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
22773       "  //...\n"
22774       "}",
22775       Style);
22776 
22777   verifyFormat(
22778       "template <typename T>\n"
22779       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
22780       "  //...\n"
22781       "}",
22782       Style);
22783 
22784   verifyFormat("template <typename It>\n"
22785                "requires Foo<It>() && Bar<It> {\n"
22786                "  //....\n"
22787                "}",
22788                Style);
22789 
22790   verifyFormat("template <typename It>\n"
22791                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
22792                "  //....\n"
22793                "}",
22794                Style);
22795 
22796   verifyFormat("template <typename It>\n"
22797                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
22798                "  //....\n"
22799                "}",
22800                Style);
22801 
22802   verifyFormat(
22803       "template <typename It>\n"
22804       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
22805       "  //....\n"
22806       "}",
22807       Style);
22808 
22809   Style.IndentRequires = true;
22810   verifyFormat("template <typename It>\n"
22811                "  requires Iterator<It>\n"
22812                "void sort(It begin, It end) {\n"
22813                "  //....\n"
22814                "}",
22815                Style);
22816   verifyFormat("template <std::size index_>\n"
22817                "  requires(index_ < sizeof...(Children_))\n"
22818                "Tree auto &child() {\n"
22819                "  // ...\n"
22820                "}",
22821                Style);
22822 
22823   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
22824   verifyFormat("template <typename T>\n"
22825                "concept Hashable = requires (T a) {\n"
22826                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22827                "};",
22828                Style);
22829 
22830   verifyFormat("template <class T = void>\n"
22831                "  requires EqualityComparable<T> || Same<T, void>\n"
22832                "struct equal_to;",
22833                Style);
22834 
22835   verifyFormat("template <class T>\n"
22836                "  requires requires {\n"
22837                "    T{};\n"
22838                "    T (int);\n"
22839                "  }\n",
22840                Style);
22841 
22842   Style.ColumnLimit = 78;
22843   verifyFormat("template <typename T>\n"
22844                "concept Context = Traits<typename T::traits_type> and\n"
22845                "    Interface<typename T::interface_type> and\n"
22846                "    Request<typename T::request_type> and\n"
22847                "    Response<typename T::response_type> and\n"
22848                "    ContextExtension<typename T::extension_type> and\n"
22849                "    ::std::is_copy_constructable<T> and "
22850                "::std::is_move_constructable<T> and\n"
22851                "    requires (T c) {\n"
22852                "  { c.response; } -> Response;\n"
22853                "} and requires (T c) {\n"
22854                "  { c.request; } -> Request;\n"
22855                "}\n",
22856                Style);
22857 
22858   verifyFormat("template <typename T>\n"
22859                "concept Context = Traits<typename T::traits_type> or\n"
22860                "    Interface<typename T::interface_type> or\n"
22861                "    Request<typename T::request_type> or\n"
22862                "    Response<typename T::response_type> or\n"
22863                "    ContextExtension<typename T::extension_type> or\n"
22864                "    ::std::is_copy_constructable<T> or "
22865                "::std::is_move_constructable<T> or\n"
22866                "    requires (T c) {\n"
22867                "  { c.response; } -> Response;\n"
22868                "} or requires (T c) {\n"
22869                "  { c.request; } -> Request;\n"
22870                "}\n",
22871                Style);
22872 
22873   verifyFormat("template <typename T>\n"
22874                "concept Context = Traits<typename T::traits_type> &&\n"
22875                "    Interface<typename T::interface_type> &&\n"
22876                "    Request<typename T::request_type> &&\n"
22877                "    Response<typename T::response_type> &&\n"
22878                "    ContextExtension<typename T::extension_type> &&\n"
22879                "    ::std::is_copy_constructable<T> && "
22880                "::std::is_move_constructable<T> &&\n"
22881                "    requires (T c) {\n"
22882                "  { c.response; } -> Response;\n"
22883                "} && requires (T c) {\n"
22884                "  { c.request; } -> Request;\n"
22885                "}\n",
22886                Style);
22887 
22888   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
22889                "Constraint2<T>;");
22890 
22891   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
22892   Style.BraceWrapping.AfterFunction = true;
22893   Style.BraceWrapping.AfterClass = true;
22894   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
22895   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
22896   verifyFormat("void Foo () requires (std::copyable<T>)\n"
22897                "{\n"
22898                "  return\n"
22899                "}\n",
22900                Style);
22901 
22902   verifyFormat("void Foo () requires std::copyable<T>\n"
22903                "{\n"
22904                "  return\n"
22905                "}\n",
22906                Style);
22907 
22908   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22909                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
22910                "struct constant;",
22911                Style);
22912 
22913   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22914                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
22915                "struct constant;",
22916                Style);
22917 
22918   verifyFormat("template <class T>\n"
22919                "class plane_with_very_very_very_long_name\n"
22920                "{\n"
22921                "  constexpr plane_with_very_very_very_long_name () requires "
22922                "std::copyable<T>\n"
22923                "      : plane_with_very_very_very_long_name (1)\n"
22924                "  {\n"
22925                "  }\n"
22926                "}\n",
22927                Style);
22928 
22929   verifyFormat("template <class T>\n"
22930                "class plane_with_long_name\n"
22931                "{\n"
22932                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
22933                "      : plane_with_long_name (1)\n"
22934                "  {\n"
22935                "  }\n"
22936                "}\n",
22937                Style);
22938 
22939   Style.BreakBeforeConceptDeclarations = false;
22940   verifyFormat("template <typename T> concept Tree = true;", Style);
22941 
22942   Style.IndentRequires = false;
22943   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22944                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
22945                "struct constant;",
22946                Style);
22947 }
22948 
22949 TEST_F(FormatTest, StatementAttributeLikeMacros) {
22950   FormatStyle Style = getLLVMStyle();
22951   StringRef Source = "void Foo::slot() {\n"
22952                      "  unsigned char MyChar = 'x';\n"
22953                      "  emit signal(MyChar);\n"
22954                      "  Q_EMIT signal(MyChar);\n"
22955                      "}";
22956 
22957   EXPECT_EQ(Source, format(Source, Style));
22958 
22959   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
22960   EXPECT_EQ("void Foo::slot() {\n"
22961             "  unsigned char MyChar = 'x';\n"
22962             "  emit          signal(MyChar);\n"
22963             "  Q_EMIT signal(MyChar);\n"
22964             "}",
22965             format(Source, Style));
22966 
22967   Style.StatementAttributeLikeMacros.push_back("emit");
22968   EXPECT_EQ(Source, format(Source, Style));
22969 
22970   Style.StatementAttributeLikeMacros = {};
22971   EXPECT_EQ("void Foo::slot() {\n"
22972             "  unsigned char MyChar = 'x';\n"
22973             "  emit          signal(MyChar);\n"
22974             "  Q_EMIT        signal(MyChar);\n"
22975             "}",
22976             format(Source, Style));
22977 }
22978 
22979 TEST_F(FormatTest, IndentAccessModifiers) {
22980   FormatStyle Style = getLLVMStyle();
22981   Style.IndentAccessModifiers = true;
22982   // Members are *two* levels below the record;
22983   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
22984   verifyFormat("class C {\n"
22985                "    int i;\n"
22986                "};\n",
22987                Style);
22988   verifyFormat("union C {\n"
22989                "    int i;\n"
22990                "    unsigned u;\n"
22991                "};\n",
22992                Style);
22993   // Access modifiers should be indented one level below the record.
22994   verifyFormat("class C {\n"
22995                "  public:\n"
22996                "    int i;\n"
22997                "};\n",
22998                Style);
22999   verifyFormat("struct S {\n"
23000                "  private:\n"
23001                "    class C {\n"
23002                "        int j;\n"
23003                "\n"
23004                "      public:\n"
23005                "        C();\n"
23006                "    };\n"
23007                "\n"
23008                "  public:\n"
23009                "    int i;\n"
23010                "};\n",
23011                Style);
23012   // Enumerations are not records and should be unaffected.
23013   Style.AllowShortEnumsOnASingleLine = false;
23014   verifyFormat("enum class E {\n"
23015                "  A,\n"
23016                "  B\n"
23017                "};\n",
23018                Style);
23019   // Test with a different indentation width;
23020   // also proves that the result is Style.AccessModifierOffset agnostic.
23021   Style.IndentWidth = 3;
23022   verifyFormat("class C {\n"
23023                "   public:\n"
23024                "      int i;\n"
23025                "};\n",
23026                Style);
23027 }
23028 
23029 TEST_F(FormatTest, LimitlessStringsAndComments) {
23030   auto Style = getLLVMStyleWithColumns(0);
23031   constexpr StringRef Code =
23032       "/**\n"
23033       " * This is a multiline comment with quite some long lines, at least for "
23034       "the LLVM Style.\n"
23035       " * We will redo this with strings and line comments. Just to  check if "
23036       "everything is working.\n"
23037       " */\n"
23038       "bool foo() {\n"
23039       "  /* Single line multi line comment. */\n"
23040       "  const std::string String = \"This is a multiline string with quite "
23041       "some long lines, at least for the LLVM Style.\"\n"
23042       "                             \"We already did it with multi line "
23043       "comments, and we will do it with line comments. Just to check if "
23044       "everything is working.\";\n"
23045       "  // This is a line comment (block) with quite some long lines, at "
23046       "least for the LLVM Style.\n"
23047       "  // We already did this with multi line comments and strings. Just to "
23048       "check if everything is working.\n"
23049       "  const std::string SmallString = \"Hello World\";\n"
23050       "  // Small line comment\n"
23051       "  return String.size() > SmallString.size();\n"
23052       "}";
23053   EXPECT_EQ(Code, format(Code, Style));
23054 }
23055 
23056 TEST_F(FormatTest, FormatDecayCopy) {
23057   // error cases from unit tests
23058   verifyFormat("foo(auto())");
23059   verifyFormat("foo(auto{})");
23060   verifyFormat("foo(auto({}))");
23061   verifyFormat("foo(auto{{}})");
23062 
23063   verifyFormat("foo(auto(1))");
23064   verifyFormat("foo(auto{1})");
23065   verifyFormat("foo(new auto(1))");
23066   verifyFormat("foo(new auto{1})");
23067   verifyFormat("decltype(auto(1)) x;");
23068   verifyFormat("decltype(auto{1}) x;");
23069   verifyFormat("auto(x);");
23070   verifyFormat("auto{x};");
23071   verifyFormat("new auto{x};");
23072   verifyFormat("auto{x} = y;");
23073   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
23074                                 // the user's own fault
23075   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
23076                                          // clearly the user's own fault
23077   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
23078 }
23079 
23080 TEST_F(FormatTest, Cpp20ModulesSupport) {
23081   FormatStyle Style = getLLVMStyle();
23082   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
23083   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
23084 
23085   verifyFormat("export import foo;", Style);
23086   verifyFormat("export import foo:bar;", Style);
23087   verifyFormat("export import foo.bar;", Style);
23088   verifyFormat("export import foo.bar:baz;", Style);
23089   verifyFormat("export import :bar;", Style);
23090   verifyFormat("export module foo:bar;", Style);
23091   verifyFormat("export module foo;", Style);
23092   verifyFormat("export module foo.bar;", Style);
23093   verifyFormat("export module foo.bar:baz;", Style);
23094   verifyFormat("export import <string_view>;", Style);
23095 
23096   verifyFormat("export type_name var;", Style);
23097   verifyFormat("template <class T> export using A = B<T>;", Style);
23098   verifyFormat("export using A = B;", Style);
23099   verifyFormat("export int func() {\n"
23100                "  foo();\n"
23101                "}",
23102                Style);
23103   verifyFormat("export struct {\n"
23104                "  int foo;\n"
23105                "};",
23106                Style);
23107   verifyFormat("export {\n"
23108                "  int foo;\n"
23109                "};",
23110                Style);
23111   verifyFormat("export export char const *hello() { return \"hello\"; }");
23112 
23113   verifyFormat("import bar;", Style);
23114   verifyFormat("import foo.bar;", Style);
23115   verifyFormat("import foo:bar;", Style);
23116   verifyFormat("import :bar;", Style);
23117   verifyFormat("import <ctime>;", Style);
23118   verifyFormat("import \"header\";", Style);
23119 
23120   verifyFormat("module foo;", Style);
23121   verifyFormat("module foo:bar;", Style);
23122   verifyFormat("module foo.bar;", Style);
23123   verifyFormat("module;", Style);
23124 
23125   verifyFormat("export namespace hi {\n"
23126                "const char *sayhi();\n"
23127                "}",
23128                Style);
23129 
23130   verifyFormat("module :private;", Style);
23131   verifyFormat("import <foo/bar.h>;", Style);
23132   verifyFormat("import foo...bar;", Style);
23133   verifyFormat("import ..........;", Style);
23134   verifyFormat("module foo:private;", Style);
23135   verifyFormat("import a", Style);
23136   verifyFormat("module a", Style);
23137   verifyFormat("export import a", Style);
23138   verifyFormat("export module a", Style);
23139 
23140   verifyFormat("import", Style);
23141   verifyFormat("module", Style);
23142   verifyFormat("export", Style);
23143 }
23144 
23145 TEST_F(FormatTest, CoroutineForCoawait) {
23146   FormatStyle Style = getLLVMStyle();
23147   verifyFormat("for co_await (auto x : range())\n  ;");
23148   verifyFormat("for (auto i : arr) {\n"
23149                "}",
23150                Style);
23151   verifyFormat("for co_await (auto i : arr) {\n"
23152                "}",
23153                Style);
23154   verifyFormat("for co_await (auto i : foo(T{})) {\n"
23155                "}",
23156                Style);
23157 }
23158 
23159 TEST_F(FormatTest, CoroutineCoAwait) {
23160   verifyFormat("int x = co_await foo();");
23161   verifyFormat("int x = (co_await foo());");
23162   verifyFormat("co_await (42);");
23163   verifyFormat("void operator co_await(int);");
23164   verifyFormat("void operator co_await(a);");
23165   verifyFormat("co_await a;");
23166   verifyFormat("co_await missing_await_resume{};");
23167   verifyFormat("co_await a; // comment");
23168   verifyFormat("void test0() { co_await a; }");
23169   verifyFormat("co_await co_await co_await foo();");
23170   verifyFormat("co_await foo().bar();");
23171   verifyFormat("co_await [this]() -> Task { co_return x; }");
23172   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
23173                "foo(); }(x, y);");
23174 
23175   FormatStyle Style = getLLVMStyleWithColumns(40);
23176   verifyFormat("co_await [this](int a, int b) -> Task {\n"
23177                "  co_return co_await foo();\n"
23178                "}(x, y);",
23179                Style);
23180   verifyFormat("co_await;");
23181 }
23182 
23183 TEST_F(FormatTest, CoroutineCoYield) {
23184   verifyFormat("int x = co_yield foo();");
23185   verifyFormat("int x = (co_yield foo());");
23186   verifyFormat("co_yield (42);");
23187   verifyFormat("co_yield {42};");
23188   verifyFormat("co_yield 42;");
23189   verifyFormat("co_yield n++;");
23190   verifyFormat("co_yield ++n;");
23191   verifyFormat("co_yield;");
23192 }
23193 
23194 TEST_F(FormatTest, CoroutineCoReturn) {
23195   verifyFormat("co_return (42);");
23196   verifyFormat("co_return;");
23197   verifyFormat("co_return {};");
23198   verifyFormat("co_return x;");
23199   verifyFormat("co_return co_await foo();");
23200   verifyFormat("co_return co_yield foo();");
23201 }
23202 
23203 TEST_F(FormatTest, EmptyShortBlock) {
23204   auto Style = getLLVMStyle();
23205   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
23206 
23207   verifyFormat("try {\n"
23208                "  doA();\n"
23209                "} catch (Exception &e) {\n"
23210                "  e.printStackTrace();\n"
23211                "}\n",
23212                Style);
23213 
23214   verifyFormat("try {\n"
23215                "  doA();\n"
23216                "} catch (Exception &e) {}\n",
23217                Style);
23218 }
23219 
23220 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
23221   auto Style = getLLVMStyle();
23222 
23223   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
23224   verifyFormat("struct Y<[] { return 0; }> {};", Style);
23225 
23226   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
23227 }
23228 
23229 } // namespace
23230 } // namespace format
23231 } // namespace clang
23232