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 = clang::format::getLLVMStyle();
266   CustomStyle.BreakBeforeBraces = clang::format::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 
1928   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1929   verifyFormat("Const unsigned int *c;\n"
1930                "const unsigned int *d;\n"
1931                "Const unsigned int &e;\n"
1932                "const unsigned int &f;\n"
1933                "const unsigned    &&g;\n"
1934                "Const unsigned      h;",
1935                Style);
1936 
1937   Style.PointerAlignment = FormatStyle::PAS_Left;
1938   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1939   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
1940   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
1941   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
1942   verifyFormat("int* f1(int& a) const& = 0;", Style);
1943   verifyFormat("int* a = f1();", Style);
1944   verifyFormat("int& b = f2();", Style);
1945   verifyFormat("int&& c = f3();", Style);
1946 
1947   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1948   verifyFormat("Const unsigned int* c;\n"
1949                "const unsigned int* d;\n"
1950                "Const unsigned int& e;\n"
1951                "const unsigned int& f;\n"
1952                "const unsigned&&    g;\n"
1953                "Const unsigned      h;",
1954                Style);
1955 
1956   Style.PointerAlignment = FormatStyle::PAS_Right;
1957   Style.ReferenceAlignment = FormatStyle::RAS_Left;
1958   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
1959   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
1960   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
1961   verifyFormat("int *a = f1();", Style);
1962   verifyFormat("int& b = f2();", Style);
1963   verifyFormat("int&& c = f3();", Style);
1964 
1965   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1966   verifyFormat("Const unsigned int *c;\n"
1967                "const unsigned int *d;\n"
1968                "Const unsigned int& e;\n"
1969                "const unsigned int& f;\n"
1970                "const unsigned      g;\n"
1971                "Const unsigned      h;",
1972                Style);
1973 
1974   Style.PointerAlignment = FormatStyle::PAS_Left;
1975   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
1976   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
1977   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
1978   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
1979   verifyFormat("int* a = f1();", Style);
1980   verifyFormat("int & b = f2();", Style);
1981   verifyFormat("int && c = f3();", Style);
1982 
1983   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1984   verifyFormat("Const unsigned int*  c;\n"
1985                "const unsigned int*  d;\n"
1986                "Const unsigned int & e;\n"
1987                "const unsigned int & f;\n"
1988                "const unsigned &&    g;\n"
1989                "Const unsigned       h;",
1990                Style);
1991 
1992   Style.PointerAlignment = FormatStyle::PAS_Middle;
1993   Style.ReferenceAlignment = FormatStyle::RAS_Right;
1994   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
1995   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
1996   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
1997   verifyFormat("int * a = f1();", Style);
1998   verifyFormat("int &b = f2();", Style);
1999   verifyFormat("int &&c = f3();", Style);
2000 
2001   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2002   // specifically handled
2003   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2004 }
2005 
2006 TEST_F(FormatTest, FormatsForLoop) {
2007   verifyFormat(
2008       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2009       "     ++VeryVeryLongLoopVariable)\n"
2010       "  ;");
2011   verifyFormat("for (;;)\n"
2012                "  f();");
2013   verifyFormat("for (;;) {\n}");
2014   verifyFormat("for (;;) {\n"
2015                "  f();\n"
2016                "}");
2017   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2018 
2019   verifyFormat(
2020       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2021       "                                          E = UnwrappedLines.end();\n"
2022       "     I != E; ++I) {\n}");
2023 
2024   verifyFormat(
2025       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2026       "     ++IIIII) {\n}");
2027   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2028                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2029                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2030   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2031                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2032                "         E = FD->getDeclsInPrototypeScope().end();\n"
2033                "     I != E; ++I) {\n}");
2034   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2035                "         I = Container.begin(),\n"
2036                "         E = Container.end();\n"
2037                "     I != E; ++I) {\n}",
2038                getLLVMStyleWithColumns(76));
2039 
2040   verifyFormat(
2041       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2042       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2043       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2044       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2045       "     ++aaaaaaaaaaa) {\n}");
2046   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2047                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2048                "     ++i) {\n}");
2049   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2050                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2051                "}");
2052   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2053                "         aaaaaaaaaa);\n"
2054                "     iter; ++iter) {\n"
2055                "}");
2056   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2057                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2058                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2059                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2060 
2061   // These should not be formatted as Objective-C for-in loops.
2062   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2063   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2064   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2065   verifyFormat(
2066       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2067 
2068   FormatStyle NoBinPacking = getLLVMStyle();
2069   NoBinPacking.BinPackParameters = false;
2070   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2071                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2072                "                                           aaaaaaaaaaaaaaaa,\n"
2073                "                                           aaaaaaaaaaaaaaaa,\n"
2074                "                                           aaaaaaaaaaaaaaaa);\n"
2075                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2076                "}",
2077                NoBinPacking);
2078   verifyFormat(
2079       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2080       "                                          E = UnwrappedLines.end();\n"
2081       "     I != E;\n"
2082       "     ++I) {\n}",
2083       NoBinPacking);
2084 
2085   FormatStyle AlignLeft = getLLVMStyle();
2086   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2087   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2088 }
2089 
2090 TEST_F(FormatTest, RangeBasedForLoops) {
2091   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2092                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2093   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2094                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2095   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2096                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2097   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2098                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2099 }
2100 
2101 TEST_F(FormatTest, ForEachLoops) {
2102   verifyFormat("void f() {\n"
2103                "  foreach (Item *item, itemlist) {}\n"
2104                "  Q_FOREACH (Item *item, itemlist) {}\n"
2105                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
2106                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
2107                "}");
2108 
2109   FormatStyle Style = getLLVMStyle();
2110   Style.SpaceBeforeParens =
2111       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2112   verifyFormat("void f() {\n"
2113                "  foreach(Item *item, itemlist) {}\n"
2114                "  Q_FOREACH(Item *item, itemlist) {}\n"
2115                "  BOOST_FOREACH(Item *item, itemlist) {}\n"
2116                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
2117                "}",
2118                Style);
2119 
2120   // As function-like macros.
2121   verifyFormat("#define foreach(x, y)\n"
2122                "#define Q_FOREACH(x, y)\n"
2123                "#define BOOST_FOREACH(x, y)\n"
2124                "#define UNKNOWN_FOREACH(x, y)\n");
2125 
2126   // Not as function-like macros.
2127   verifyFormat("#define foreach (x, y)\n"
2128                "#define Q_FOREACH (x, y)\n"
2129                "#define BOOST_FOREACH (x, y)\n"
2130                "#define UNKNOWN_FOREACH (x, y)\n");
2131 
2132   // handle microsoft non standard extension
2133   verifyFormat("for each (char c in x->MyStringProperty)");
2134 }
2135 
2136 TEST_F(FormatTest, FormatsWhileLoop) {
2137   verifyFormat("while (true) {\n}");
2138   verifyFormat("while (true)\n"
2139                "  f();");
2140   verifyFormat("while () {\n}");
2141   verifyFormat("while () {\n"
2142                "  f();\n"
2143                "}");
2144 }
2145 
2146 TEST_F(FormatTest, FormatsDoWhile) {
2147   verifyFormat("do {\n"
2148                "  do_something();\n"
2149                "} while (something());");
2150   verifyFormat("do\n"
2151                "  do_something();\n"
2152                "while (something());");
2153 }
2154 
2155 TEST_F(FormatTest, FormatsSwitchStatement) {
2156   verifyFormat("switch (x) {\n"
2157                "case 1:\n"
2158                "  f();\n"
2159                "  break;\n"
2160                "case kFoo:\n"
2161                "case ns::kBar:\n"
2162                "case kBaz:\n"
2163                "  break;\n"
2164                "default:\n"
2165                "  g();\n"
2166                "  break;\n"
2167                "}");
2168   verifyFormat("switch (x) {\n"
2169                "case 1: {\n"
2170                "  f();\n"
2171                "  break;\n"
2172                "}\n"
2173                "case 2: {\n"
2174                "  break;\n"
2175                "}\n"
2176                "}");
2177   verifyFormat("switch (x) {\n"
2178                "case 1: {\n"
2179                "  f();\n"
2180                "  {\n"
2181                "    g();\n"
2182                "    h();\n"
2183                "  }\n"
2184                "  break;\n"
2185                "}\n"
2186                "}");
2187   verifyFormat("switch (x) {\n"
2188                "case 1: {\n"
2189                "  f();\n"
2190                "  if (foo) {\n"
2191                "    g();\n"
2192                "    h();\n"
2193                "  }\n"
2194                "  break;\n"
2195                "}\n"
2196                "}");
2197   verifyFormat("switch (x) {\n"
2198                "case 1: {\n"
2199                "  f();\n"
2200                "  g();\n"
2201                "} break;\n"
2202                "}");
2203   verifyFormat("switch (test)\n"
2204                "  ;");
2205   verifyFormat("switch (x) {\n"
2206                "default: {\n"
2207                "  // Do nothing.\n"
2208                "}\n"
2209                "}");
2210   verifyFormat("switch (x) {\n"
2211                "// comment\n"
2212                "// if 1, do f()\n"
2213                "case 1:\n"
2214                "  f();\n"
2215                "}");
2216   verifyFormat("switch (x) {\n"
2217                "case 1:\n"
2218                "  // Do amazing stuff\n"
2219                "  {\n"
2220                "    f();\n"
2221                "    g();\n"
2222                "  }\n"
2223                "  break;\n"
2224                "}");
2225   verifyFormat("#define A          \\\n"
2226                "  switch (x) {     \\\n"
2227                "  case a:          \\\n"
2228                "    foo = b;       \\\n"
2229                "  }",
2230                getLLVMStyleWithColumns(20));
2231   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2232                "  case OP_name:                        \\\n"
2233                "    return operations::Operation##name\n",
2234                getLLVMStyleWithColumns(40));
2235   verifyFormat("switch (x) {\n"
2236                "case 1:;\n"
2237                "default:;\n"
2238                "  int i;\n"
2239                "}");
2240 
2241   verifyGoogleFormat("switch (x) {\n"
2242                      "  case 1:\n"
2243                      "    f();\n"
2244                      "    break;\n"
2245                      "  case kFoo:\n"
2246                      "  case ns::kBar:\n"
2247                      "  case kBaz:\n"
2248                      "    break;\n"
2249                      "  default:\n"
2250                      "    g();\n"
2251                      "    break;\n"
2252                      "}");
2253   verifyGoogleFormat("switch (x) {\n"
2254                      "  case 1: {\n"
2255                      "    f();\n"
2256                      "    break;\n"
2257                      "  }\n"
2258                      "}");
2259   verifyGoogleFormat("switch (test)\n"
2260                      "  ;");
2261 
2262   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2263                      "  case OP_name:              \\\n"
2264                      "    return operations::Operation##name\n");
2265   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2266                      "  // Get the correction operation class.\n"
2267                      "  switch (OpCode) {\n"
2268                      "    CASE(Add);\n"
2269                      "    CASE(Subtract);\n"
2270                      "    default:\n"
2271                      "      return operations::Unknown;\n"
2272                      "  }\n"
2273                      "#undef OPERATION_CASE\n"
2274                      "}");
2275   verifyFormat("DEBUG({\n"
2276                "  switch (x) {\n"
2277                "  case A:\n"
2278                "    f();\n"
2279                "    break;\n"
2280                "    // fallthrough\n"
2281                "  case B:\n"
2282                "    g();\n"
2283                "    break;\n"
2284                "  }\n"
2285                "});");
2286   EXPECT_EQ("DEBUG({\n"
2287             "  switch (x) {\n"
2288             "  case A:\n"
2289             "    f();\n"
2290             "    break;\n"
2291             "  // On B:\n"
2292             "  case B:\n"
2293             "    g();\n"
2294             "    break;\n"
2295             "  }\n"
2296             "});",
2297             format("DEBUG({\n"
2298                    "  switch (x) {\n"
2299                    "  case A:\n"
2300                    "    f();\n"
2301                    "    break;\n"
2302                    "  // On B:\n"
2303                    "  case B:\n"
2304                    "    g();\n"
2305                    "    break;\n"
2306                    "  }\n"
2307                    "});",
2308                    getLLVMStyle()));
2309   EXPECT_EQ("switch (n) {\n"
2310             "case 0: {\n"
2311             "  return false;\n"
2312             "}\n"
2313             "default: {\n"
2314             "  return true;\n"
2315             "}\n"
2316             "}",
2317             format("switch (n)\n"
2318                    "{\n"
2319                    "case 0: {\n"
2320                    "  return false;\n"
2321                    "}\n"
2322                    "default: {\n"
2323                    "  return true;\n"
2324                    "}\n"
2325                    "}",
2326                    getLLVMStyle()));
2327   verifyFormat("switch (a) {\n"
2328                "case (b):\n"
2329                "  return;\n"
2330                "}");
2331 
2332   verifyFormat("switch (a) {\n"
2333                "case some_namespace::\n"
2334                "    some_constant:\n"
2335                "  return;\n"
2336                "}",
2337                getLLVMStyleWithColumns(34));
2338 
2339   FormatStyle Style = getLLVMStyle();
2340   Style.IndentCaseLabels = true;
2341   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2342   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2343   Style.BraceWrapping.AfterCaseLabel = true;
2344   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2345   EXPECT_EQ("switch (n)\n"
2346             "{\n"
2347             "  case 0:\n"
2348             "  {\n"
2349             "    return false;\n"
2350             "  }\n"
2351             "  default:\n"
2352             "  {\n"
2353             "    return true;\n"
2354             "  }\n"
2355             "}",
2356             format("switch (n) {\n"
2357                    "  case 0: {\n"
2358                    "    return false;\n"
2359                    "  }\n"
2360                    "  default: {\n"
2361                    "    return true;\n"
2362                    "  }\n"
2363                    "}",
2364                    Style));
2365   Style.BraceWrapping.AfterCaseLabel = false;
2366   EXPECT_EQ("switch (n)\n"
2367             "{\n"
2368             "  case 0: {\n"
2369             "    return false;\n"
2370             "  }\n"
2371             "  default: {\n"
2372             "    return true;\n"
2373             "  }\n"
2374             "}",
2375             format("switch (n) {\n"
2376                    "  case 0:\n"
2377                    "  {\n"
2378                    "    return false;\n"
2379                    "  }\n"
2380                    "  default:\n"
2381                    "  {\n"
2382                    "    return true;\n"
2383                    "  }\n"
2384                    "}",
2385                    Style));
2386   Style.IndentCaseLabels = false;
2387   Style.IndentCaseBlocks = true;
2388   EXPECT_EQ("switch (n)\n"
2389             "{\n"
2390             "case 0:\n"
2391             "  {\n"
2392             "    return false;\n"
2393             "  }\n"
2394             "case 1:\n"
2395             "  break;\n"
2396             "default:\n"
2397             "  {\n"
2398             "    return true;\n"
2399             "  }\n"
2400             "}",
2401             format("switch (n) {\n"
2402                    "case 0: {\n"
2403                    "  return false;\n"
2404                    "}\n"
2405                    "case 1:\n"
2406                    "  break;\n"
2407                    "default: {\n"
2408                    "  return true;\n"
2409                    "}\n"
2410                    "}",
2411                    Style));
2412   Style.IndentCaseLabels = true;
2413   Style.IndentCaseBlocks = true;
2414   EXPECT_EQ("switch (n)\n"
2415             "{\n"
2416             "  case 0:\n"
2417             "    {\n"
2418             "      return false;\n"
2419             "    }\n"
2420             "  case 1:\n"
2421             "    break;\n"
2422             "  default:\n"
2423             "    {\n"
2424             "      return true;\n"
2425             "    }\n"
2426             "}",
2427             format("switch (n) {\n"
2428                    "case 0: {\n"
2429                    "  return false;\n"
2430                    "}\n"
2431                    "case 1:\n"
2432                    "  break;\n"
2433                    "default: {\n"
2434                    "  return true;\n"
2435                    "}\n"
2436                    "}",
2437                    Style));
2438 }
2439 
2440 TEST_F(FormatTest, CaseRanges) {
2441   verifyFormat("switch (x) {\n"
2442                "case 'A' ... 'Z':\n"
2443                "case 1 ... 5:\n"
2444                "case a ... b:\n"
2445                "  break;\n"
2446                "}");
2447 }
2448 
2449 TEST_F(FormatTest, ShortEnums) {
2450   FormatStyle Style = getLLVMStyle();
2451   Style.AllowShortEnumsOnASingleLine = true;
2452   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2453   Style.AllowShortEnumsOnASingleLine = false;
2454   verifyFormat("enum {\n"
2455                "  A,\n"
2456                "  B,\n"
2457                "  C\n"
2458                "} ShortEnum1, ShortEnum2;",
2459                Style);
2460   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2461   Style.BraceWrapping.AfterEnum = true;
2462   verifyFormat("enum\n"
2463                "{\n"
2464                "  A,\n"
2465                "  B,\n"
2466                "  C\n"
2467                "} ShortEnum1, ShortEnum2;",
2468                Style);
2469 }
2470 
2471 TEST_F(FormatTest, ShortCaseLabels) {
2472   FormatStyle Style = getLLVMStyle();
2473   Style.AllowShortCaseLabelsOnASingleLine = true;
2474   verifyFormat("switch (a) {\n"
2475                "case 1: x = 1; break;\n"
2476                "case 2: return;\n"
2477                "case 3:\n"
2478                "case 4:\n"
2479                "case 5: return;\n"
2480                "case 6: // comment\n"
2481                "  return;\n"
2482                "case 7:\n"
2483                "  // comment\n"
2484                "  return;\n"
2485                "case 8:\n"
2486                "  x = 8; // comment\n"
2487                "  break;\n"
2488                "default: y = 1; break;\n"
2489                "}",
2490                Style);
2491   verifyFormat("switch (a) {\n"
2492                "case 0: return; // comment\n"
2493                "case 1: break;  // comment\n"
2494                "case 2: return;\n"
2495                "// comment\n"
2496                "case 3: return;\n"
2497                "// comment 1\n"
2498                "// comment 2\n"
2499                "// comment 3\n"
2500                "case 4: break; /* comment */\n"
2501                "case 5:\n"
2502                "  // comment\n"
2503                "  break;\n"
2504                "case 6: /* comment */ x = 1; break;\n"
2505                "case 7: x = /* comment */ 1; break;\n"
2506                "case 8:\n"
2507                "  x = 1; /* comment */\n"
2508                "  break;\n"
2509                "case 9:\n"
2510                "  break; // comment line 1\n"
2511                "         // comment line 2\n"
2512                "}",
2513                Style);
2514   EXPECT_EQ("switch (a) {\n"
2515             "case 1:\n"
2516             "  x = 8;\n"
2517             "  // fall through\n"
2518             "case 2: x = 8;\n"
2519             "// comment\n"
2520             "case 3:\n"
2521             "  return; /* comment line 1\n"
2522             "           * comment line 2 */\n"
2523             "case 4: i = 8;\n"
2524             "// something else\n"
2525             "#if FOO\n"
2526             "case 5: break;\n"
2527             "#endif\n"
2528             "}",
2529             format("switch (a) {\n"
2530                    "case 1: x = 8;\n"
2531                    "  // fall through\n"
2532                    "case 2:\n"
2533                    "  x = 8;\n"
2534                    "// comment\n"
2535                    "case 3:\n"
2536                    "  return; /* comment line 1\n"
2537                    "           * comment line 2 */\n"
2538                    "case 4:\n"
2539                    "  i = 8;\n"
2540                    "// something else\n"
2541                    "#if FOO\n"
2542                    "case 5: break;\n"
2543                    "#endif\n"
2544                    "}",
2545                    Style));
2546   EXPECT_EQ("switch (a) {\n"
2547             "case 0:\n"
2548             "  return; // long long long long long long long long long long "
2549             "long long comment\n"
2550             "          // line\n"
2551             "}",
2552             format("switch (a) {\n"
2553                    "case 0: return; // long long long long long long long long "
2554                    "long long long long comment line\n"
2555                    "}",
2556                    Style));
2557   EXPECT_EQ("switch (a) {\n"
2558             "case 0:\n"
2559             "  return; /* long long long long long long long long long long "
2560             "long long comment\n"
2561             "             line */\n"
2562             "}",
2563             format("switch (a) {\n"
2564                    "case 0: return; /* long long long long long long long long "
2565                    "long long long long comment line */\n"
2566                    "}",
2567                    Style));
2568   verifyFormat("switch (a) {\n"
2569                "#if FOO\n"
2570                "case 0: return 0;\n"
2571                "#endif\n"
2572                "}",
2573                Style);
2574   verifyFormat("switch (a) {\n"
2575                "case 1: {\n"
2576                "}\n"
2577                "case 2: {\n"
2578                "  return;\n"
2579                "}\n"
2580                "case 3: {\n"
2581                "  x = 1;\n"
2582                "  return;\n"
2583                "}\n"
2584                "case 4:\n"
2585                "  if (x)\n"
2586                "    return;\n"
2587                "}",
2588                Style);
2589   Style.ColumnLimit = 21;
2590   verifyFormat("switch (a) {\n"
2591                "case 1: x = 1; break;\n"
2592                "case 2: return;\n"
2593                "case 3:\n"
2594                "case 4:\n"
2595                "case 5: return;\n"
2596                "default:\n"
2597                "  y = 1;\n"
2598                "  break;\n"
2599                "}",
2600                Style);
2601   Style.ColumnLimit = 80;
2602   Style.AllowShortCaseLabelsOnASingleLine = false;
2603   Style.IndentCaseLabels = true;
2604   EXPECT_EQ("switch (n) {\n"
2605             "  default /*comments*/:\n"
2606             "    return true;\n"
2607             "  case 0:\n"
2608             "    return false;\n"
2609             "}",
2610             format("switch (n) {\n"
2611                    "default/*comments*/:\n"
2612                    "  return true;\n"
2613                    "case 0:\n"
2614                    "  return false;\n"
2615                    "}",
2616                    Style));
2617   Style.AllowShortCaseLabelsOnASingleLine = true;
2618   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2619   Style.BraceWrapping.AfterCaseLabel = true;
2620   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2621   EXPECT_EQ("switch (n)\n"
2622             "{\n"
2623             "  case 0:\n"
2624             "  {\n"
2625             "    return false;\n"
2626             "  }\n"
2627             "  default:\n"
2628             "  {\n"
2629             "    return true;\n"
2630             "  }\n"
2631             "}",
2632             format("switch (n) {\n"
2633                    "  case 0: {\n"
2634                    "    return false;\n"
2635                    "  }\n"
2636                    "  default:\n"
2637                    "  {\n"
2638                    "    return true;\n"
2639                    "  }\n"
2640                    "}",
2641                    Style));
2642 }
2643 
2644 TEST_F(FormatTest, FormatsLabels) {
2645   verifyFormat("void f() {\n"
2646                "  some_code();\n"
2647                "test_label:\n"
2648                "  some_other_code();\n"
2649                "  {\n"
2650                "    some_more_code();\n"
2651                "  another_label:\n"
2652                "    some_more_code();\n"
2653                "  }\n"
2654                "}");
2655   verifyFormat("{\n"
2656                "  some_code();\n"
2657                "test_label:\n"
2658                "  some_other_code();\n"
2659                "}");
2660   verifyFormat("{\n"
2661                "  some_code();\n"
2662                "test_label:;\n"
2663                "  int i = 0;\n"
2664                "}");
2665   FormatStyle Style = getLLVMStyle();
2666   Style.IndentGotoLabels = false;
2667   verifyFormat("void f() {\n"
2668                "  some_code();\n"
2669                "test_label:\n"
2670                "  some_other_code();\n"
2671                "  {\n"
2672                "    some_more_code();\n"
2673                "another_label:\n"
2674                "    some_more_code();\n"
2675                "  }\n"
2676                "}",
2677                Style);
2678   verifyFormat("{\n"
2679                "  some_code();\n"
2680                "test_label:\n"
2681                "  some_other_code();\n"
2682                "}",
2683                Style);
2684   verifyFormat("{\n"
2685                "  some_code();\n"
2686                "test_label:;\n"
2687                "  int i = 0;\n"
2688                "}");
2689 }
2690 
2691 TEST_F(FormatTest, MultiLineControlStatements) {
2692   FormatStyle Style = getLLVMStyle();
2693   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2694   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2695   Style.ColumnLimit = 20;
2696   // Short lines should keep opening brace on same line.
2697   EXPECT_EQ("if (foo) {\n"
2698             "  bar();\n"
2699             "}",
2700             format("if(foo){bar();}", Style));
2701   EXPECT_EQ("if (foo) {\n"
2702             "  bar();\n"
2703             "} else {\n"
2704             "  baz();\n"
2705             "}",
2706             format("if(foo){bar();}else{baz();}", Style));
2707   EXPECT_EQ("if (foo && bar) {\n"
2708             "  baz();\n"
2709             "}",
2710             format("if(foo&&bar){baz();}", Style));
2711   EXPECT_EQ("if (foo) {\n"
2712             "  bar();\n"
2713             "} else if (baz) {\n"
2714             "  quux();\n"
2715             "}",
2716             format("if(foo){bar();}else if(baz){quux();}", Style));
2717   EXPECT_EQ(
2718       "if (foo) {\n"
2719       "  bar();\n"
2720       "} else if (baz) {\n"
2721       "  quux();\n"
2722       "} else {\n"
2723       "  foobar();\n"
2724       "}",
2725       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
2726   EXPECT_EQ("for (;;) {\n"
2727             "  foo();\n"
2728             "}",
2729             format("for(;;){foo();}"));
2730   EXPECT_EQ("while (1) {\n"
2731             "  foo();\n"
2732             "}",
2733             format("while(1){foo();}", Style));
2734   EXPECT_EQ("switch (foo) {\n"
2735             "case bar:\n"
2736             "  return;\n"
2737             "}",
2738             format("switch(foo){case bar:return;}", Style));
2739   EXPECT_EQ("try {\n"
2740             "  foo();\n"
2741             "} catch (...) {\n"
2742             "  bar();\n"
2743             "}",
2744             format("try{foo();}catch(...){bar();}", Style));
2745   EXPECT_EQ("do {\n"
2746             "  foo();\n"
2747             "} while (bar &&\n"
2748             "         baz);",
2749             format("do{foo();}while(bar&&baz);", Style));
2750   // Long lines should put opening brace on new line.
2751   EXPECT_EQ("if (foo && bar &&\n"
2752             "    baz)\n"
2753             "{\n"
2754             "  quux();\n"
2755             "}",
2756             format("if(foo&&bar&&baz){quux();}", Style));
2757   EXPECT_EQ("if (foo && bar &&\n"
2758             "    baz)\n"
2759             "{\n"
2760             "  quux();\n"
2761             "}",
2762             format("if (foo && bar &&\n"
2763                    "    baz) {\n"
2764                    "  quux();\n"
2765                    "}",
2766                    Style));
2767   EXPECT_EQ("if (foo) {\n"
2768             "  bar();\n"
2769             "} else if (baz ||\n"
2770             "           quux)\n"
2771             "{\n"
2772             "  foobar();\n"
2773             "}",
2774             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
2775   EXPECT_EQ(
2776       "if (foo) {\n"
2777       "  bar();\n"
2778       "} else if (baz ||\n"
2779       "           quux)\n"
2780       "{\n"
2781       "  foobar();\n"
2782       "} else {\n"
2783       "  barbaz();\n"
2784       "}",
2785       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2786              Style));
2787   EXPECT_EQ("for (int i = 0;\n"
2788             "     i < 10; ++i)\n"
2789             "{\n"
2790             "  foo();\n"
2791             "}",
2792             format("for(int i=0;i<10;++i){foo();}", Style));
2793   EXPECT_EQ("foreach (int i,\n"
2794             "         list)\n"
2795             "{\n"
2796             "  foo();\n"
2797             "}",
2798             format("foreach(int i, list){foo();}", Style));
2799   Style.ColumnLimit =
2800       40; // to concentrate at brace wrapping, not line wrap due to column limit
2801   EXPECT_EQ("foreach (int i, list) {\n"
2802             "  foo();\n"
2803             "}",
2804             format("foreach(int i, list){foo();}", Style));
2805   Style.ColumnLimit =
2806       20; // to concentrate at brace wrapping, not line wrap due to column limit
2807   EXPECT_EQ("while (foo || bar ||\n"
2808             "       baz)\n"
2809             "{\n"
2810             "  quux();\n"
2811             "}",
2812             format("while(foo||bar||baz){quux();}", Style));
2813   EXPECT_EQ("switch (\n"
2814             "    foo = barbaz)\n"
2815             "{\n"
2816             "case quux:\n"
2817             "  return;\n"
2818             "}",
2819             format("switch(foo=barbaz){case quux:return;}", Style));
2820   EXPECT_EQ("try {\n"
2821             "  foo();\n"
2822             "} catch (\n"
2823             "    Exception &bar)\n"
2824             "{\n"
2825             "  baz();\n"
2826             "}",
2827             format("try{foo();}catch(Exception&bar){baz();}", Style));
2828   Style.ColumnLimit =
2829       40; // to concentrate at brace wrapping, not line wrap due to column limit
2830   EXPECT_EQ("try {\n"
2831             "  foo();\n"
2832             "} catch (Exception &bar) {\n"
2833             "  baz();\n"
2834             "}",
2835             format("try{foo();}catch(Exception&bar){baz();}", Style));
2836   Style.ColumnLimit =
2837       20; // to concentrate at brace wrapping, not line wrap due to column limit
2838 
2839   Style.BraceWrapping.BeforeElse = true;
2840   EXPECT_EQ(
2841       "if (foo) {\n"
2842       "  bar();\n"
2843       "}\n"
2844       "else if (baz ||\n"
2845       "         quux)\n"
2846       "{\n"
2847       "  foobar();\n"
2848       "}\n"
2849       "else {\n"
2850       "  barbaz();\n"
2851       "}",
2852       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2853              Style));
2854 
2855   Style.BraceWrapping.BeforeCatch = true;
2856   EXPECT_EQ("try {\n"
2857             "  foo();\n"
2858             "}\n"
2859             "catch (...) {\n"
2860             "  baz();\n"
2861             "}",
2862             format("try{foo();}catch(...){baz();}", Style));
2863 }
2864 
2865 TEST_F(FormatTest, BeforeWhile) {
2866   FormatStyle Style = getLLVMStyle();
2867   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2868 
2869   verifyFormat("do {\n"
2870                "  foo();\n"
2871                "} while (1);",
2872                Style);
2873   Style.BraceWrapping.BeforeWhile = true;
2874   verifyFormat("do {\n"
2875                "  foo();\n"
2876                "}\n"
2877                "while (1);",
2878                Style);
2879 }
2880 
2881 //===----------------------------------------------------------------------===//
2882 // Tests for classes, namespaces, etc.
2883 //===----------------------------------------------------------------------===//
2884 
2885 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
2886   verifyFormat("class A {};");
2887 }
2888 
2889 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
2890   verifyFormat("class A {\n"
2891                "public:\n"
2892                "public: // comment\n"
2893                "protected:\n"
2894                "private:\n"
2895                "  void f() {}\n"
2896                "};");
2897   verifyFormat("export class A {\n"
2898                "public:\n"
2899                "public: // comment\n"
2900                "protected:\n"
2901                "private:\n"
2902                "  void f() {}\n"
2903                "};");
2904   verifyGoogleFormat("class A {\n"
2905                      " public:\n"
2906                      " protected:\n"
2907                      " private:\n"
2908                      "  void f() {}\n"
2909                      "};");
2910   verifyGoogleFormat("export class A {\n"
2911                      " public:\n"
2912                      " protected:\n"
2913                      " private:\n"
2914                      "  void f() {}\n"
2915                      "};");
2916   verifyFormat("class A {\n"
2917                "public slots:\n"
2918                "  void f1() {}\n"
2919                "public Q_SLOTS:\n"
2920                "  void f2() {}\n"
2921                "protected slots:\n"
2922                "  void f3() {}\n"
2923                "protected Q_SLOTS:\n"
2924                "  void f4() {}\n"
2925                "private slots:\n"
2926                "  void f5() {}\n"
2927                "private Q_SLOTS:\n"
2928                "  void f6() {}\n"
2929                "signals:\n"
2930                "  void g1();\n"
2931                "Q_SIGNALS:\n"
2932                "  void g2();\n"
2933                "};");
2934 
2935   // Don't interpret 'signals' the wrong way.
2936   verifyFormat("signals.set();");
2937   verifyFormat("for (Signals signals : f()) {\n}");
2938   verifyFormat("{\n"
2939                "  signals.set(); // This needs indentation.\n"
2940                "}");
2941   verifyFormat("void f() {\n"
2942                "label:\n"
2943                "  signals.baz();\n"
2944                "}");
2945 }
2946 
2947 TEST_F(FormatTest, SeparatesLogicalBlocks) {
2948   EXPECT_EQ("class A {\n"
2949             "public:\n"
2950             "  void f();\n"
2951             "\n"
2952             "private:\n"
2953             "  void g() {}\n"
2954             "  // test\n"
2955             "protected:\n"
2956             "  int h;\n"
2957             "};",
2958             format("class A {\n"
2959                    "public:\n"
2960                    "void f();\n"
2961                    "private:\n"
2962                    "void g() {}\n"
2963                    "// test\n"
2964                    "protected:\n"
2965                    "int h;\n"
2966                    "};"));
2967   EXPECT_EQ("class A {\n"
2968             "protected:\n"
2969             "public:\n"
2970             "  void f();\n"
2971             "};",
2972             format("class A {\n"
2973                    "protected:\n"
2974                    "\n"
2975                    "public:\n"
2976                    "\n"
2977                    "  void f();\n"
2978                    "};"));
2979 
2980   // Even ensure proper spacing inside macros.
2981   EXPECT_EQ("#define B     \\\n"
2982             "  class A {   \\\n"
2983             "   protected: \\\n"
2984             "   public:    \\\n"
2985             "    void f(); \\\n"
2986             "  };",
2987             format("#define B     \\\n"
2988                    "  class A {   \\\n"
2989                    "   protected: \\\n"
2990                    "              \\\n"
2991                    "   public:    \\\n"
2992                    "              \\\n"
2993                    "    void f(); \\\n"
2994                    "  };",
2995                    getGoogleStyle()));
2996   // But don't remove empty lines after macros ending in access specifiers.
2997   EXPECT_EQ("#define A private:\n"
2998             "\n"
2999             "int i;",
3000             format("#define A         private:\n"
3001                    "\n"
3002                    "int              i;"));
3003 }
3004 
3005 TEST_F(FormatTest, FormatsClasses) {
3006   verifyFormat("class A : public B {};");
3007   verifyFormat("class A : public ::B {};");
3008 
3009   verifyFormat(
3010       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3011       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3012   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3013                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3014                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3015   verifyFormat(
3016       "class A : public B, public C, public D, public E, public F {};");
3017   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3018                "                     public C,\n"
3019                "                     public D,\n"
3020                "                     public E,\n"
3021                "                     public F,\n"
3022                "                     public G {};");
3023 
3024   verifyFormat("class\n"
3025                "    ReallyReallyLongClassName {\n"
3026                "  int i;\n"
3027                "};",
3028                getLLVMStyleWithColumns(32));
3029   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3030                "                           aaaaaaaaaaaaaaaa> {};");
3031   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3032                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3033                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3034   verifyFormat("template <class R, class C>\n"
3035                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3036                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3037   verifyFormat("class ::A::B {};");
3038 }
3039 
3040 TEST_F(FormatTest, BreakInheritanceStyle) {
3041   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3042   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3043       FormatStyle::BILS_BeforeComma;
3044   verifyFormat("class MyClass : public X {};",
3045                StyleWithInheritanceBreakBeforeComma);
3046   verifyFormat("class MyClass\n"
3047                "    : public X\n"
3048                "    , public Y {};",
3049                StyleWithInheritanceBreakBeforeComma);
3050   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3051                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3052                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3053                StyleWithInheritanceBreakBeforeComma);
3054   verifyFormat("struct aaaaaaaaaaaaa\n"
3055                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3056                "          aaaaaaaaaaaaaaaa> {};",
3057                StyleWithInheritanceBreakBeforeComma);
3058 
3059   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3060   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3061       FormatStyle::BILS_AfterColon;
3062   verifyFormat("class MyClass : public X {};",
3063                StyleWithInheritanceBreakAfterColon);
3064   verifyFormat("class MyClass : public X, public Y {};",
3065                StyleWithInheritanceBreakAfterColon);
3066   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3067                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3068                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3069                StyleWithInheritanceBreakAfterColon);
3070   verifyFormat("struct aaaaaaaaaaaaa :\n"
3071                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3072                "        aaaaaaaaaaaaaaaa> {};",
3073                StyleWithInheritanceBreakAfterColon);
3074 
3075   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3076   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3077       FormatStyle::BILS_AfterComma;
3078   verifyFormat("class MyClass : public X {};",
3079                StyleWithInheritanceBreakAfterComma);
3080   verifyFormat("class MyClass : public X,\n"
3081                "                public Y {};",
3082                StyleWithInheritanceBreakAfterComma);
3083   verifyFormat(
3084       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3085       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3086       "{};",
3087       StyleWithInheritanceBreakAfterComma);
3088   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3089                "                           aaaaaaaaaaaaaaaa> {};",
3090                StyleWithInheritanceBreakAfterComma);
3091   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3092                "    : public OnceBreak,\n"
3093                "      public AlwaysBreak,\n"
3094                "      EvenBasesFitInOneLine {};",
3095                StyleWithInheritanceBreakAfterComma);
3096 }
3097 
3098 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
3099   verifyFormat("class A {\n} a, b;");
3100   verifyFormat("struct A {\n} a, b;");
3101   verifyFormat("union A {\n} a;");
3102 }
3103 
3104 TEST_F(FormatTest, FormatsEnum) {
3105   verifyFormat("enum {\n"
3106                "  Zero,\n"
3107                "  One = 1,\n"
3108                "  Two = One + 1,\n"
3109                "  Three = (One + Two),\n"
3110                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3111                "  Five = (One, Two, Three, Four, 5)\n"
3112                "};");
3113   verifyGoogleFormat("enum {\n"
3114                      "  Zero,\n"
3115                      "  One = 1,\n"
3116                      "  Two = One + 1,\n"
3117                      "  Three = (One + Two),\n"
3118                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3119                      "  Five = (One, Two, Three, Four, 5)\n"
3120                      "};");
3121   verifyFormat("enum Enum {};");
3122   verifyFormat("enum {};");
3123   verifyFormat("enum X E {} d;");
3124   verifyFormat("enum __attribute__((...)) E {} d;");
3125   verifyFormat("enum __declspec__((...)) E {} d;");
3126   verifyFormat("enum {\n"
3127                "  Bar = Foo<int, int>::value\n"
3128                "};",
3129                getLLVMStyleWithColumns(30));
3130 
3131   verifyFormat("enum ShortEnum { A, B, C };");
3132   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3133 
3134   EXPECT_EQ("enum KeepEmptyLines {\n"
3135             "  ONE,\n"
3136             "\n"
3137             "  TWO,\n"
3138             "\n"
3139             "  THREE\n"
3140             "}",
3141             format("enum KeepEmptyLines {\n"
3142                    "  ONE,\n"
3143                    "\n"
3144                    "  TWO,\n"
3145                    "\n"
3146                    "\n"
3147                    "  THREE\n"
3148                    "}"));
3149   verifyFormat("enum E { // comment\n"
3150                "  ONE,\n"
3151                "  TWO\n"
3152                "};\n"
3153                "int i;");
3154 
3155   FormatStyle EightIndent = getLLVMStyle();
3156   EightIndent.IndentWidth = 8;
3157   verifyFormat("enum {\n"
3158                "        VOID,\n"
3159                "        CHAR,\n"
3160                "        SHORT,\n"
3161                "        INT,\n"
3162                "        LONG,\n"
3163                "        SIGNED,\n"
3164                "        UNSIGNED,\n"
3165                "        BOOL,\n"
3166                "        FLOAT,\n"
3167                "        DOUBLE,\n"
3168                "        COMPLEX\n"
3169                "};",
3170                EightIndent);
3171 
3172   // Not enums.
3173   verifyFormat("enum X f() {\n"
3174                "  a();\n"
3175                "  return 42;\n"
3176                "}");
3177   verifyFormat("enum X Type::f() {\n"
3178                "  a();\n"
3179                "  return 42;\n"
3180                "}");
3181   verifyFormat("enum ::X f() {\n"
3182                "  a();\n"
3183                "  return 42;\n"
3184                "}");
3185   verifyFormat("enum ns::X f() {\n"
3186                "  a();\n"
3187                "  return 42;\n"
3188                "}");
3189 }
3190 
3191 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3192   verifyFormat("enum Type {\n"
3193                "  One = 0; // These semicolons should be commas.\n"
3194                "  Two = 1;\n"
3195                "};");
3196   verifyFormat("namespace n {\n"
3197                "enum Type {\n"
3198                "  One,\n"
3199                "  Two, // missing };\n"
3200                "  int i;\n"
3201                "}\n"
3202                "void g() {}");
3203 }
3204 
3205 TEST_F(FormatTest, FormatsEnumStruct) {
3206   verifyFormat("enum struct {\n"
3207                "  Zero,\n"
3208                "  One = 1,\n"
3209                "  Two = One + 1,\n"
3210                "  Three = (One + Two),\n"
3211                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3212                "  Five = (One, Two, Three, Four, 5)\n"
3213                "};");
3214   verifyFormat("enum struct Enum {};");
3215   verifyFormat("enum struct {};");
3216   verifyFormat("enum struct X E {} d;");
3217   verifyFormat("enum struct __attribute__((...)) E {} d;");
3218   verifyFormat("enum struct __declspec__((...)) E {} d;");
3219   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3220 }
3221 
3222 TEST_F(FormatTest, FormatsEnumClass) {
3223   verifyFormat("enum class {\n"
3224                "  Zero,\n"
3225                "  One = 1,\n"
3226                "  Two = One + 1,\n"
3227                "  Three = (One + Two),\n"
3228                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3229                "  Five = (One, Two, Three, Four, 5)\n"
3230                "};");
3231   verifyFormat("enum class Enum {};");
3232   verifyFormat("enum class {};");
3233   verifyFormat("enum class X E {} d;");
3234   verifyFormat("enum class __attribute__((...)) E {} d;");
3235   verifyFormat("enum class __declspec__((...)) E {} d;");
3236   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3237 }
3238 
3239 TEST_F(FormatTest, FormatsEnumTypes) {
3240   verifyFormat("enum X : int {\n"
3241                "  A, // Force multiple lines.\n"
3242                "  B\n"
3243                "};");
3244   verifyFormat("enum X : int { A, B };");
3245   verifyFormat("enum X : std::uint32_t { A, B };");
3246 }
3247 
3248 TEST_F(FormatTest, FormatsTypedefEnum) {
3249   FormatStyle Style = getLLVMStyle();
3250   Style.ColumnLimit = 40;
3251   verifyFormat("typedef enum {} EmptyEnum;");
3252   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3253   verifyFormat("typedef enum {\n"
3254                "  ZERO = 0,\n"
3255                "  ONE = 1,\n"
3256                "  TWO = 2,\n"
3257                "  THREE = 3\n"
3258                "} LongEnum;",
3259                Style);
3260   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3261   Style.BraceWrapping.AfterEnum = true;
3262   verifyFormat("typedef enum {} EmptyEnum;");
3263   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3264   verifyFormat("typedef enum\n"
3265                "{\n"
3266                "  ZERO = 0,\n"
3267                "  ONE = 1,\n"
3268                "  TWO = 2,\n"
3269                "  THREE = 3\n"
3270                "} LongEnum;",
3271                Style);
3272 }
3273 
3274 TEST_F(FormatTest, FormatsNSEnums) {
3275   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3276   verifyGoogleFormat(
3277       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3278   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3279                      "  // Information about someDecentlyLongValue.\n"
3280                      "  someDecentlyLongValue,\n"
3281                      "  // Information about anotherDecentlyLongValue.\n"
3282                      "  anotherDecentlyLongValue,\n"
3283                      "  // Information about aThirdDecentlyLongValue.\n"
3284                      "  aThirdDecentlyLongValue\n"
3285                      "};");
3286   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3287                      "  // Information about someDecentlyLongValue.\n"
3288                      "  someDecentlyLongValue,\n"
3289                      "  // Information about anotherDecentlyLongValue.\n"
3290                      "  anotherDecentlyLongValue,\n"
3291                      "  // Information about aThirdDecentlyLongValue.\n"
3292                      "  aThirdDecentlyLongValue\n"
3293                      "};");
3294   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3295                      "  a = 1,\n"
3296                      "  b = 2,\n"
3297                      "  c = 3,\n"
3298                      "};");
3299   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3300                      "  a = 1,\n"
3301                      "  b = 2,\n"
3302                      "  c = 3,\n"
3303                      "};");
3304   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3305                      "  a = 1,\n"
3306                      "  b = 2,\n"
3307                      "  c = 3,\n"
3308                      "};");
3309   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3310                      "  a = 1,\n"
3311                      "  b = 2,\n"
3312                      "  c = 3,\n"
3313                      "};");
3314 }
3315 
3316 TEST_F(FormatTest, FormatsBitfields) {
3317   verifyFormat("struct Bitfields {\n"
3318                "  unsigned sClass : 8;\n"
3319                "  unsigned ValueKind : 2;\n"
3320                "};");
3321   verifyFormat("struct A {\n"
3322                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3323                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3324                "};");
3325   verifyFormat("struct MyStruct {\n"
3326                "  uchar data;\n"
3327                "  uchar : 8;\n"
3328                "  uchar : 8;\n"
3329                "  uchar other;\n"
3330                "};");
3331   FormatStyle Style = getLLVMStyle();
3332   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3333   verifyFormat("struct Bitfields {\n"
3334                "  unsigned sClass:8;\n"
3335                "  unsigned ValueKind:2;\n"
3336                "  uchar other;\n"
3337                "};",
3338                Style);
3339   verifyFormat("struct A {\n"
3340                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3341                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3342                "};",
3343                Style);
3344   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3345   verifyFormat("struct Bitfields {\n"
3346                "  unsigned sClass :8;\n"
3347                "  unsigned ValueKind :2;\n"
3348                "  uchar other;\n"
3349                "};",
3350                Style);
3351   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3352   verifyFormat("struct Bitfields {\n"
3353                "  unsigned sClass: 8;\n"
3354                "  unsigned ValueKind: 2;\n"
3355                "  uchar other;\n"
3356                "};",
3357                Style);
3358 }
3359 
3360 TEST_F(FormatTest, FormatsNamespaces) {
3361   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3362   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3363 
3364   verifyFormat("namespace some_namespace {\n"
3365                "class A {};\n"
3366                "void f() { f(); }\n"
3367                "}",
3368                LLVMWithNoNamespaceFix);
3369   verifyFormat("namespace N::inline D {\n"
3370                "class A {};\n"
3371                "void f() { f(); }\n"
3372                "}",
3373                LLVMWithNoNamespaceFix);
3374   verifyFormat("namespace N::inline D::E {\n"
3375                "class A {};\n"
3376                "void f() { f(); }\n"
3377                "}",
3378                LLVMWithNoNamespaceFix);
3379   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3380                "class A {};\n"
3381                "void f() { f(); }\n"
3382                "}",
3383                LLVMWithNoNamespaceFix);
3384   verifyFormat("/* something */ namespace some_namespace {\n"
3385                "class A {};\n"
3386                "void f() { f(); }\n"
3387                "}",
3388                LLVMWithNoNamespaceFix);
3389   verifyFormat("namespace {\n"
3390                "class A {};\n"
3391                "void f() { f(); }\n"
3392                "}",
3393                LLVMWithNoNamespaceFix);
3394   verifyFormat("/* something */ namespace {\n"
3395                "class A {};\n"
3396                "void f() { f(); }\n"
3397                "}",
3398                LLVMWithNoNamespaceFix);
3399   verifyFormat("inline namespace X {\n"
3400                "class A {};\n"
3401                "void f() { f(); }\n"
3402                "}",
3403                LLVMWithNoNamespaceFix);
3404   verifyFormat("/* something */ inline namespace X {\n"
3405                "class A {};\n"
3406                "void f() { f(); }\n"
3407                "}",
3408                LLVMWithNoNamespaceFix);
3409   verifyFormat("export namespace X {\n"
3410                "class A {};\n"
3411                "void f() { f(); }\n"
3412                "}",
3413                LLVMWithNoNamespaceFix);
3414   verifyFormat("using namespace some_namespace;\n"
3415                "class A {};\n"
3416                "void f() { f(); }",
3417                LLVMWithNoNamespaceFix);
3418 
3419   // This code is more common than we thought; if we
3420   // layout this correctly the semicolon will go into
3421   // its own line, which is undesirable.
3422   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3423   verifyFormat("namespace {\n"
3424                "class A {};\n"
3425                "};",
3426                LLVMWithNoNamespaceFix);
3427 
3428   verifyFormat("namespace {\n"
3429                "int SomeVariable = 0; // comment\n"
3430                "} // namespace",
3431                LLVMWithNoNamespaceFix);
3432   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3433             "#define HEADER_GUARD\n"
3434             "namespace my_namespace {\n"
3435             "int i;\n"
3436             "} // my_namespace\n"
3437             "#endif // HEADER_GUARD",
3438             format("#ifndef HEADER_GUARD\n"
3439                    " #define HEADER_GUARD\n"
3440                    "   namespace my_namespace {\n"
3441                    "int i;\n"
3442                    "}    // my_namespace\n"
3443                    "#endif    // HEADER_GUARD",
3444                    LLVMWithNoNamespaceFix));
3445 
3446   EXPECT_EQ("namespace A::B {\n"
3447             "class C {};\n"
3448             "}",
3449             format("namespace A::B {\n"
3450                    "class C {};\n"
3451                    "}",
3452                    LLVMWithNoNamespaceFix));
3453 
3454   FormatStyle Style = getLLVMStyle();
3455   Style.NamespaceIndentation = FormatStyle::NI_All;
3456   EXPECT_EQ("namespace out {\n"
3457             "  int i;\n"
3458             "  namespace in {\n"
3459             "    int i;\n"
3460             "  } // namespace in\n"
3461             "} // namespace out",
3462             format("namespace out {\n"
3463                    "int i;\n"
3464                    "namespace in {\n"
3465                    "int i;\n"
3466                    "} // namespace in\n"
3467                    "} // namespace out",
3468                    Style));
3469 
3470   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3471   EXPECT_EQ("namespace out {\n"
3472             "int i;\n"
3473             "namespace in {\n"
3474             "  int i;\n"
3475             "} // namespace in\n"
3476             "} // namespace out",
3477             format("namespace out {\n"
3478                    "int i;\n"
3479                    "namespace in {\n"
3480                    "int i;\n"
3481                    "} // namespace in\n"
3482                    "} // namespace out",
3483                    Style));
3484 }
3485 
3486 TEST_F(FormatTest, NamespaceMacros) {
3487   FormatStyle Style = getLLVMStyle();
3488   Style.NamespaceMacros.push_back("TESTSUITE");
3489 
3490   verifyFormat("TESTSUITE(A) {\n"
3491                "int foo();\n"
3492                "} // TESTSUITE(A)",
3493                Style);
3494 
3495   verifyFormat("TESTSUITE(A, B) {\n"
3496                "int foo();\n"
3497                "} // TESTSUITE(A)",
3498                Style);
3499 
3500   // Properly indent according to NamespaceIndentation style
3501   Style.NamespaceIndentation = FormatStyle::NI_All;
3502   verifyFormat("TESTSUITE(A) {\n"
3503                "  int foo();\n"
3504                "} // TESTSUITE(A)",
3505                Style);
3506   verifyFormat("TESTSUITE(A) {\n"
3507                "  namespace B {\n"
3508                "    int foo();\n"
3509                "  } // namespace B\n"
3510                "} // TESTSUITE(A)",
3511                Style);
3512   verifyFormat("namespace A {\n"
3513                "  TESTSUITE(B) {\n"
3514                "    int foo();\n"
3515                "  } // TESTSUITE(B)\n"
3516                "} // namespace A",
3517                Style);
3518 
3519   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3520   verifyFormat("TESTSUITE(A) {\n"
3521                "TESTSUITE(B) {\n"
3522                "  int foo();\n"
3523                "} // TESTSUITE(B)\n"
3524                "} // TESTSUITE(A)",
3525                Style);
3526   verifyFormat("TESTSUITE(A) {\n"
3527                "namespace B {\n"
3528                "  int foo();\n"
3529                "} // namespace B\n"
3530                "} // TESTSUITE(A)",
3531                Style);
3532   verifyFormat("namespace A {\n"
3533                "TESTSUITE(B) {\n"
3534                "  int foo();\n"
3535                "} // TESTSUITE(B)\n"
3536                "} // namespace A",
3537                Style);
3538 
3539   // Properly merge namespace-macros blocks in CompactNamespaces mode
3540   Style.NamespaceIndentation = FormatStyle::NI_None;
3541   Style.CompactNamespaces = true;
3542   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
3543                "}} // TESTSUITE(A::B)",
3544                Style);
3545 
3546   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3547             "}} // TESTSUITE(out::in)",
3548             format("TESTSUITE(out) {\n"
3549                    "TESTSUITE(in) {\n"
3550                    "} // TESTSUITE(in)\n"
3551                    "} // TESTSUITE(out)",
3552                    Style));
3553 
3554   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3555             "}} // TESTSUITE(out::in)",
3556             format("TESTSUITE(out) {\n"
3557                    "TESTSUITE(in) {\n"
3558                    "} // TESTSUITE(in)\n"
3559                    "} // TESTSUITE(out)",
3560                    Style));
3561 
3562   // Do not merge different namespaces/macros
3563   EXPECT_EQ("namespace out {\n"
3564             "TESTSUITE(in) {\n"
3565             "} // TESTSUITE(in)\n"
3566             "} // namespace out",
3567             format("namespace out {\n"
3568                    "TESTSUITE(in) {\n"
3569                    "} // TESTSUITE(in)\n"
3570                    "} // namespace out",
3571                    Style));
3572   EXPECT_EQ("TESTSUITE(out) {\n"
3573             "namespace in {\n"
3574             "} // namespace in\n"
3575             "} // TESTSUITE(out)",
3576             format("TESTSUITE(out) {\n"
3577                    "namespace in {\n"
3578                    "} // namespace in\n"
3579                    "} // TESTSUITE(out)",
3580                    Style));
3581   Style.NamespaceMacros.push_back("FOOBAR");
3582   EXPECT_EQ("TESTSUITE(out) {\n"
3583             "FOOBAR(in) {\n"
3584             "} // FOOBAR(in)\n"
3585             "} // TESTSUITE(out)",
3586             format("TESTSUITE(out) {\n"
3587                    "FOOBAR(in) {\n"
3588                    "} // FOOBAR(in)\n"
3589                    "} // TESTSUITE(out)",
3590                    Style));
3591 }
3592 
3593 TEST_F(FormatTest, FormatsCompactNamespaces) {
3594   FormatStyle Style = getLLVMStyle();
3595   Style.CompactNamespaces = true;
3596   Style.NamespaceMacros.push_back("TESTSUITE");
3597 
3598   verifyFormat("namespace A { namespace B {\n"
3599                "}} // namespace A::B",
3600                Style);
3601 
3602   EXPECT_EQ("namespace out { namespace in {\n"
3603             "}} // namespace out::in",
3604             format("namespace out {\n"
3605                    "namespace in {\n"
3606                    "} // namespace in\n"
3607                    "} // namespace out",
3608                    Style));
3609 
3610   // Only namespaces which have both consecutive opening and end get compacted
3611   EXPECT_EQ("namespace out {\n"
3612             "namespace in1 {\n"
3613             "} // namespace in1\n"
3614             "namespace in2 {\n"
3615             "} // namespace in2\n"
3616             "} // namespace out",
3617             format("namespace out {\n"
3618                    "namespace in1 {\n"
3619                    "} // namespace in1\n"
3620                    "namespace in2 {\n"
3621                    "} // namespace in2\n"
3622                    "} // namespace out",
3623                    Style));
3624 
3625   EXPECT_EQ("namespace out {\n"
3626             "int i;\n"
3627             "namespace in {\n"
3628             "int j;\n"
3629             "} // namespace in\n"
3630             "int k;\n"
3631             "} // namespace out",
3632             format("namespace out { int i;\n"
3633                    "namespace in { int j; } // namespace in\n"
3634                    "int k; } // namespace out",
3635                    Style));
3636 
3637   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
3638             "}}} // namespace A::B::C\n",
3639             format("namespace A { namespace B {\n"
3640                    "namespace C {\n"
3641                    "}} // namespace B::C\n"
3642                    "} // namespace A\n",
3643                    Style));
3644 
3645   Style.ColumnLimit = 40;
3646   EXPECT_EQ("namespace aaaaaaaaaa {\n"
3647             "namespace bbbbbbbbbb {\n"
3648             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
3649             format("namespace aaaaaaaaaa {\n"
3650                    "namespace bbbbbbbbbb {\n"
3651                    "} // namespace bbbbbbbbbb\n"
3652                    "} // namespace aaaaaaaaaa",
3653                    Style));
3654 
3655   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
3656             "namespace cccccc {\n"
3657             "}}} // namespace aaaaaa::bbbbbb::cccccc",
3658             format("namespace aaaaaa {\n"
3659                    "namespace bbbbbb {\n"
3660                    "namespace cccccc {\n"
3661                    "} // namespace cccccc\n"
3662                    "} // namespace bbbbbb\n"
3663                    "} // namespace aaaaaa",
3664                    Style));
3665   Style.ColumnLimit = 80;
3666 
3667   // Extra semicolon after 'inner' closing brace prevents merging
3668   EXPECT_EQ("namespace out { namespace in {\n"
3669             "}; } // namespace out::in",
3670             format("namespace out {\n"
3671                    "namespace in {\n"
3672                    "}; // namespace in\n"
3673                    "} // namespace out",
3674                    Style));
3675 
3676   // Extra semicolon after 'outer' closing brace is conserved
3677   EXPECT_EQ("namespace out { namespace in {\n"
3678             "}}; // namespace out::in",
3679             format("namespace out {\n"
3680                    "namespace in {\n"
3681                    "} // namespace in\n"
3682                    "}; // namespace out",
3683                    Style));
3684 
3685   Style.NamespaceIndentation = FormatStyle::NI_All;
3686   EXPECT_EQ("namespace out { namespace in {\n"
3687             "  int i;\n"
3688             "}} // namespace out::in",
3689             format("namespace out {\n"
3690                    "namespace in {\n"
3691                    "int i;\n"
3692                    "} // namespace in\n"
3693                    "} // namespace out",
3694                    Style));
3695   EXPECT_EQ("namespace out { namespace mid {\n"
3696             "  namespace in {\n"
3697             "    int j;\n"
3698             "  } // namespace in\n"
3699             "  int k;\n"
3700             "}} // namespace out::mid",
3701             format("namespace out { namespace mid {\n"
3702                    "namespace in { int j; } // namespace in\n"
3703                    "int k; }} // namespace out::mid",
3704                    Style));
3705 
3706   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3707   EXPECT_EQ("namespace out { namespace in {\n"
3708             "  int i;\n"
3709             "}} // namespace out::in",
3710             format("namespace out {\n"
3711                    "namespace in {\n"
3712                    "int i;\n"
3713                    "} // namespace in\n"
3714                    "} // namespace out",
3715                    Style));
3716   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
3717             "  int i;\n"
3718             "}}} // namespace out::mid::in",
3719             format("namespace out {\n"
3720                    "namespace mid {\n"
3721                    "namespace in {\n"
3722                    "int i;\n"
3723                    "} // namespace in\n"
3724                    "} // namespace mid\n"
3725                    "} // namespace out",
3726                    Style));
3727 }
3728 
3729 TEST_F(FormatTest, FormatsExternC) {
3730   verifyFormat("extern \"C\" {\nint a;");
3731   verifyFormat("extern \"C\" {}");
3732   verifyFormat("extern \"C\" {\n"
3733                "int foo();\n"
3734                "}");
3735   verifyFormat("extern \"C\" int foo() {}");
3736   verifyFormat("extern \"C\" int foo();");
3737   verifyFormat("extern \"C\" int foo() {\n"
3738                "  int i = 42;\n"
3739                "  return i;\n"
3740                "}");
3741 
3742   FormatStyle Style = getLLVMStyle();
3743   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3744   Style.BraceWrapping.AfterFunction = true;
3745   verifyFormat("extern \"C\" int foo() {}", Style);
3746   verifyFormat("extern \"C\" int foo();", Style);
3747   verifyFormat("extern \"C\" int foo()\n"
3748                "{\n"
3749                "  int i = 42;\n"
3750                "  return i;\n"
3751                "}",
3752                Style);
3753 
3754   Style.BraceWrapping.AfterExternBlock = true;
3755   Style.BraceWrapping.SplitEmptyRecord = false;
3756   verifyFormat("extern \"C\"\n"
3757                "{}",
3758                Style);
3759   verifyFormat("extern \"C\"\n"
3760                "{\n"
3761                "  int foo();\n"
3762                "}",
3763                Style);
3764 }
3765 
3766 TEST_F(FormatTest, IndentExternBlockStyle) {
3767   FormatStyle Style = getLLVMStyle();
3768   Style.IndentWidth = 2;
3769 
3770   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3771   verifyFormat("extern \"C\" { /*9*/\n}", Style);
3772   verifyFormat("extern \"C\" {\n"
3773                "  int foo10();\n"
3774                "}",
3775                Style);
3776 
3777   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
3778   verifyFormat("extern \"C\" { /*11*/\n}", Style);
3779   verifyFormat("extern \"C\" {\n"
3780                "int foo12();\n"
3781                "}",
3782                Style);
3783 
3784   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
3785   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3786   Style.BraceWrapping.AfterExternBlock = true;
3787   verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
3788   verifyFormat("extern \"C\"\n{\n"
3789                "  int foo14();\n"
3790                "}",
3791                Style);
3792 
3793   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
3794   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3795   Style.BraceWrapping.AfterExternBlock = false;
3796   verifyFormat("extern \"C\" { /*15*/\n}", Style);
3797   verifyFormat("extern \"C\" {\n"
3798                "int foo16();\n"
3799                "}",
3800                Style);
3801 }
3802 
3803 TEST_F(FormatTest, FormatsInlineASM) {
3804   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
3805   verifyFormat("asm(\"nop\" ::: \"memory\");");
3806   verifyFormat(
3807       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
3808       "    \"cpuid\\n\\t\"\n"
3809       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
3810       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
3811       "    : \"a\"(value));");
3812   EXPECT_EQ(
3813       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
3814       "  __asm {\n"
3815       "        mov     edx,[that] // vtable in edx\n"
3816       "        mov     eax,methodIndex\n"
3817       "        call    [edx][eax*4] // stdcall\n"
3818       "  }\n"
3819       "}",
3820       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
3821              "    __asm {\n"
3822              "        mov     edx,[that] // vtable in edx\n"
3823              "        mov     eax,methodIndex\n"
3824              "        call    [edx][eax*4] // stdcall\n"
3825              "    }\n"
3826              "}"));
3827   EXPECT_EQ("_asm {\n"
3828             "  xor eax, eax;\n"
3829             "  cpuid;\n"
3830             "}",
3831             format("_asm {\n"
3832                    "  xor eax, eax;\n"
3833                    "  cpuid;\n"
3834                    "}"));
3835   verifyFormat("void function() {\n"
3836                "  // comment\n"
3837                "  asm(\"\");\n"
3838                "}");
3839   EXPECT_EQ("__asm {\n"
3840             "}\n"
3841             "int i;",
3842             format("__asm   {\n"
3843                    "}\n"
3844                    "int   i;"));
3845 }
3846 
3847 TEST_F(FormatTest, FormatTryCatch) {
3848   verifyFormat("try {\n"
3849                "  throw a * b;\n"
3850                "} catch (int a) {\n"
3851                "  // Do nothing.\n"
3852                "} catch (...) {\n"
3853                "  exit(42);\n"
3854                "}");
3855 
3856   // Function-level try statements.
3857   verifyFormat("int f() try { return 4; } catch (...) {\n"
3858                "  return 5;\n"
3859                "}");
3860   verifyFormat("class A {\n"
3861                "  int a;\n"
3862                "  A() try : a(0) {\n"
3863                "  } catch (...) {\n"
3864                "    throw;\n"
3865                "  }\n"
3866                "};\n");
3867   verifyFormat("class A {\n"
3868                "  int a;\n"
3869                "  A() try : a(0), b{1} {\n"
3870                "  } catch (...) {\n"
3871                "    throw;\n"
3872                "  }\n"
3873                "};\n");
3874   verifyFormat("class A {\n"
3875                "  int a;\n"
3876                "  A() try : a(0), b{1}, c{2} {\n"
3877                "  } catch (...) {\n"
3878                "    throw;\n"
3879                "  }\n"
3880                "};\n");
3881   verifyFormat("class A {\n"
3882                "  int a;\n"
3883                "  A() try : a(0), b{1}, c{2} {\n"
3884                "    { // New scope.\n"
3885                "    }\n"
3886                "  } catch (...) {\n"
3887                "    throw;\n"
3888                "  }\n"
3889                "};\n");
3890 
3891   // Incomplete try-catch blocks.
3892   verifyIncompleteFormat("try {} catch (");
3893 }
3894 
3895 TEST_F(FormatTest, FormatTryAsAVariable) {
3896   verifyFormat("int try;");
3897   verifyFormat("int try, size;");
3898   verifyFormat("try = foo();");
3899   verifyFormat("if (try < size) {\n  return true;\n}");
3900 
3901   verifyFormat("int catch;");
3902   verifyFormat("int catch, size;");
3903   verifyFormat("catch = foo();");
3904   verifyFormat("if (catch < size) {\n  return true;\n}");
3905 
3906   FormatStyle Style = getLLVMStyle();
3907   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3908   Style.BraceWrapping.AfterFunction = true;
3909   Style.BraceWrapping.BeforeCatch = true;
3910   verifyFormat("try {\n"
3911                "  int bar = 1;\n"
3912                "}\n"
3913                "catch (...) {\n"
3914                "  int bar = 1;\n"
3915                "}",
3916                Style);
3917   verifyFormat("#if NO_EX\n"
3918                "try\n"
3919                "#endif\n"
3920                "{\n"
3921                "}\n"
3922                "#if NO_EX\n"
3923                "catch (...) {\n"
3924                "}",
3925                Style);
3926   verifyFormat("try /* abc */ {\n"
3927                "  int bar = 1;\n"
3928                "}\n"
3929                "catch (...) {\n"
3930                "  int bar = 1;\n"
3931                "}",
3932                Style);
3933   verifyFormat("try\n"
3934                "// abc\n"
3935                "{\n"
3936                "  int bar = 1;\n"
3937                "}\n"
3938                "catch (...) {\n"
3939                "  int bar = 1;\n"
3940                "}",
3941                Style);
3942 }
3943 
3944 TEST_F(FormatTest, FormatSEHTryCatch) {
3945   verifyFormat("__try {\n"
3946                "  int a = b * c;\n"
3947                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
3948                "  // Do nothing.\n"
3949                "}");
3950 
3951   verifyFormat("__try {\n"
3952                "  int a = b * c;\n"
3953                "} __finally {\n"
3954                "  // Do nothing.\n"
3955                "}");
3956 
3957   verifyFormat("DEBUG({\n"
3958                "  __try {\n"
3959                "  } __finally {\n"
3960                "  }\n"
3961                "});\n");
3962 }
3963 
3964 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
3965   verifyFormat("try {\n"
3966                "  f();\n"
3967                "} catch {\n"
3968                "  g();\n"
3969                "}");
3970   verifyFormat("try {\n"
3971                "  f();\n"
3972                "} catch (A a) MACRO(x) {\n"
3973                "  g();\n"
3974                "} catch (B b) MACRO(x) {\n"
3975                "  g();\n"
3976                "}");
3977 }
3978 
3979 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
3980   FormatStyle Style = getLLVMStyle();
3981   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
3982                           FormatStyle::BS_WebKit}) {
3983     Style.BreakBeforeBraces = BraceStyle;
3984     verifyFormat("try {\n"
3985                  "  // something\n"
3986                  "} catch (...) {\n"
3987                  "  // something\n"
3988                  "}",
3989                  Style);
3990   }
3991   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
3992   verifyFormat("try {\n"
3993                "  // something\n"
3994                "}\n"
3995                "catch (...) {\n"
3996                "  // something\n"
3997                "}",
3998                Style);
3999   verifyFormat("__try {\n"
4000                "  // something\n"
4001                "}\n"
4002                "__finally {\n"
4003                "  // something\n"
4004                "}",
4005                Style);
4006   verifyFormat("@try {\n"
4007                "  // something\n"
4008                "}\n"
4009                "@finally {\n"
4010                "  // something\n"
4011                "}",
4012                Style);
4013   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4014   verifyFormat("try\n"
4015                "{\n"
4016                "  // something\n"
4017                "}\n"
4018                "catch (...)\n"
4019                "{\n"
4020                "  // something\n"
4021                "}",
4022                Style);
4023   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4024   verifyFormat("try\n"
4025                "  {\n"
4026                "  // something white\n"
4027                "  }\n"
4028                "catch (...)\n"
4029                "  {\n"
4030                "  // something white\n"
4031                "  }",
4032                Style);
4033   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4034   verifyFormat("try\n"
4035                "  {\n"
4036                "    // something\n"
4037                "  }\n"
4038                "catch (...)\n"
4039                "  {\n"
4040                "    // something\n"
4041                "  }",
4042                Style);
4043   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4044   Style.BraceWrapping.BeforeCatch = true;
4045   verifyFormat("try {\n"
4046                "  // something\n"
4047                "}\n"
4048                "catch (...) {\n"
4049                "  // something\n"
4050                "}",
4051                Style);
4052 }
4053 
4054 TEST_F(FormatTest, StaticInitializers) {
4055   verifyFormat("static SomeClass SC = {1, 'a'};");
4056 
4057   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4058                "    100000000, "
4059                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4060 
4061   // Here, everything other than the "}" would fit on a line.
4062   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4063                "    10000000000000000000000000};");
4064   EXPECT_EQ("S s = {a,\n"
4065             "\n"
4066             "       b};",
4067             format("S s = {\n"
4068                    "  a,\n"
4069                    "\n"
4070                    "  b\n"
4071                    "};"));
4072 
4073   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4074   // line. However, the formatting looks a bit off and this probably doesn't
4075   // happen often in practice.
4076   verifyFormat("static int Variable[1] = {\n"
4077                "    {1000000000000000000000000000000000000}};",
4078                getLLVMStyleWithColumns(40));
4079 }
4080 
4081 TEST_F(FormatTest, DesignatedInitializers) {
4082   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4083   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4084                "                    .bbbbbbbbbb = 2,\n"
4085                "                    .cccccccccc = 3,\n"
4086                "                    .dddddddddd = 4,\n"
4087                "                    .eeeeeeeeee = 5};");
4088   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4089                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4090                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4091                "    .ccccccccccccccccccccccccccc = 3,\n"
4092                "    .ddddddddddddddddddddddddddd = 4,\n"
4093                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4094 
4095   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4096 
4097   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4098   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4099                "                    [2] = bbbbbbbbbb,\n"
4100                "                    [3] = cccccccccc,\n"
4101                "                    [4] = dddddddddd,\n"
4102                "                    [5] = eeeeeeeeee};");
4103   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4104                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4105                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4106                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4107                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4108                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4109 }
4110 
4111 TEST_F(FormatTest, NestedStaticInitializers) {
4112   verifyFormat("static A x = {{{}}};\n");
4113   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4114                "               {init1, init2, init3, init4}}};",
4115                getLLVMStyleWithColumns(50));
4116 
4117   verifyFormat("somes Status::global_reps[3] = {\n"
4118                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4119                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4120                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4121                getLLVMStyleWithColumns(60));
4122   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4123                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4124                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4125                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4126   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4127                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4128                "rect.fTop}};");
4129 
4130   verifyFormat(
4131       "SomeArrayOfSomeType a = {\n"
4132       "    {{1, 2, 3},\n"
4133       "     {1, 2, 3},\n"
4134       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4135       "      333333333333333333333333333333},\n"
4136       "     {1, 2, 3},\n"
4137       "     {1, 2, 3}}};");
4138   verifyFormat(
4139       "SomeArrayOfSomeType a = {\n"
4140       "    {{1, 2, 3}},\n"
4141       "    {{1, 2, 3}},\n"
4142       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4143       "      333333333333333333333333333333}},\n"
4144       "    {{1, 2, 3}},\n"
4145       "    {{1, 2, 3}}};");
4146 
4147   verifyFormat("struct {\n"
4148                "  unsigned bit;\n"
4149                "  const char *const name;\n"
4150                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4151                "                 {kOsWin, \"Windows\"},\n"
4152                "                 {kOsLinux, \"Linux\"},\n"
4153                "                 {kOsCrOS, \"Chrome OS\"}};");
4154   verifyFormat("struct {\n"
4155                "  unsigned bit;\n"
4156                "  const char *const name;\n"
4157                "} kBitsToOs[] = {\n"
4158                "    {kOsMac, \"Mac\"},\n"
4159                "    {kOsWin, \"Windows\"},\n"
4160                "    {kOsLinux, \"Linux\"},\n"
4161                "    {kOsCrOS, \"Chrome OS\"},\n"
4162                "};");
4163 }
4164 
4165 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4166   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4167                "                      \\\n"
4168                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4169 }
4170 
4171 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4172   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4173                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4174 
4175   // Do break defaulted and deleted functions.
4176   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4177                "    default;",
4178                getLLVMStyleWithColumns(40));
4179   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4180                "    delete;",
4181                getLLVMStyleWithColumns(40));
4182 }
4183 
4184 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4185   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4186                getLLVMStyleWithColumns(40));
4187   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4188                getLLVMStyleWithColumns(40));
4189   EXPECT_EQ("#define Q                              \\\n"
4190             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4191             "  \"aaaaaaaa.cpp\"",
4192             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4193                    getLLVMStyleWithColumns(40)));
4194 }
4195 
4196 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4197   EXPECT_EQ("# 123 \"A string literal\"",
4198             format("   #     123    \"A string literal\""));
4199 }
4200 
4201 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4202   EXPECT_EQ("#;", format("#;"));
4203   verifyFormat("#\n;\n;\n;");
4204 }
4205 
4206 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4207   EXPECT_EQ("#line 42 \"test\"\n",
4208             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4209   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4210                                     getLLVMStyleWithColumns(12)));
4211 }
4212 
4213 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4214   EXPECT_EQ("#line 42 \"test\"",
4215             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4216   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4217 }
4218 
4219 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4220   verifyFormat("#define A \\x20");
4221   verifyFormat("#define A \\ x20");
4222   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4223   verifyFormat("#define A ''");
4224   verifyFormat("#define A ''qqq");
4225   verifyFormat("#define A `qqq");
4226   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4227   EXPECT_EQ("const char *c = STRINGIFY(\n"
4228             "\\na : b);",
4229             format("const char * c = STRINGIFY(\n"
4230                    "\\na : b);"));
4231 
4232   verifyFormat("a\r\\");
4233   verifyFormat("a\v\\");
4234   verifyFormat("a\f\\");
4235 }
4236 
4237 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4238   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4239   style.IndentWidth = 4;
4240   style.PPIndentWidth = 1;
4241 
4242   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4243   verifyFormat("#ifdef __linux__\n"
4244                "void foo() {\n"
4245                "    int x = 0;\n"
4246                "}\n"
4247                "#define FOO\n"
4248                "#endif\n"
4249                "void bar() {\n"
4250                "    int y = 0;\n"
4251                "}\n",
4252                style);
4253 
4254   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4255   verifyFormat("#ifdef __linux__\n"
4256                "void foo() {\n"
4257                "    int x = 0;\n"
4258                "}\n"
4259                "# define FOO foo\n"
4260                "#endif\n"
4261                "void bar() {\n"
4262                "    int y = 0;\n"
4263                "}\n",
4264                style);
4265 
4266   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4267   verifyFormat("#ifdef __linux__\n"
4268                "void foo() {\n"
4269                "    int x = 0;\n"
4270                "}\n"
4271                " #define FOO foo\n"
4272                "#endif\n"
4273                "void bar() {\n"
4274                "    int y = 0;\n"
4275                "}\n",
4276                style);
4277 }
4278 
4279 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4280   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4281   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4282   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4283   // FIXME: We never break before the macro name.
4284   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4285 
4286   verifyFormat("#define A A\n#define A A");
4287   verifyFormat("#define A(X) A\n#define A A");
4288 
4289   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4290   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4291 }
4292 
4293 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4294   EXPECT_EQ("// somecomment\n"
4295             "#include \"a.h\"\n"
4296             "#define A(  \\\n"
4297             "    A, B)\n"
4298             "#include \"b.h\"\n"
4299             "// somecomment\n",
4300             format("  // somecomment\n"
4301                    "  #include \"a.h\"\n"
4302                    "#define A(A,\\\n"
4303                    "    B)\n"
4304                    "    #include \"b.h\"\n"
4305                    " // somecomment\n",
4306                    getLLVMStyleWithColumns(13)));
4307 }
4308 
4309 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4310 
4311 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4312   EXPECT_EQ("#define A    \\\n"
4313             "  c;         \\\n"
4314             "  e;\n"
4315             "f;",
4316             format("#define A c; e;\n"
4317                    "f;",
4318                    getLLVMStyleWithColumns(14)));
4319 }
4320 
4321 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4322 
4323 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4324   EXPECT_EQ("int x,\n"
4325             "#define A\n"
4326             "    y;",
4327             format("int x,\n#define A\ny;"));
4328 }
4329 
4330 TEST_F(FormatTest, HashInMacroDefinition) {
4331   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4332   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4333   verifyFormat("#define A  \\\n"
4334                "  {        \\\n"
4335                "    f(#c); \\\n"
4336                "  }",
4337                getLLVMStyleWithColumns(11));
4338 
4339   verifyFormat("#define A(X)         \\\n"
4340                "  void function##X()",
4341                getLLVMStyleWithColumns(22));
4342 
4343   verifyFormat("#define A(a, b, c)   \\\n"
4344                "  void a##b##c()",
4345                getLLVMStyleWithColumns(22));
4346 
4347   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4348 }
4349 
4350 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4351   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4352   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4353 
4354   FormatStyle Style = getLLVMStyle();
4355   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4356   verifyFormat("#define true ((foo)1)", Style);
4357   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4358   verifyFormat("#define false((foo)0)", Style);
4359 }
4360 
4361 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4362   EXPECT_EQ("#define A b;", format("#define A \\\n"
4363                                    "          \\\n"
4364                                    "  b;",
4365                                    getLLVMStyleWithColumns(25)));
4366   EXPECT_EQ("#define A \\\n"
4367             "          \\\n"
4368             "  a;      \\\n"
4369             "  b;",
4370             format("#define A \\\n"
4371                    "          \\\n"
4372                    "  a;      \\\n"
4373                    "  b;",
4374                    getLLVMStyleWithColumns(11)));
4375   EXPECT_EQ("#define A \\\n"
4376             "  a;      \\\n"
4377             "          \\\n"
4378             "  b;",
4379             format("#define A \\\n"
4380                    "  a;      \\\n"
4381                    "          \\\n"
4382                    "  b;",
4383                    getLLVMStyleWithColumns(11)));
4384 }
4385 
4386 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
4387   verifyIncompleteFormat("#define A :");
4388   verifyFormat("#define SOMECASES  \\\n"
4389                "  case 1:          \\\n"
4390                "  case 2\n",
4391                getLLVMStyleWithColumns(20));
4392   verifyFormat("#define MACRO(a) \\\n"
4393                "  if (a)         \\\n"
4394                "    f();         \\\n"
4395                "  else           \\\n"
4396                "    g()",
4397                getLLVMStyleWithColumns(18));
4398   verifyFormat("#define A template <typename T>");
4399   verifyIncompleteFormat("#define STR(x) #x\n"
4400                          "f(STR(this_is_a_string_literal{));");
4401   verifyFormat("#pragma omp threadprivate( \\\n"
4402                "    y)), // expected-warning",
4403                getLLVMStyleWithColumns(28));
4404   verifyFormat("#d, = };");
4405   verifyFormat("#if \"a");
4406   verifyIncompleteFormat("({\n"
4407                          "#define b     \\\n"
4408                          "  }           \\\n"
4409                          "  a\n"
4410                          "a",
4411                          getLLVMStyleWithColumns(15));
4412   verifyFormat("#define A     \\\n"
4413                "  {           \\\n"
4414                "    {\n"
4415                "#define B     \\\n"
4416                "  }           \\\n"
4417                "  }",
4418                getLLVMStyleWithColumns(15));
4419   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
4420   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
4421   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
4422   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
4423 }
4424 
4425 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
4426   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
4427   EXPECT_EQ("class A : public QObject {\n"
4428             "  Q_OBJECT\n"
4429             "\n"
4430             "  A() {}\n"
4431             "};",
4432             format("class A  :  public QObject {\n"
4433                    "     Q_OBJECT\n"
4434                    "\n"
4435                    "  A() {\n}\n"
4436                    "}  ;"));
4437   EXPECT_EQ("MACRO\n"
4438             "/*static*/ int i;",
4439             format("MACRO\n"
4440                    " /*static*/ int   i;"));
4441   EXPECT_EQ("SOME_MACRO\n"
4442             "namespace {\n"
4443             "void f();\n"
4444             "} // namespace",
4445             format("SOME_MACRO\n"
4446                    "  namespace    {\n"
4447                    "void   f(  );\n"
4448                    "} // namespace"));
4449   // Only if the identifier contains at least 5 characters.
4450   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
4451   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
4452   // Only if everything is upper case.
4453   EXPECT_EQ("class A : public QObject {\n"
4454             "  Q_Object A() {}\n"
4455             "};",
4456             format("class A  :  public QObject {\n"
4457                    "     Q_Object\n"
4458                    "  A() {\n}\n"
4459                    "}  ;"));
4460 
4461   // Only if the next line can actually start an unwrapped line.
4462   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
4463             format("SOME_WEIRD_LOG_MACRO\n"
4464                    "<< SomeThing;"));
4465 
4466   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
4467                "(n, buffers))\n",
4468                getChromiumStyle(FormatStyle::LK_Cpp));
4469 
4470   // See PR41483
4471   EXPECT_EQ("/**/ FOO(a)\n"
4472             "FOO(b)",
4473             format("/**/ FOO(a)\n"
4474                    "FOO(b)"));
4475 }
4476 
4477 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
4478   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4479             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4480             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4481             "class X {};\n"
4482             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4483             "int *createScopDetectionPass() { return 0; }",
4484             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4485                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4486                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4487                    "  class X {};\n"
4488                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4489                    "  int *createScopDetectionPass() { return 0; }"));
4490   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
4491   // braces, so that inner block is indented one level more.
4492   EXPECT_EQ("int q() {\n"
4493             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4494             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4495             "  IPC_END_MESSAGE_MAP()\n"
4496             "}",
4497             format("int q() {\n"
4498                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4499                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4500                    "  IPC_END_MESSAGE_MAP()\n"
4501                    "}"));
4502 
4503   // Same inside macros.
4504   EXPECT_EQ("#define LIST(L) \\\n"
4505             "  L(A)          \\\n"
4506             "  L(B)          \\\n"
4507             "  L(C)",
4508             format("#define LIST(L) \\\n"
4509                    "  L(A) \\\n"
4510                    "  L(B) \\\n"
4511                    "  L(C)",
4512                    getGoogleStyle()));
4513 
4514   // These must not be recognized as macros.
4515   EXPECT_EQ("int q() {\n"
4516             "  f(x);\n"
4517             "  f(x) {}\n"
4518             "  f(x)->g();\n"
4519             "  f(x)->*g();\n"
4520             "  f(x).g();\n"
4521             "  f(x) = x;\n"
4522             "  f(x) += x;\n"
4523             "  f(x) -= x;\n"
4524             "  f(x) *= x;\n"
4525             "  f(x) /= x;\n"
4526             "  f(x) %= x;\n"
4527             "  f(x) &= x;\n"
4528             "  f(x) |= x;\n"
4529             "  f(x) ^= x;\n"
4530             "  f(x) >>= x;\n"
4531             "  f(x) <<= x;\n"
4532             "  f(x)[y].z();\n"
4533             "  LOG(INFO) << x;\n"
4534             "  ifstream(x) >> x;\n"
4535             "}\n",
4536             format("int q() {\n"
4537                    "  f(x)\n;\n"
4538                    "  f(x)\n {}\n"
4539                    "  f(x)\n->g();\n"
4540                    "  f(x)\n->*g();\n"
4541                    "  f(x)\n.g();\n"
4542                    "  f(x)\n = x;\n"
4543                    "  f(x)\n += x;\n"
4544                    "  f(x)\n -= x;\n"
4545                    "  f(x)\n *= x;\n"
4546                    "  f(x)\n /= x;\n"
4547                    "  f(x)\n %= x;\n"
4548                    "  f(x)\n &= x;\n"
4549                    "  f(x)\n |= x;\n"
4550                    "  f(x)\n ^= x;\n"
4551                    "  f(x)\n >>= x;\n"
4552                    "  f(x)\n <<= x;\n"
4553                    "  f(x)\n[y].z();\n"
4554                    "  LOG(INFO)\n << x;\n"
4555                    "  ifstream(x)\n >> x;\n"
4556                    "}\n"));
4557   EXPECT_EQ("int q() {\n"
4558             "  F(x)\n"
4559             "  if (1) {\n"
4560             "  }\n"
4561             "  F(x)\n"
4562             "  while (1) {\n"
4563             "  }\n"
4564             "  F(x)\n"
4565             "  G(x);\n"
4566             "  F(x)\n"
4567             "  try {\n"
4568             "    Q();\n"
4569             "  } catch (...) {\n"
4570             "  }\n"
4571             "}\n",
4572             format("int q() {\n"
4573                    "F(x)\n"
4574                    "if (1) {}\n"
4575                    "F(x)\n"
4576                    "while (1) {}\n"
4577                    "F(x)\n"
4578                    "G(x);\n"
4579                    "F(x)\n"
4580                    "try { Q(); } catch (...) {}\n"
4581                    "}\n"));
4582   EXPECT_EQ("class A {\n"
4583             "  A() : t(0) {}\n"
4584             "  A(int i) noexcept() : {}\n"
4585             "  A(X x)\n" // FIXME: function-level try blocks are broken.
4586             "  try : t(0) {\n"
4587             "  } catch (...) {\n"
4588             "  }\n"
4589             "};",
4590             format("class A {\n"
4591                    "  A()\n : t(0) {}\n"
4592                    "  A(int i)\n noexcept() : {}\n"
4593                    "  A(X x)\n"
4594                    "  try : t(0) {} catch (...) {}\n"
4595                    "};"));
4596   FormatStyle Style = getLLVMStyle();
4597   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4598   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
4599   Style.BraceWrapping.AfterFunction = true;
4600   EXPECT_EQ("void f()\n"
4601             "try\n"
4602             "{\n"
4603             "}",
4604             format("void f() try {\n"
4605                    "}",
4606                    Style));
4607   EXPECT_EQ("class SomeClass {\n"
4608             "public:\n"
4609             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4610             "};",
4611             format("class SomeClass {\n"
4612                    "public:\n"
4613                    "  SomeClass()\n"
4614                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4615                    "};"));
4616   EXPECT_EQ("class SomeClass {\n"
4617             "public:\n"
4618             "  SomeClass()\n"
4619             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4620             "};",
4621             format("class SomeClass {\n"
4622                    "public:\n"
4623                    "  SomeClass()\n"
4624                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4625                    "};",
4626                    getLLVMStyleWithColumns(40)));
4627 
4628   verifyFormat("MACRO(>)");
4629 
4630   // Some macros contain an implicit semicolon.
4631   Style = getLLVMStyle();
4632   Style.StatementMacros.push_back("FOO");
4633   verifyFormat("FOO(a) int b = 0;");
4634   verifyFormat("FOO(a)\n"
4635                "int b = 0;",
4636                Style);
4637   verifyFormat("FOO(a);\n"
4638                "int b = 0;",
4639                Style);
4640   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
4641                "int b = 0;",
4642                Style);
4643   verifyFormat("FOO()\n"
4644                "int b = 0;",
4645                Style);
4646   verifyFormat("FOO\n"
4647                "int b = 0;",
4648                Style);
4649   verifyFormat("void f() {\n"
4650                "  FOO(a)\n"
4651                "  return a;\n"
4652                "}",
4653                Style);
4654   verifyFormat("FOO(a)\n"
4655                "FOO(b)",
4656                Style);
4657   verifyFormat("int a = 0;\n"
4658                "FOO(b)\n"
4659                "int c = 0;",
4660                Style);
4661   verifyFormat("int a = 0;\n"
4662                "int x = FOO(a)\n"
4663                "int b = 0;",
4664                Style);
4665   verifyFormat("void foo(int a) { FOO(a) }\n"
4666                "uint32_t bar() {}",
4667                Style);
4668 }
4669 
4670 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
4671   verifyFormat("#define A \\\n"
4672                "  f({     \\\n"
4673                "    g();  \\\n"
4674                "  });",
4675                getLLVMStyleWithColumns(11));
4676 }
4677 
4678 TEST_F(FormatTest, IndentPreprocessorDirectives) {
4679   FormatStyle Style = getLLVMStyle();
4680   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
4681   Style.ColumnLimit = 40;
4682   verifyFormat("#ifdef _WIN32\n"
4683                "#define A 0\n"
4684                "#ifdef VAR2\n"
4685                "#define B 1\n"
4686                "#include <someheader.h>\n"
4687                "#define MACRO                          \\\n"
4688                "  some_very_long_func_aaaaaaaaaa();\n"
4689                "#endif\n"
4690                "#else\n"
4691                "#define A 1\n"
4692                "#endif",
4693                Style);
4694   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4695   verifyFormat("#ifdef _WIN32\n"
4696                "#  define A 0\n"
4697                "#  ifdef VAR2\n"
4698                "#    define B 1\n"
4699                "#    include <someheader.h>\n"
4700                "#    define MACRO                      \\\n"
4701                "      some_very_long_func_aaaaaaaaaa();\n"
4702                "#  endif\n"
4703                "#else\n"
4704                "#  define A 1\n"
4705                "#endif",
4706                Style);
4707   verifyFormat("#if A\n"
4708                "#  define MACRO                        \\\n"
4709                "    void a(int x) {                    \\\n"
4710                "      b();                             \\\n"
4711                "      c();                             \\\n"
4712                "      d();                             \\\n"
4713                "      e();                             \\\n"
4714                "      f();                             \\\n"
4715                "    }\n"
4716                "#endif",
4717                Style);
4718   // Comments before include guard.
4719   verifyFormat("// file comment\n"
4720                "// file comment\n"
4721                "#ifndef HEADER_H\n"
4722                "#define HEADER_H\n"
4723                "code();\n"
4724                "#endif",
4725                Style);
4726   // Test with include guards.
4727   verifyFormat("#ifndef HEADER_H\n"
4728                "#define HEADER_H\n"
4729                "code();\n"
4730                "#endif",
4731                Style);
4732   // Include guards must have a #define with the same variable immediately
4733   // after #ifndef.
4734   verifyFormat("#ifndef NOT_GUARD\n"
4735                "#  define FOO\n"
4736                "code();\n"
4737                "#endif",
4738                Style);
4739 
4740   // Include guards must cover the entire file.
4741   verifyFormat("code();\n"
4742                "code();\n"
4743                "#ifndef NOT_GUARD\n"
4744                "#  define NOT_GUARD\n"
4745                "code();\n"
4746                "#endif",
4747                Style);
4748   verifyFormat("#ifndef NOT_GUARD\n"
4749                "#  define NOT_GUARD\n"
4750                "code();\n"
4751                "#endif\n"
4752                "code();",
4753                Style);
4754   // Test with trailing blank lines.
4755   verifyFormat("#ifndef HEADER_H\n"
4756                "#define HEADER_H\n"
4757                "code();\n"
4758                "#endif\n",
4759                Style);
4760   // Include guards don't have #else.
4761   verifyFormat("#ifndef NOT_GUARD\n"
4762                "#  define NOT_GUARD\n"
4763                "code();\n"
4764                "#else\n"
4765                "#endif",
4766                Style);
4767   verifyFormat("#ifndef NOT_GUARD\n"
4768                "#  define NOT_GUARD\n"
4769                "code();\n"
4770                "#elif FOO\n"
4771                "#endif",
4772                Style);
4773   // Non-identifier #define after potential include guard.
4774   verifyFormat("#ifndef FOO\n"
4775                "#  define 1\n"
4776                "#endif\n",
4777                Style);
4778   // #if closes past last non-preprocessor line.
4779   verifyFormat("#ifndef FOO\n"
4780                "#define FOO\n"
4781                "#if 1\n"
4782                "int i;\n"
4783                "#  define A 0\n"
4784                "#endif\n"
4785                "#endif\n",
4786                Style);
4787   // Don't crash if there is an #elif directive without a condition.
4788   verifyFormat("#if 1\n"
4789                "int x;\n"
4790                "#elif\n"
4791                "int y;\n"
4792                "#else\n"
4793                "int z;\n"
4794                "#endif",
4795                Style);
4796   // FIXME: This doesn't handle the case where there's code between the
4797   // #ifndef and #define but all other conditions hold. This is because when
4798   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
4799   // previous code line yet, so we can't detect it.
4800   EXPECT_EQ("#ifndef NOT_GUARD\n"
4801             "code();\n"
4802             "#define NOT_GUARD\n"
4803             "code();\n"
4804             "#endif",
4805             format("#ifndef NOT_GUARD\n"
4806                    "code();\n"
4807                    "#  define NOT_GUARD\n"
4808                    "code();\n"
4809                    "#endif",
4810                    Style));
4811   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
4812   // be outside an include guard. Examples are #pragma once and
4813   // #pragma GCC diagnostic, or anything else that does not change the meaning
4814   // of the file if it's included multiple times.
4815   EXPECT_EQ("#ifdef WIN32\n"
4816             "#  pragma once\n"
4817             "#endif\n"
4818             "#ifndef HEADER_H\n"
4819             "#  define HEADER_H\n"
4820             "code();\n"
4821             "#endif",
4822             format("#ifdef WIN32\n"
4823                    "#  pragma once\n"
4824                    "#endif\n"
4825                    "#ifndef HEADER_H\n"
4826                    "#define HEADER_H\n"
4827                    "code();\n"
4828                    "#endif",
4829                    Style));
4830   // FIXME: This does not detect when there is a single non-preprocessor line
4831   // in front of an include-guard-like structure where other conditions hold
4832   // because ScopedLineState hides the line.
4833   EXPECT_EQ("code();\n"
4834             "#ifndef HEADER_H\n"
4835             "#define HEADER_H\n"
4836             "code();\n"
4837             "#endif",
4838             format("code();\n"
4839                    "#ifndef HEADER_H\n"
4840                    "#  define HEADER_H\n"
4841                    "code();\n"
4842                    "#endif",
4843                    Style));
4844   // Keep comments aligned with #, otherwise indent comments normally. These
4845   // tests cannot use verifyFormat because messUp manipulates leading
4846   // whitespace.
4847   {
4848     const char *Expected = ""
4849                            "void f() {\n"
4850                            "#if 1\n"
4851                            "// Preprocessor aligned.\n"
4852                            "#  define A 0\n"
4853                            "  // Code. Separated by blank line.\n"
4854                            "\n"
4855                            "#  define B 0\n"
4856                            "  // Code. Not aligned with #\n"
4857                            "#  define C 0\n"
4858                            "#endif";
4859     const char *ToFormat = ""
4860                            "void f() {\n"
4861                            "#if 1\n"
4862                            "// Preprocessor aligned.\n"
4863                            "#  define A 0\n"
4864                            "// Code. Separated by blank line.\n"
4865                            "\n"
4866                            "#  define B 0\n"
4867                            "   // Code. Not aligned with #\n"
4868                            "#  define C 0\n"
4869                            "#endif";
4870     EXPECT_EQ(Expected, format(ToFormat, Style));
4871     EXPECT_EQ(Expected, format(Expected, Style));
4872   }
4873   // Keep block quotes aligned.
4874   {
4875     const char *Expected = ""
4876                            "void f() {\n"
4877                            "#if 1\n"
4878                            "/* Preprocessor aligned. */\n"
4879                            "#  define A 0\n"
4880                            "  /* Code. Separated by blank line. */\n"
4881                            "\n"
4882                            "#  define B 0\n"
4883                            "  /* Code. Not aligned with # */\n"
4884                            "#  define C 0\n"
4885                            "#endif";
4886     const char *ToFormat = ""
4887                            "void f() {\n"
4888                            "#if 1\n"
4889                            "/* Preprocessor aligned. */\n"
4890                            "#  define A 0\n"
4891                            "/* Code. Separated by blank line. */\n"
4892                            "\n"
4893                            "#  define B 0\n"
4894                            "   /* Code. Not aligned with # */\n"
4895                            "#  define C 0\n"
4896                            "#endif";
4897     EXPECT_EQ(Expected, format(ToFormat, Style));
4898     EXPECT_EQ(Expected, format(Expected, Style));
4899   }
4900   // Keep comments aligned with un-indented directives.
4901   {
4902     const char *Expected = ""
4903                            "void f() {\n"
4904                            "// Preprocessor aligned.\n"
4905                            "#define A 0\n"
4906                            "  // Code. Separated by blank line.\n"
4907                            "\n"
4908                            "#define B 0\n"
4909                            "  // Code. Not aligned with #\n"
4910                            "#define C 0\n";
4911     const char *ToFormat = ""
4912                            "void f() {\n"
4913                            "// Preprocessor aligned.\n"
4914                            "#define A 0\n"
4915                            "// Code. Separated by blank line.\n"
4916                            "\n"
4917                            "#define B 0\n"
4918                            "   // Code. Not aligned with #\n"
4919                            "#define C 0\n";
4920     EXPECT_EQ(Expected, format(ToFormat, Style));
4921     EXPECT_EQ(Expected, format(Expected, Style));
4922   }
4923   // Test AfterHash with tabs.
4924   {
4925     FormatStyle Tabbed = Style;
4926     Tabbed.UseTab = FormatStyle::UT_Always;
4927     Tabbed.IndentWidth = 8;
4928     Tabbed.TabWidth = 8;
4929     verifyFormat("#ifdef _WIN32\n"
4930                  "#\tdefine A 0\n"
4931                  "#\tifdef VAR2\n"
4932                  "#\t\tdefine B 1\n"
4933                  "#\t\tinclude <someheader.h>\n"
4934                  "#\t\tdefine MACRO          \\\n"
4935                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
4936                  "#\tendif\n"
4937                  "#else\n"
4938                  "#\tdefine A 1\n"
4939                  "#endif",
4940                  Tabbed);
4941   }
4942 
4943   // Regression test: Multiline-macro inside include guards.
4944   verifyFormat("#ifndef HEADER_H\n"
4945                "#define HEADER_H\n"
4946                "#define A()        \\\n"
4947                "  int i;           \\\n"
4948                "  int j;\n"
4949                "#endif // HEADER_H",
4950                getLLVMStyleWithColumns(20));
4951 
4952   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4953   // Basic before hash indent tests
4954   verifyFormat("#ifdef _WIN32\n"
4955                "  #define A 0\n"
4956                "  #ifdef VAR2\n"
4957                "    #define B 1\n"
4958                "    #include <someheader.h>\n"
4959                "    #define MACRO                      \\\n"
4960                "      some_very_long_func_aaaaaaaaaa();\n"
4961                "  #endif\n"
4962                "#else\n"
4963                "  #define A 1\n"
4964                "#endif",
4965                Style);
4966   verifyFormat("#if A\n"
4967                "  #define MACRO                        \\\n"
4968                "    void a(int x) {                    \\\n"
4969                "      b();                             \\\n"
4970                "      c();                             \\\n"
4971                "      d();                             \\\n"
4972                "      e();                             \\\n"
4973                "      f();                             \\\n"
4974                "    }\n"
4975                "#endif",
4976                Style);
4977   // Keep comments aligned with indented directives. These
4978   // tests cannot use verifyFormat because messUp manipulates leading
4979   // whitespace.
4980   {
4981     const char *Expected = "void f() {\n"
4982                            "// Aligned to preprocessor.\n"
4983                            "#if 1\n"
4984                            "  // Aligned to code.\n"
4985                            "  int a;\n"
4986                            "  #if 1\n"
4987                            "    // Aligned to preprocessor.\n"
4988                            "    #define A 0\n"
4989                            "  // Aligned to code.\n"
4990                            "  int b;\n"
4991                            "  #endif\n"
4992                            "#endif\n"
4993                            "}";
4994     const char *ToFormat = "void f() {\n"
4995                            "// Aligned to preprocessor.\n"
4996                            "#if 1\n"
4997                            "// Aligned to code.\n"
4998                            "int a;\n"
4999                            "#if 1\n"
5000                            "// Aligned to preprocessor.\n"
5001                            "#define A 0\n"
5002                            "// Aligned to code.\n"
5003                            "int b;\n"
5004                            "#endif\n"
5005                            "#endif\n"
5006                            "}";
5007     EXPECT_EQ(Expected, format(ToFormat, Style));
5008     EXPECT_EQ(Expected, format(Expected, Style));
5009   }
5010   {
5011     const char *Expected = "void f() {\n"
5012                            "/* Aligned to preprocessor. */\n"
5013                            "#if 1\n"
5014                            "  /* Aligned to code. */\n"
5015                            "  int a;\n"
5016                            "  #if 1\n"
5017                            "    /* Aligned to preprocessor. */\n"
5018                            "    #define A 0\n"
5019                            "  /* Aligned to code. */\n"
5020                            "  int b;\n"
5021                            "  #endif\n"
5022                            "#endif\n"
5023                            "}";
5024     const char *ToFormat = "void f() {\n"
5025                            "/* Aligned to preprocessor. */\n"
5026                            "#if 1\n"
5027                            "/* Aligned to code. */\n"
5028                            "int a;\n"
5029                            "#if 1\n"
5030                            "/* Aligned to preprocessor. */\n"
5031                            "#define A 0\n"
5032                            "/* Aligned to code. */\n"
5033                            "int b;\n"
5034                            "#endif\n"
5035                            "#endif\n"
5036                            "}";
5037     EXPECT_EQ(Expected, format(ToFormat, Style));
5038     EXPECT_EQ(Expected, format(Expected, Style));
5039   }
5040 
5041   // Test single comment before preprocessor
5042   verifyFormat("// Comment\n"
5043                "\n"
5044                "#if 1\n"
5045                "#endif",
5046                Style);
5047 }
5048 
5049 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5050   verifyFormat("{\n  { a #c; }\n}");
5051 }
5052 
5053 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5054   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5055             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5056   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5057             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5058 }
5059 
5060 TEST_F(FormatTest, EscapedNewlines) {
5061   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5062   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5063             format("#define A \\\nint i;\\\n  int j;", Narrow));
5064   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5065   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5066   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5067   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5068 
5069   FormatStyle AlignLeft = getLLVMStyle();
5070   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5071   EXPECT_EQ("#define MACRO(x) \\\n"
5072             "private:         \\\n"
5073             "  int x(int a);\n",
5074             format("#define MACRO(x) \\\n"
5075                    "private:         \\\n"
5076                    "  int x(int a);\n",
5077                    AlignLeft));
5078 
5079   // CRLF line endings
5080   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5081             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5082   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5083   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5084   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5085   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5086   EXPECT_EQ("#define MACRO(x) \\\r\n"
5087             "private:         \\\r\n"
5088             "  int x(int a);\r\n",
5089             format("#define MACRO(x) \\\r\n"
5090                    "private:         \\\r\n"
5091                    "  int x(int a);\r\n",
5092                    AlignLeft));
5093 
5094   FormatStyle DontAlign = getLLVMStyle();
5095   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5096   DontAlign.MaxEmptyLinesToKeep = 3;
5097   // FIXME: can't use verifyFormat here because the newline before
5098   // "public:" is not inserted the first time it's reformatted
5099   EXPECT_EQ("#define A \\\n"
5100             "  class Foo { \\\n"
5101             "    void bar(); \\\n"
5102             "\\\n"
5103             "\\\n"
5104             "\\\n"
5105             "  public: \\\n"
5106             "    void baz(); \\\n"
5107             "  };",
5108             format("#define A \\\n"
5109                    "  class Foo { \\\n"
5110                    "    void bar(); \\\n"
5111                    "\\\n"
5112                    "\\\n"
5113                    "\\\n"
5114                    "  public: \\\n"
5115                    "    void baz(); \\\n"
5116                    "  };",
5117                    DontAlign));
5118 }
5119 
5120 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5121   verifyFormat("#define A \\\n"
5122                "  int v(  \\\n"
5123                "      a); \\\n"
5124                "  int i;",
5125                getLLVMStyleWithColumns(11));
5126 }
5127 
5128 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5129   EXPECT_EQ(
5130       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5131       "                      \\\n"
5132       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5133       "\n"
5134       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5135       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5136       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5137              "\\\n"
5138              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5139              "  \n"
5140              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5141              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5142 }
5143 
5144 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5145   EXPECT_EQ("int\n"
5146             "#define A\n"
5147             "    a;",
5148             format("int\n#define A\na;"));
5149   verifyFormat("functionCallTo(\n"
5150                "    someOtherFunction(\n"
5151                "        withSomeParameters, whichInSequence,\n"
5152                "        areLongerThanALine(andAnotherCall,\n"
5153                "#define A B\n"
5154                "                           withMoreParamters,\n"
5155                "                           whichStronglyInfluenceTheLayout),\n"
5156                "        andMoreParameters),\n"
5157                "    trailing);",
5158                getLLVMStyleWithColumns(69));
5159   verifyFormat("Foo::Foo()\n"
5160                "#ifdef BAR\n"
5161                "    : baz(0)\n"
5162                "#endif\n"
5163                "{\n"
5164                "}");
5165   verifyFormat("void f() {\n"
5166                "  if (true)\n"
5167                "#ifdef A\n"
5168                "    f(42);\n"
5169                "  x();\n"
5170                "#else\n"
5171                "    g();\n"
5172                "  x();\n"
5173                "#endif\n"
5174                "}");
5175   verifyFormat("void f(param1, param2,\n"
5176                "       param3,\n"
5177                "#ifdef A\n"
5178                "       param4(param5,\n"
5179                "#ifdef A1\n"
5180                "              param6,\n"
5181                "#ifdef A2\n"
5182                "              param7),\n"
5183                "#else\n"
5184                "              param8),\n"
5185                "       param9,\n"
5186                "#endif\n"
5187                "       param10,\n"
5188                "#endif\n"
5189                "       param11)\n"
5190                "#else\n"
5191                "       param12)\n"
5192                "#endif\n"
5193                "{\n"
5194                "  x();\n"
5195                "}",
5196                getLLVMStyleWithColumns(28));
5197   verifyFormat("#if 1\n"
5198                "int i;");
5199   verifyFormat("#if 1\n"
5200                "#endif\n"
5201                "#if 1\n"
5202                "#else\n"
5203                "#endif\n");
5204   verifyFormat("DEBUG({\n"
5205                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5206                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5207                "});\n"
5208                "#if a\n"
5209                "#else\n"
5210                "#endif");
5211 
5212   verifyIncompleteFormat("void f(\n"
5213                          "#if A\n"
5214                          ");\n"
5215                          "#else\n"
5216                          "#endif");
5217 }
5218 
5219 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5220   verifyFormat("#endif\n"
5221                "#if B");
5222 }
5223 
5224 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5225   FormatStyle SingleLine = getLLVMStyle();
5226   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5227   verifyFormat("#if 0\n"
5228                "#elif 1\n"
5229                "#endif\n"
5230                "void foo() {\n"
5231                "  if (test) foo2();\n"
5232                "}",
5233                SingleLine);
5234 }
5235 
5236 TEST_F(FormatTest, LayoutBlockInsideParens) {
5237   verifyFormat("functionCall({ int i; });");
5238   verifyFormat("functionCall({\n"
5239                "  int i;\n"
5240                "  int j;\n"
5241                "});");
5242   verifyFormat("functionCall(\n"
5243                "    {\n"
5244                "      int i;\n"
5245                "      int j;\n"
5246                "    },\n"
5247                "    aaaa, bbbb, cccc);");
5248   verifyFormat("functionA(functionB({\n"
5249                "            int i;\n"
5250                "            int j;\n"
5251                "          }),\n"
5252                "          aaaa, bbbb, cccc);");
5253   verifyFormat("functionCall(\n"
5254                "    {\n"
5255                "      int i;\n"
5256                "      int j;\n"
5257                "    },\n"
5258                "    aaaa, bbbb, // comment\n"
5259                "    cccc);");
5260   verifyFormat("functionA(functionB({\n"
5261                "            int i;\n"
5262                "            int j;\n"
5263                "          }),\n"
5264                "          aaaa, bbbb, // comment\n"
5265                "          cccc);");
5266   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5267   verifyFormat("functionCall(aaaa, bbbb, {\n"
5268                "  int i;\n"
5269                "  int j;\n"
5270                "});");
5271   verifyFormat(
5272       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5273       "    {\n"
5274       "      int i; // break\n"
5275       "    },\n"
5276       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5277       "                                     ccccccccccccccccc));");
5278   verifyFormat("DEBUG({\n"
5279                "  if (a)\n"
5280                "    f();\n"
5281                "});");
5282 }
5283 
5284 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5285   EXPECT_EQ("SOME_MACRO { int i; }\n"
5286             "int i;",
5287             format("  SOME_MACRO  {int i;}  int i;"));
5288 }
5289 
5290 TEST_F(FormatTest, LayoutNestedBlocks) {
5291   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5292                "  struct s {\n"
5293                "    int i;\n"
5294                "  };\n"
5295                "  s kBitsToOs[] = {{10}};\n"
5296                "  for (int i = 0; i < 10; ++i)\n"
5297                "    return;\n"
5298                "}");
5299   verifyFormat("call(parameter, {\n"
5300                "  something();\n"
5301                "  // Comment using all columns.\n"
5302                "  somethingelse();\n"
5303                "});",
5304                getLLVMStyleWithColumns(40));
5305   verifyFormat("DEBUG( //\n"
5306                "    { f(); }, a);");
5307   verifyFormat("DEBUG( //\n"
5308                "    {\n"
5309                "      f(); //\n"
5310                "    },\n"
5311                "    a);");
5312 
5313   EXPECT_EQ("call(parameter, {\n"
5314             "  something();\n"
5315             "  // Comment too\n"
5316             "  // looooooooooong.\n"
5317             "  somethingElse();\n"
5318             "});",
5319             format("call(parameter, {\n"
5320                    "  something();\n"
5321                    "  // Comment too looooooooooong.\n"
5322                    "  somethingElse();\n"
5323                    "});",
5324                    getLLVMStyleWithColumns(29)));
5325   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5326   EXPECT_EQ("DEBUG({ // comment\n"
5327             "  int i;\n"
5328             "});",
5329             format("DEBUG({ // comment\n"
5330                    "int  i;\n"
5331                    "});"));
5332   EXPECT_EQ("DEBUG({\n"
5333             "  int i;\n"
5334             "\n"
5335             "  // comment\n"
5336             "  int j;\n"
5337             "});",
5338             format("DEBUG({\n"
5339                    "  int  i;\n"
5340                    "\n"
5341                    "  // comment\n"
5342                    "  int  j;\n"
5343                    "});"));
5344 
5345   verifyFormat("DEBUG({\n"
5346                "  if (a)\n"
5347                "    return;\n"
5348                "});");
5349   verifyGoogleFormat("DEBUG({\n"
5350                      "  if (a) return;\n"
5351                      "});");
5352   FormatStyle Style = getGoogleStyle();
5353   Style.ColumnLimit = 45;
5354   verifyFormat("Debug(\n"
5355                "    aaaaa,\n"
5356                "    {\n"
5357                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5358                "    },\n"
5359                "    a);",
5360                Style);
5361 
5362   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5363 
5364   verifyNoCrash("^{v^{a}}");
5365 }
5366 
5367 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
5368   EXPECT_EQ("#define MACRO()                     \\\n"
5369             "  Debug(aaa, /* force line break */ \\\n"
5370             "        {                           \\\n"
5371             "          int i;                    \\\n"
5372             "          int j;                    \\\n"
5373             "        })",
5374             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
5375                    "          {  int   i;  int  j;   })",
5376                    getGoogleStyle()));
5377 
5378   EXPECT_EQ("#define A                                       \\\n"
5379             "  [] {                                          \\\n"
5380             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
5381             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
5382             "  }",
5383             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5384                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
5385                    getGoogleStyle()));
5386 }
5387 
5388 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
5389   EXPECT_EQ("{}", format("{}"));
5390   verifyFormat("enum E {};");
5391   verifyFormat("enum E {}");
5392   FormatStyle Style = getLLVMStyle();
5393   Style.SpaceInEmptyBlock = true;
5394   EXPECT_EQ("void f() { }", format("void f() {}", Style));
5395   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
5396   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
5397 }
5398 
5399 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
5400   FormatStyle Style = getLLVMStyle();
5401   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
5402   Style.MacroBlockEnd = "^[A-Z_]+_END$";
5403   verifyFormat("FOO_BEGIN\n"
5404                "  FOO_ENTRY\n"
5405                "FOO_END",
5406                Style);
5407   verifyFormat("FOO_BEGIN\n"
5408                "  NESTED_FOO_BEGIN\n"
5409                "    NESTED_FOO_ENTRY\n"
5410                "  NESTED_FOO_END\n"
5411                "FOO_END",
5412                Style);
5413   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
5414                "  int x;\n"
5415                "  x = 1;\n"
5416                "FOO_END(Baz)",
5417                Style);
5418 }
5419 
5420 //===----------------------------------------------------------------------===//
5421 // Line break tests.
5422 //===----------------------------------------------------------------------===//
5423 
5424 TEST_F(FormatTest, PreventConfusingIndents) {
5425   verifyFormat(
5426       "void f() {\n"
5427       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
5428       "                         parameter, parameter, parameter)),\n"
5429       "                     SecondLongCall(parameter));\n"
5430       "}");
5431   verifyFormat(
5432       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5433       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5434       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5435       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
5436   verifyFormat(
5437       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5438       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
5439       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5440       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
5441   verifyFormat(
5442       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5443       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
5444       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
5445       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
5446   verifyFormat("int a = bbbb && ccc &&\n"
5447                "        fffff(\n"
5448                "#define A Just forcing a new line\n"
5449                "            ddd);");
5450 }
5451 
5452 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
5453   verifyFormat(
5454       "bool aaaaaaa =\n"
5455       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
5456       "    bbbbbbbb();");
5457   verifyFormat(
5458       "bool aaaaaaa =\n"
5459       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
5460       "    bbbbbbbb();");
5461 
5462   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5463                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
5464                "    ccccccccc == ddddddddddd;");
5465   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5466                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
5467                "    ccccccccc == ddddddddddd;");
5468   verifyFormat(
5469       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
5470       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
5471       "    ccccccccc == ddddddddddd;");
5472 
5473   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5474                "                 aaaaaa) &&\n"
5475                "         bbbbbb && cccccc;");
5476   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5477                "                 aaaaaa) >>\n"
5478                "         bbbbbb;");
5479   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
5480                "    SourceMgr.getSpellingColumnNumber(\n"
5481                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
5482                "    1);");
5483 
5484   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5485                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
5486                "    cccccc) {\n}");
5487   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5488                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5489                "              cccccc) {\n}");
5490   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5491                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5492                "              cccccc) {\n}");
5493   verifyFormat("b = a &&\n"
5494                "    // Comment\n"
5495                "    b.c && d;");
5496 
5497   // If the LHS of a comparison is not a binary expression itself, the
5498   // additional linebreak confuses many people.
5499   verifyFormat(
5500       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5501       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
5502       "}");
5503   verifyFormat(
5504       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5505       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5506       "}");
5507   verifyFormat(
5508       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
5509       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5510       "}");
5511   verifyFormat(
5512       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5513       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
5514       "}");
5515   // Even explicit parentheses stress the precedence enough to make the
5516   // additional break unnecessary.
5517   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5518                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5519                "}");
5520   // This cases is borderline, but with the indentation it is still readable.
5521   verifyFormat(
5522       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5523       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5524       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
5525       "}",
5526       getLLVMStyleWithColumns(75));
5527 
5528   // If the LHS is a binary expression, we should still use the additional break
5529   // as otherwise the formatting hides the operator precedence.
5530   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5531                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5532                "    5) {\n"
5533                "}");
5534   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5535                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
5536                "    5) {\n"
5537                "}");
5538 
5539   FormatStyle OnePerLine = getLLVMStyle();
5540   OnePerLine.BinPackParameters = false;
5541   verifyFormat(
5542       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5543       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5544       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
5545       OnePerLine);
5546 
5547   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
5548                "                .aaa(aaaaaaaaaaaaa) *\n"
5549                "            aaaaaaa +\n"
5550                "        aaaaaaa;",
5551                getLLVMStyleWithColumns(40));
5552 }
5553 
5554 TEST_F(FormatTest, ExpressionIndentation) {
5555   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5556                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5557                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5558                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5559                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
5560                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
5561                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5562                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
5563                "                 ccccccccccccccccccccccccccccccccccccccccc;");
5564   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5565                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5566                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5567                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5568   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5569                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5570                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5571                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5572   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5573                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5574                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5575                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5576   verifyFormat("if () {\n"
5577                "} else if (aaaaa && bbbbb > // break\n"
5578                "                        ccccc) {\n"
5579                "}");
5580   verifyFormat("if () {\n"
5581                "} else if constexpr (aaaaa && bbbbb > // break\n"
5582                "                                  ccccc) {\n"
5583                "}");
5584   verifyFormat("if () {\n"
5585                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
5586                "                                  ccccc) {\n"
5587                "}");
5588   verifyFormat("if () {\n"
5589                "} else if (aaaaa &&\n"
5590                "           bbbbb > // break\n"
5591                "               ccccc &&\n"
5592                "           ddddd) {\n"
5593                "}");
5594 
5595   // Presence of a trailing comment used to change indentation of b.
5596   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
5597                "       b;\n"
5598                "return aaaaaaaaaaaaaaaaaaa +\n"
5599                "       b; //",
5600                getLLVMStyleWithColumns(30));
5601 }
5602 
5603 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
5604   // Not sure what the best system is here. Like this, the LHS can be found
5605   // immediately above an operator (everything with the same or a higher
5606   // indent). The RHS is aligned right of the operator and so compasses
5607   // everything until something with the same indent as the operator is found.
5608   // FIXME: Is this a good system?
5609   FormatStyle Style = getLLVMStyle();
5610   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5611   verifyFormat(
5612       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5613       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5614       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5615       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5616       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5617       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5618       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5619       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5620       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
5621       Style);
5622   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5623                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5624                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5625                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5626                Style);
5627   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5628                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5629                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5630                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5631                Style);
5632   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5633                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5634                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5635                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5636                Style);
5637   verifyFormat("if () {\n"
5638                "} else if (aaaaa\n"
5639                "           && bbbbb // break\n"
5640                "                  > ccccc) {\n"
5641                "}",
5642                Style);
5643   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5644                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5645                Style);
5646   verifyFormat("return (a)\n"
5647                "       // comment\n"
5648                "       + b;",
5649                Style);
5650   verifyFormat(
5651       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5652       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5653       "             + cc;",
5654       Style);
5655 
5656   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5657                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5658                Style);
5659 
5660   // Forced by comments.
5661   verifyFormat(
5662       "unsigned ContentSize =\n"
5663       "    sizeof(int16_t)   // DWARF ARange version number\n"
5664       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5665       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5666       "    + sizeof(int8_t); // Segment Size (in bytes)");
5667 
5668   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5669                "       == boost::fusion::at_c<1>(iiii).second;",
5670                Style);
5671 
5672   Style.ColumnLimit = 60;
5673   verifyFormat("zzzzzzzzzz\n"
5674                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5675                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5676                Style);
5677 
5678   Style.ColumnLimit = 80;
5679   Style.IndentWidth = 4;
5680   Style.TabWidth = 4;
5681   Style.UseTab = FormatStyle::UT_Always;
5682   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5683   Style.AlignOperands = FormatStyle::OAS_DontAlign;
5684   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
5685             "\t&& (someOtherLongishConditionPart1\n"
5686             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
5687             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
5688                    "(someOtherLongishConditionPart1 || "
5689                    "someOtherEvenLongerNestedConditionPart2);",
5690                    Style));
5691 }
5692 
5693 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
5694   FormatStyle Style = getLLVMStyle();
5695   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5696   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
5697 
5698   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5699                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5700                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5701                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5702                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5703                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5704                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5705                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5706                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
5707                Style);
5708   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5709                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5710                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5711                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5712                Style);
5713   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5714                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5715                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5716                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5717                Style);
5718   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5719                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5720                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5721                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5722                Style);
5723   verifyFormat("if () {\n"
5724                "} else if (aaaaa\n"
5725                "           && bbbbb // break\n"
5726                "                  > ccccc) {\n"
5727                "}",
5728                Style);
5729   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5730                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5731                Style);
5732   verifyFormat("return (a)\n"
5733                "     // comment\n"
5734                "     + b;",
5735                Style);
5736   verifyFormat(
5737       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5738       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5739       "           + cc;",
5740       Style);
5741   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
5742                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
5743                "                        : 3333333333333333;",
5744                Style);
5745   verifyFormat(
5746       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
5747       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
5748       "                                             : eeeeeeeeeeeeeeeeee)\n"
5749       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
5750       "                        : 3333333333333333;",
5751       Style);
5752   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5753                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5754                Style);
5755 
5756   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5757                "    == boost::fusion::at_c<1>(iiii).second;",
5758                Style);
5759 
5760   Style.ColumnLimit = 60;
5761   verifyFormat("zzzzzzzzzzzzz\n"
5762                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5763                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5764                Style);
5765 
5766   // Forced by comments.
5767   Style.ColumnLimit = 80;
5768   verifyFormat(
5769       "unsigned ContentSize\n"
5770       "    = sizeof(int16_t) // DWARF ARange version number\n"
5771       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5772       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5773       "    + sizeof(int8_t); // Segment Size (in bytes)",
5774       Style);
5775 
5776   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5777   verifyFormat(
5778       "unsigned ContentSize =\n"
5779       "    sizeof(int16_t)   // DWARF ARange version number\n"
5780       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5781       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5782       "    + sizeof(int8_t); // Segment Size (in bytes)",
5783       Style);
5784 
5785   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
5786   verifyFormat(
5787       "unsigned ContentSize =\n"
5788       "    sizeof(int16_t)   // DWARF ARange version number\n"
5789       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5790       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5791       "    + sizeof(int8_t); // Segment Size (in bytes)",
5792       Style);
5793 }
5794 
5795 TEST_F(FormatTest, EnforcedOperatorWraps) {
5796   // Here we'd like to wrap after the || operators, but a comment is forcing an
5797   // earlier wrap.
5798   verifyFormat("bool x = aaaaa //\n"
5799                "         || bbbbb\n"
5800                "         //\n"
5801                "         || cccc;");
5802 }
5803 
5804 TEST_F(FormatTest, NoOperandAlignment) {
5805   FormatStyle Style = getLLVMStyle();
5806   Style.AlignOperands = FormatStyle::OAS_DontAlign;
5807   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
5808                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5809                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5810                Style);
5811   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5812   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5813                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5814                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5815                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5816                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5817                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5818                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5819                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5820                "        > ccccccccccccccccccccccccccccccccccccccccc;",
5821                Style);
5822 
5823   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5824                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5825                "    + cc;",
5826                Style);
5827   verifyFormat("int a = aa\n"
5828                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5829                "        * cccccccccccccccccccccccccccccccccccc;\n",
5830                Style);
5831 
5832   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5833   verifyFormat("return (a > b\n"
5834                "    // comment1\n"
5835                "    // comment2\n"
5836                "    || c);",
5837                Style);
5838 }
5839 
5840 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
5841   FormatStyle Style = getLLVMStyle();
5842   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5843   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5844                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5845                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5846                Style);
5847 }
5848 
5849 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
5850   FormatStyle Style = getLLVMStyle();
5851   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5852   Style.BinPackArguments = false;
5853   Style.ColumnLimit = 40;
5854   verifyFormat("void test() {\n"
5855                "  someFunction(\n"
5856                "      this + argument + is + quite\n"
5857                "      + long + so + it + gets + wrapped\n"
5858                "      + but + remains + bin - packed);\n"
5859                "}",
5860                Style);
5861   verifyFormat("void test() {\n"
5862                "  someFunction(arg1,\n"
5863                "               this + argument + is\n"
5864                "                   + quite + long + so\n"
5865                "                   + it + gets + wrapped\n"
5866                "                   + but + remains + bin\n"
5867                "                   - packed,\n"
5868                "               arg3);\n"
5869                "}",
5870                Style);
5871   verifyFormat("void test() {\n"
5872                "  someFunction(\n"
5873                "      arg1,\n"
5874                "      this + argument + has\n"
5875                "          + anotherFunc(nested,\n"
5876                "                        calls + whose\n"
5877                "                            + arguments\n"
5878                "                            + are + also\n"
5879                "                            + wrapped,\n"
5880                "                        in + addition)\n"
5881                "          + to + being + bin - packed,\n"
5882                "      arg3);\n"
5883                "}",
5884                Style);
5885 
5886   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
5887   verifyFormat("void test() {\n"
5888                "  someFunction(\n"
5889                "      arg1,\n"
5890                "      this + argument + has +\n"
5891                "          anotherFunc(nested,\n"
5892                "                      calls + whose +\n"
5893                "                          arguments +\n"
5894                "                          are + also +\n"
5895                "                          wrapped,\n"
5896                "                      in + addition) +\n"
5897                "          to + being + bin - packed,\n"
5898                "      arg3);\n"
5899                "}",
5900                Style);
5901 }
5902 
5903 TEST_F(FormatTest, ConstructorInitializers) {
5904   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
5905   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
5906                getLLVMStyleWithColumns(45));
5907   verifyFormat("Constructor()\n"
5908                "    : Inttializer(FitsOnTheLine) {}",
5909                getLLVMStyleWithColumns(44));
5910   verifyFormat("Constructor()\n"
5911                "    : Inttializer(FitsOnTheLine) {}",
5912                getLLVMStyleWithColumns(43));
5913 
5914   verifyFormat("template <typename T>\n"
5915                "Constructor() : Initializer(FitsOnTheLine) {}",
5916                getLLVMStyleWithColumns(45));
5917 
5918   verifyFormat(
5919       "SomeClass::Constructor()\n"
5920       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
5921 
5922   verifyFormat(
5923       "SomeClass::Constructor()\n"
5924       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5925       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
5926   verifyFormat(
5927       "SomeClass::Constructor()\n"
5928       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5929       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
5930   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5931                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5932                "    : aaaaaaaaaa(aaaaaa) {}");
5933 
5934   verifyFormat("Constructor()\n"
5935                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5936                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5937                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5938                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
5939 
5940   verifyFormat("Constructor()\n"
5941                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5942                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5943 
5944   verifyFormat("Constructor(int Parameter = 0)\n"
5945                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
5946                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
5947   verifyFormat("Constructor()\n"
5948                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
5949                "}",
5950                getLLVMStyleWithColumns(60));
5951   verifyFormat("Constructor()\n"
5952                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5953                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
5954 
5955   // Here a line could be saved by splitting the second initializer onto two
5956   // lines, but that is not desirable.
5957   verifyFormat("Constructor()\n"
5958                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
5959                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
5960                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5961 
5962   FormatStyle OnePerLine = getLLVMStyle();
5963   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
5964   verifyFormat("MyClass::MyClass()\n"
5965                "    : a(a),\n"
5966                "      b(b),\n"
5967                "      c(c) {}",
5968                OnePerLine);
5969   verifyFormat("MyClass::MyClass()\n"
5970                "    : a(a), // comment\n"
5971                "      b(b),\n"
5972                "      c(c) {}",
5973                OnePerLine);
5974   verifyFormat("MyClass::MyClass(int a)\n"
5975                "    : b(a),      // comment\n"
5976                "      c(a + 1) { // lined up\n"
5977                "}",
5978                OnePerLine);
5979   verifyFormat("Constructor()\n"
5980                "    : a(b, b, b) {}",
5981                OnePerLine);
5982   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
5983   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
5984   verifyFormat("SomeClass::Constructor()\n"
5985                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5986                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5987                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5988                OnePerLine);
5989   verifyFormat("SomeClass::Constructor()\n"
5990                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
5991                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5992                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5993                OnePerLine);
5994   verifyFormat("MyClass::MyClass(int var)\n"
5995                "    : some_var_(var),            // 4 space indent\n"
5996                "      some_other_var_(var + 1) { // lined up\n"
5997                "}",
5998                OnePerLine);
5999   verifyFormat("Constructor()\n"
6000                "    : aaaaa(aaaaaa),\n"
6001                "      aaaaa(aaaaaa),\n"
6002                "      aaaaa(aaaaaa),\n"
6003                "      aaaaa(aaaaaa),\n"
6004                "      aaaaa(aaaaaa) {}",
6005                OnePerLine);
6006   verifyFormat("Constructor()\n"
6007                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6008                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6009                OnePerLine);
6010   OnePerLine.BinPackParameters = false;
6011   verifyFormat(
6012       "Constructor()\n"
6013       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6014       "          aaaaaaaaaaa().aaa(),\n"
6015       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6016       OnePerLine);
6017   OnePerLine.ColumnLimit = 60;
6018   verifyFormat("Constructor()\n"
6019                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6020                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6021                OnePerLine);
6022 
6023   EXPECT_EQ("Constructor()\n"
6024             "    : // Comment forcing unwanted break.\n"
6025             "      aaaa(aaaa) {}",
6026             format("Constructor() :\n"
6027                    "    // Comment forcing unwanted break.\n"
6028                    "    aaaa(aaaa) {}"));
6029 }
6030 
6031 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6032   FormatStyle Style = getLLVMStyle();
6033   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6034   Style.ColumnLimit = 60;
6035   Style.BinPackParameters = false;
6036 
6037   for (int i = 0; i < 4; ++i) {
6038     // Test all combinations of parameters that should not have an effect.
6039     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6040     Style.AllowAllArgumentsOnNextLine = i & 2;
6041 
6042     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6043     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6044     verifyFormat("Constructor()\n"
6045                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6046                  Style);
6047     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6048 
6049     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6050     verifyFormat("Constructor()\n"
6051                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6052                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6053                  Style);
6054     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6055 
6056     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6057     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6058     verifyFormat("Constructor()\n"
6059                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6060                  Style);
6061 
6062     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6063     verifyFormat("Constructor()\n"
6064                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6065                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6066                  Style);
6067 
6068     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6069     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6070     verifyFormat("Constructor() :\n"
6071                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6072                  Style);
6073 
6074     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6075     verifyFormat("Constructor() :\n"
6076                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6077                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6078                  Style);
6079   }
6080 
6081   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6082   // AllowAllConstructorInitializersOnNextLine in all
6083   // BreakConstructorInitializers modes
6084   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6085   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6086   verifyFormat("SomeClassWithALongName::Constructor(\n"
6087                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6088                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6089                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6090                Style);
6091 
6092   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6093   verifyFormat("SomeClassWithALongName::Constructor(\n"
6094                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6095                "    int bbbbbbbbbbbbb,\n"
6096                "    int cccccccccccccccc)\n"
6097                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6098                Style);
6099 
6100   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6101   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6102   verifyFormat("SomeClassWithALongName::Constructor(\n"
6103                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6104                "    int bbbbbbbbbbbbb)\n"
6105                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6106                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6107                Style);
6108 
6109   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6110 
6111   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6112   verifyFormat("SomeClassWithALongName::Constructor(\n"
6113                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6114                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6115                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6116                Style);
6117 
6118   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6119   verifyFormat("SomeClassWithALongName::Constructor(\n"
6120                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6121                "    int bbbbbbbbbbbbb,\n"
6122                "    int cccccccccccccccc)\n"
6123                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6124                Style);
6125 
6126   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6127   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6128   verifyFormat("SomeClassWithALongName::Constructor(\n"
6129                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6130                "    int bbbbbbbbbbbbb)\n"
6131                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6132                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6133                Style);
6134 
6135   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6136   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6137   verifyFormat("SomeClassWithALongName::Constructor(\n"
6138                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6139                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6140                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6141                Style);
6142 
6143   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6144   verifyFormat("SomeClassWithALongName::Constructor(\n"
6145                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6146                "    int bbbbbbbbbbbbb,\n"
6147                "    int cccccccccccccccc) :\n"
6148                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6149                Style);
6150 
6151   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6152   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6153   verifyFormat("SomeClassWithALongName::Constructor(\n"
6154                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6155                "    int bbbbbbbbbbbbb) :\n"
6156                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6157                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6158                Style);
6159 }
6160 
6161 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6162   FormatStyle Style = getLLVMStyle();
6163   Style.ColumnLimit = 60;
6164   Style.BinPackArguments = false;
6165   for (int i = 0; i < 4; ++i) {
6166     // Test all combinations of parameters that should not have an effect.
6167     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6168     Style.PackConstructorInitializers =
6169         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6170 
6171     Style.AllowAllArgumentsOnNextLine = true;
6172     verifyFormat("void foo() {\n"
6173                  "  FunctionCallWithReallyLongName(\n"
6174                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6175                  "}",
6176                  Style);
6177     Style.AllowAllArgumentsOnNextLine = false;
6178     verifyFormat("void foo() {\n"
6179                  "  FunctionCallWithReallyLongName(\n"
6180                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6181                  "      bbbbbbbbbbbb);\n"
6182                  "}",
6183                  Style);
6184 
6185     Style.AllowAllArgumentsOnNextLine = true;
6186     verifyFormat("void foo() {\n"
6187                  "  auto VariableWithReallyLongName = {\n"
6188                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6189                  "}",
6190                  Style);
6191     Style.AllowAllArgumentsOnNextLine = false;
6192     verifyFormat("void foo() {\n"
6193                  "  auto VariableWithReallyLongName = {\n"
6194                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6195                  "      bbbbbbbbbbbb};\n"
6196                  "}",
6197                  Style);
6198   }
6199 
6200   // This parameter should not affect declarations.
6201   Style.BinPackParameters = false;
6202   Style.AllowAllArgumentsOnNextLine = false;
6203   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6204   verifyFormat("void FunctionCallWithReallyLongName(\n"
6205                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6206                Style);
6207   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6208   verifyFormat("void FunctionCallWithReallyLongName(\n"
6209                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6210                "    int bbbbbbbbbbbb);",
6211                Style);
6212 }
6213 
6214 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6215   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6216   // and BAS_Align.
6217   auto Style = getLLVMStyle();
6218   Style.ColumnLimit = 35;
6219   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6220                     "void functionDecl(int A, int B, int C);";
6221   Style.AllowAllArgumentsOnNextLine = false;
6222   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6223   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6224                       "    paramC);\n"
6225                       "void functionDecl(int A, int B,\n"
6226                       "    int C);"),
6227             format(Input, Style));
6228   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6229   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6230                       "             paramC);\n"
6231                       "void functionDecl(int A, int B,\n"
6232                       "                  int C);"),
6233             format(Input, Style));
6234   // However, BAS_AlwaysBreak should take precedence over
6235   // AllowAllArgumentsOnNextLine.
6236   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6237   EXPECT_EQ(StringRef("functionCall(\n"
6238                       "    paramA, paramB, paramC);\n"
6239                       "void functionDecl(\n"
6240                       "    int A, int B, int C);"),
6241             format(Input, Style));
6242 
6243   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6244   // first argument.
6245   Style.AllowAllArgumentsOnNextLine = true;
6246   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6247   EXPECT_EQ(StringRef("functionCall(\n"
6248                       "    paramA, paramB, paramC);\n"
6249                       "void functionDecl(\n"
6250                       "    int A, int B, int C);"),
6251             format(Input, Style));
6252   // It wouldn't fit on one line with aligned parameters so this setting
6253   // doesn't change anything for BAS_Align.
6254   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6255   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6256                       "             paramC);\n"
6257                       "void functionDecl(int A, int B,\n"
6258                       "                  int C);"),
6259             format(Input, Style));
6260   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6261   EXPECT_EQ(StringRef("functionCall(\n"
6262                       "    paramA, paramB, paramC);\n"
6263                       "void functionDecl(\n"
6264                       "    int A, int B, int C);"),
6265             format(Input, Style));
6266 }
6267 
6268 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6269   FormatStyle Style = getLLVMStyle();
6270   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6271 
6272   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6273   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6274                getStyleWithColumns(Style, 45));
6275   verifyFormat("Constructor() :\n"
6276                "    Initializer(FitsOnTheLine) {}",
6277                getStyleWithColumns(Style, 44));
6278   verifyFormat("Constructor() :\n"
6279                "    Initializer(FitsOnTheLine) {}",
6280                getStyleWithColumns(Style, 43));
6281 
6282   verifyFormat("template <typename T>\n"
6283                "Constructor() : Initializer(FitsOnTheLine) {}",
6284                getStyleWithColumns(Style, 50));
6285   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6286   verifyFormat(
6287       "SomeClass::Constructor() :\n"
6288       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6289       Style);
6290 
6291   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6292   verifyFormat(
6293       "SomeClass::Constructor() :\n"
6294       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6295       Style);
6296 
6297   verifyFormat(
6298       "SomeClass::Constructor() :\n"
6299       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6300       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6301       Style);
6302   verifyFormat(
6303       "SomeClass::Constructor() :\n"
6304       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6305       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6306       Style);
6307   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6308                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6309                "    aaaaaaaaaa(aaaaaa) {}",
6310                Style);
6311 
6312   verifyFormat("Constructor() :\n"
6313                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6314                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6315                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6316                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
6317                Style);
6318 
6319   verifyFormat("Constructor() :\n"
6320                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6321                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6322                Style);
6323 
6324   verifyFormat("Constructor(int Parameter = 0) :\n"
6325                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6326                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
6327                Style);
6328   verifyFormat("Constructor() :\n"
6329                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6330                "}",
6331                getStyleWithColumns(Style, 60));
6332   verifyFormat("Constructor() :\n"
6333                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6334                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
6335                Style);
6336 
6337   // Here a line could be saved by splitting the second initializer onto two
6338   // lines, but that is not desirable.
6339   verifyFormat("Constructor() :\n"
6340                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6341                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
6342                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6343                Style);
6344 
6345   FormatStyle OnePerLine = Style;
6346   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6347   verifyFormat("SomeClass::Constructor() :\n"
6348                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6349                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6350                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6351                OnePerLine);
6352   verifyFormat("SomeClass::Constructor() :\n"
6353                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6354                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6355                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6356                OnePerLine);
6357   verifyFormat("MyClass::MyClass(int var) :\n"
6358                "    some_var_(var),            // 4 space indent\n"
6359                "    some_other_var_(var + 1) { // lined up\n"
6360                "}",
6361                OnePerLine);
6362   verifyFormat("Constructor() :\n"
6363                "    aaaaa(aaaaaa),\n"
6364                "    aaaaa(aaaaaa),\n"
6365                "    aaaaa(aaaaaa),\n"
6366                "    aaaaa(aaaaaa),\n"
6367                "    aaaaa(aaaaaa) {}",
6368                OnePerLine);
6369   verifyFormat("Constructor() :\n"
6370                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6371                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
6372                OnePerLine);
6373   OnePerLine.BinPackParameters = false;
6374   verifyFormat("Constructor() :\n"
6375                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6376                "        aaaaaaaaaaa().aaa(),\n"
6377                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6378                OnePerLine);
6379   OnePerLine.ColumnLimit = 60;
6380   verifyFormat("Constructor() :\n"
6381                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6382                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6383                OnePerLine);
6384 
6385   EXPECT_EQ("Constructor() :\n"
6386             "    // Comment forcing unwanted break.\n"
6387             "    aaaa(aaaa) {}",
6388             format("Constructor() :\n"
6389                    "    // Comment forcing unwanted break.\n"
6390                    "    aaaa(aaaa) {}",
6391                    Style));
6392 
6393   Style.ColumnLimit = 0;
6394   verifyFormat("SomeClass::Constructor() :\n"
6395                "    a(a) {}",
6396                Style);
6397   verifyFormat("SomeClass::Constructor() noexcept :\n"
6398                "    a(a) {}",
6399                Style);
6400   verifyFormat("SomeClass::Constructor() :\n"
6401                "    a(a), b(b), c(c) {}",
6402                Style);
6403   verifyFormat("SomeClass::Constructor() :\n"
6404                "    a(a) {\n"
6405                "  foo();\n"
6406                "  bar();\n"
6407                "}",
6408                Style);
6409 
6410   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6411   verifyFormat("SomeClass::Constructor() :\n"
6412                "    a(a), b(b), c(c) {\n"
6413                "}",
6414                Style);
6415   verifyFormat("SomeClass::Constructor() :\n"
6416                "    a(a) {\n"
6417                "}",
6418                Style);
6419 
6420   Style.ColumnLimit = 80;
6421   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
6422   Style.ConstructorInitializerIndentWidth = 2;
6423   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
6424   verifyFormat("SomeClass::Constructor() :\n"
6425                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6426                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
6427                Style);
6428 
6429   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
6430   // well
6431   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
6432   verifyFormat(
6433       "class SomeClass\n"
6434       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6435       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6436       Style);
6437   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
6438   verifyFormat(
6439       "class SomeClass\n"
6440       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6441       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6442       Style);
6443   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
6444   verifyFormat(
6445       "class SomeClass :\n"
6446       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6447       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6448       Style);
6449   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
6450   verifyFormat(
6451       "class SomeClass\n"
6452       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6453       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6454       Style);
6455 }
6456 
6457 #ifndef EXPENSIVE_CHECKS
6458 // Expensive checks enables libstdc++ checking which includes validating the
6459 // state of ranges used in std::priority_queue - this blows out the
6460 // runtime/scalability of the function and makes this test unacceptably slow.
6461 TEST_F(FormatTest, MemoizationTests) {
6462   // This breaks if the memoization lookup does not take \c Indent and
6463   // \c LastSpace into account.
6464   verifyFormat(
6465       "extern CFRunLoopTimerRef\n"
6466       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
6467       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
6468       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
6469       "                     CFRunLoopTimerContext *context) {}");
6470 
6471   // Deep nesting somewhat works around our memoization.
6472   verifyFormat(
6473       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6474       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6475       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6476       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6477       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
6478       getLLVMStyleWithColumns(65));
6479   verifyFormat(
6480       "aaaaa(\n"
6481       "    aaaaa,\n"
6482       "    aaaaa(\n"
6483       "        aaaaa,\n"
6484       "        aaaaa(\n"
6485       "            aaaaa,\n"
6486       "            aaaaa(\n"
6487       "                aaaaa,\n"
6488       "                aaaaa(\n"
6489       "                    aaaaa,\n"
6490       "                    aaaaa(\n"
6491       "                        aaaaa,\n"
6492       "                        aaaaa(\n"
6493       "                            aaaaa,\n"
6494       "                            aaaaa(\n"
6495       "                                aaaaa,\n"
6496       "                                aaaaa(\n"
6497       "                                    aaaaa,\n"
6498       "                                    aaaaa(\n"
6499       "                                        aaaaa,\n"
6500       "                                        aaaaa(\n"
6501       "                                            aaaaa,\n"
6502       "                                            aaaaa(\n"
6503       "                                                aaaaa,\n"
6504       "                                                aaaaa))))))))))));",
6505       getLLVMStyleWithColumns(65));
6506   verifyFormat(
6507       "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"
6508       "                                  a),\n"
6509       "                                a),\n"
6510       "                              a),\n"
6511       "                            a),\n"
6512       "                          a),\n"
6513       "                        a),\n"
6514       "                      a),\n"
6515       "                    a),\n"
6516       "                  a),\n"
6517       "                a),\n"
6518       "              a),\n"
6519       "            a),\n"
6520       "          a),\n"
6521       "        a),\n"
6522       "      a),\n"
6523       "    a),\n"
6524       "  a)",
6525       getLLVMStyleWithColumns(65));
6526 
6527   // This test takes VERY long when memoization is broken.
6528   FormatStyle OnePerLine = getLLVMStyle();
6529   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6530   OnePerLine.BinPackParameters = false;
6531   std::string input = "Constructor()\n"
6532                       "    : aaaa(a,\n";
6533   for (unsigned i = 0, e = 80; i != e; ++i) {
6534     input += "           a,\n";
6535   }
6536   input += "           a) {}";
6537   verifyFormat(input, OnePerLine);
6538 }
6539 #endif
6540 
6541 TEST_F(FormatTest, BreaksAsHighAsPossible) {
6542   verifyFormat(
6543       "void f() {\n"
6544       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
6545       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
6546       "    f();\n"
6547       "}");
6548   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
6549                "    Intervals[i - 1].getRange().getLast()) {\n}");
6550 }
6551 
6552 TEST_F(FormatTest, BreaksFunctionDeclarations) {
6553   // Principially, we break function declarations in a certain order:
6554   // 1) break amongst arguments.
6555   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
6556                "                              Cccccccccccccc cccccccccccccc);");
6557   verifyFormat("template <class TemplateIt>\n"
6558                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
6559                "                            TemplateIt *stop) {}");
6560 
6561   // 2) break after return type.
6562   verifyFormat(
6563       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6564       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
6565       getGoogleStyle());
6566 
6567   // 3) break after (.
6568   verifyFormat(
6569       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
6570       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
6571       getGoogleStyle());
6572 
6573   // 4) break before after nested name specifiers.
6574   verifyFormat(
6575       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6576       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
6577       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
6578       getGoogleStyle());
6579 
6580   // However, there are exceptions, if a sufficient amount of lines can be
6581   // saved.
6582   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
6583   // more adjusting.
6584   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6585                "                                  Cccccccccccccc cccccccccc,\n"
6586                "                                  Cccccccccccccc cccccccccc,\n"
6587                "                                  Cccccccccccccc cccccccccc,\n"
6588                "                                  Cccccccccccccc cccccccccc);");
6589   verifyFormat(
6590       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6591       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6592       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6593       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
6594       getGoogleStyle());
6595   verifyFormat(
6596       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6597       "                                          Cccccccccccccc cccccccccc,\n"
6598       "                                          Cccccccccccccc cccccccccc,\n"
6599       "                                          Cccccccccccccc cccccccccc,\n"
6600       "                                          Cccccccccccccc cccccccccc,\n"
6601       "                                          Cccccccccccccc cccccccccc,\n"
6602       "                                          Cccccccccccccc cccccccccc);");
6603   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6604                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6605                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6606                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6607                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
6608 
6609   // Break after multi-line parameters.
6610   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6611                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6612                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6613                "    bbbb bbbb);");
6614   verifyFormat("void SomeLoooooooooooongFunction(\n"
6615                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6616                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6617                "    int bbbbbbbbbbbbb);");
6618 
6619   // Treat overloaded operators like other functions.
6620   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6621                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
6622   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6623                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
6624   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6625                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
6626   verifyGoogleFormat(
6627       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
6628       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6629   verifyGoogleFormat(
6630       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
6631       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6632   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6633                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6634   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
6635                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6636   verifyGoogleFormat(
6637       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
6638       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6639       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
6640   verifyGoogleFormat("template <typename T>\n"
6641                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6642                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
6643                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
6644 
6645   FormatStyle Style = getLLVMStyle();
6646   Style.PointerAlignment = FormatStyle::PAS_Left;
6647   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6648                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
6649                Style);
6650   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
6651                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6652                Style);
6653 }
6654 
6655 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
6656   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
6657   // Prefer keeping `::` followed by `operator` together.
6658   EXPECT_EQ("const aaaa::bbbbbbb &\n"
6659             "ccccccccc::operator++() {\n"
6660             "  stuff();\n"
6661             "}",
6662             format("const aaaa::bbbbbbb\n"
6663                    "&ccccccccc::operator++() { stuff(); }",
6664                    getLLVMStyleWithColumns(40)));
6665 }
6666 
6667 TEST_F(FormatTest, TrailingReturnType) {
6668   verifyFormat("auto foo() -> int;\n");
6669   // correct trailing return type spacing
6670   verifyFormat("auto operator->() -> int;\n");
6671   verifyFormat("auto operator++(int) -> int;\n");
6672 
6673   verifyFormat("struct S {\n"
6674                "  auto bar() const -> int;\n"
6675                "};");
6676   verifyFormat("template <size_t Order, typename T>\n"
6677                "auto load_img(const std::string &filename)\n"
6678                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
6679   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
6680                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
6681   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
6682   verifyFormat("template <typename T>\n"
6683                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
6684                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
6685 
6686   // Not trailing return types.
6687   verifyFormat("void f() { auto a = b->c(); }");
6688 }
6689 
6690 TEST_F(FormatTest, DeductionGuides) {
6691   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
6692   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
6693   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
6694   verifyFormat(
6695       "template <class... T>\n"
6696       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
6697   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
6698   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
6699   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
6700   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
6701   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
6702   verifyFormat("template <class T> x() -> x<1>;");
6703   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
6704 
6705   // Ensure not deduction guides.
6706   verifyFormat("c()->f<int>();");
6707   verifyFormat("x()->foo<1>;");
6708   verifyFormat("x = p->foo<3>();");
6709   verifyFormat("x()->x<1>();");
6710   verifyFormat("x()->x<1>;");
6711 }
6712 
6713 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
6714   // Avoid breaking before trailing 'const' or other trailing annotations, if
6715   // they are not function-like.
6716   FormatStyle Style = getGoogleStyle();
6717   Style.ColumnLimit = 47;
6718   verifyFormat("void someLongFunction(\n"
6719                "    int someLoooooooooooooongParameter) const {\n}",
6720                getLLVMStyleWithColumns(47));
6721   verifyFormat("LoooooongReturnType\n"
6722                "someLoooooooongFunction() const {}",
6723                getLLVMStyleWithColumns(47));
6724   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
6725                "    const {}",
6726                Style);
6727   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6728                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
6729   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6730                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
6731   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6732                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
6733   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
6734                "                   aaaaaaaaaaa aaaaa) const override;");
6735   verifyGoogleFormat(
6736       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6737       "    const override;");
6738 
6739   // Even if the first parameter has to be wrapped.
6740   verifyFormat("void someLongFunction(\n"
6741                "    int someLongParameter) const {}",
6742                getLLVMStyleWithColumns(46));
6743   verifyFormat("void someLongFunction(\n"
6744                "    int someLongParameter) const {}",
6745                Style);
6746   verifyFormat("void someLongFunction(\n"
6747                "    int someLongParameter) override {}",
6748                Style);
6749   verifyFormat("void someLongFunction(\n"
6750                "    int someLongParameter) OVERRIDE {}",
6751                Style);
6752   verifyFormat("void someLongFunction(\n"
6753                "    int someLongParameter) final {}",
6754                Style);
6755   verifyFormat("void someLongFunction(\n"
6756                "    int someLongParameter) FINAL {}",
6757                Style);
6758   verifyFormat("void someLongFunction(\n"
6759                "    int parameter) const override {}",
6760                Style);
6761 
6762   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
6763   verifyFormat("void someLongFunction(\n"
6764                "    int someLongParameter) const\n"
6765                "{\n"
6766                "}",
6767                Style);
6768 
6769   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
6770   verifyFormat("void someLongFunction(\n"
6771                "    int someLongParameter) const\n"
6772                "  {\n"
6773                "  }",
6774                Style);
6775 
6776   // Unless these are unknown annotations.
6777   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
6778                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6779                "    LONG_AND_UGLY_ANNOTATION;");
6780 
6781   // Breaking before function-like trailing annotations is fine to keep them
6782   // close to their arguments.
6783   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6784                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
6785   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
6786                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
6787   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
6788                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
6789   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
6790                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
6791   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
6792 
6793   verifyFormat(
6794       "void aaaaaaaaaaaaaaaaaa()\n"
6795       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
6796       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
6797   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6798                "    __attribute__((unused));");
6799   verifyGoogleFormat(
6800       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6801       "    GUARDED_BY(aaaaaaaaaaaa);");
6802   verifyGoogleFormat(
6803       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6804       "    GUARDED_BY(aaaaaaaaaaaa);");
6805   verifyGoogleFormat(
6806       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6807       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6808   verifyGoogleFormat(
6809       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6810       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
6811 }
6812 
6813 TEST_F(FormatTest, FunctionAnnotations) {
6814   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6815                "int OldFunction(const string &parameter) {}");
6816   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6817                "string OldFunction(const string &parameter) {}");
6818   verifyFormat("template <typename T>\n"
6819                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6820                "string OldFunction(const string &parameter) {}");
6821 
6822   // Not function annotations.
6823   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6824                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
6825   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
6826                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
6827   verifyFormat("MACRO(abc).function() // wrap\n"
6828                "    << abc;");
6829   verifyFormat("MACRO(abc)->function() // wrap\n"
6830                "    << abc;");
6831   verifyFormat("MACRO(abc)::function() // wrap\n"
6832                "    << abc;");
6833 }
6834 
6835 TEST_F(FormatTest, BreaksDesireably) {
6836   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6837                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6838                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
6839   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6840                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
6841                "}");
6842 
6843   verifyFormat(
6844       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6845       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6846 
6847   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6848                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6849                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6850 
6851   verifyFormat(
6852       "aaaaaaaa(aaaaaaaaaaaaa,\n"
6853       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6854       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
6855       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6856       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
6857 
6858   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6859                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6860 
6861   verifyFormat(
6862       "void f() {\n"
6863       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
6864       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
6865       "}");
6866   verifyFormat(
6867       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6868       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6869   verifyFormat(
6870       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6871       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6872   verifyFormat(
6873       "aaaaaa(aaa,\n"
6874       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6875       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6876       "       aaaa);");
6877   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6878                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6879                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6880 
6881   // Indent consistently independent of call expression and unary operator.
6882   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6883                "    dddddddddddddddddddddddddddddd));");
6884   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6885                "    dddddddddddddddddddddddddddddd));");
6886   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
6887                "    dddddddddddddddddddddddddddddd));");
6888 
6889   // This test case breaks on an incorrect memoization, i.e. an optimization not
6890   // taking into account the StopAt value.
6891   verifyFormat(
6892       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6893       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6894       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6895       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6896 
6897   verifyFormat("{\n  {\n    {\n"
6898                "      Annotation.SpaceRequiredBefore =\n"
6899                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
6900                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
6901                "    }\n  }\n}");
6902 
6903   // Break on an outer level if there was a break on an inner level.
6904   EXPECT_EQ("f(g(h(a, // comment\n"
6905             "      b, c),\n"
6906             "    d, e),\n"
6907             "  x, y);",
6908             format("f(g(h(a, // comment\n"
6909                    "    b, c), d, e), x, y);"));
6910 
6911   // Prefer breaking similar line breaks.
6912   verifyFormat(
6913       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
6914       "                             NSTrackingMouseEnteredAndExited |\n"
6915       "                             NSTrackingActiveAlways;");
6916 }
6917 
6918 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
6919   FormatStyle NoBinPacking = getGoogleStyle();
6920   NoBinPacking.BinPackParameters = false;
6921   NoBinPacking.BinPackArguments = true;
6922   verifyFormat("void f() {\n"
6923                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
6924                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
6925                "}",
6926                NoBinPacking);
6927   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
6928                "       int aaaaaaaaaaaaaaaaaaaa,\n"
6929                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6930                NoBinPacking);
6931 
6932   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
6933   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6934                "                        vector<int> bbbbbbbbbbbbbbb);",
6935                NoBinPacking);
6936   // FIXME: This behavior difference is probably not wanted. However, currently
6937   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
6938   // template arguments from BreakBeforeParameter being set because of the
6939   // one-per-line formatting.
6940   verifyFormat(
6941       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
6942       "                                             aaaaaaaaaa> aaaaaaaaaa);",
6943       NoBinPacking);
6944   verifyFormat(
6945       "void fffffffffff(\n"
6946       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
6947       "        aaaaaaaaaa);");
6948 }
6949 
6950 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
6951   FormatStyle NoBinPacking = getGoogleStyle();
6952   NoBinPacking.BinPackParameters = false;
6953   NoBinPacking.BinPackArguments = false;
6954   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
6955                "  aaaaaaaaaaaaaaaaaaaa,\n"
6956                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
6957                NoBinPacking);
6958   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
6959                "        aaaaaaaaaaaaa,\n"
6960                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
6961                NoBinPacking);
6962   verifyFormat(
6963       "aaaaaaaa(aaaaaaaaaaaaa,\n"
6964       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6965       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
6966       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6967       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
6968       NoBinPacking);
6969   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
6970                "    .aaaaaaaaaaaaaaaaaa();",
6971                NoBinPacking);
6972   verifyFormat("void f() {\n"
6973                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6974                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
6975                "}",
6976                NoBinPacking);
6977 
6978   verifyFormat(
6979       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6980       "             aaaaaaaaaaaa,\n"
6981       "             aaaaaaaaaaaa);",
6982       NoBinPacking);
6983   verifyFormat(
6984       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
6985       "                               ddddddddddddddddddddddddddddd),\n"
6986       "             test);",
6987       NoBinPacking);
6988 
6989   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
6990                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
6991                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
6992                "    aaaaaaaaaaaaaaaaaa;",
6993                NoBinPacking);
6994   verifyFormat("a(\"a\"\n"
6995                "  \"a\",\n"
6996                "  a);");
6997 
6998   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
6999   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7000                "                aaaaaaaaa,\n"
7001                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7002                NoBinPacking);
7003   verifyFormat(
7004       "void f() {\n"
7005       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7006       "      .aaaaaaa();\n"
7007       "}",
7008       NoBinPacking);
7009   verifyFormat(
7010       "template <class SomeType, class SomeOtherType>\n"
7011       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7012       NoBinPacking);
7013 }
7014 
7015 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7016   FormatStyle Style = getLLVMStyleWithColumns(15);
7017   Style.ExperimentalAutoDetectBinPacking = true;
7018   EXPECT_EQ("aaa(aaaa,\n"
7019             "    aaaa,\n"
7020             "    aaaa);\n"
7021             "aaa(aaaa,\n"
7022             "    aaaa,\n"
7023             "    aaaa);",
7024             format("aaa(aaaa,\n" // one-per-line
7025                    "  aaaa,\n"
7026                    "    aaaa  );\n"
7027                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7028                    Style));
7029   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7030             "    aaaa);\n"
7031             "aaa(aaaa, aaaa,\n"
7032             "    aaaa);",
7033             format("aaa(aaaa,  aaaa,\n" // bin-packed
7034                    "    aaaa  );\n"
7035                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7036                    Style));
7037 }
7038 
7039 TEST_F(FormatTest, FormatsBuilderPattern) {
7040   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7041                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7042                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7043                "    .StartsWith(\".init\", ORDER_INIT)\n"
7044                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7045                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7046                "    .Default(ORDER_TEXT);\n");
7047 
7048   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7049                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7050   verifyFormat("aaaaaaa->aaaaaaa\n"
7051                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7052                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7053                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7054   verifyFormat(
7055       "aaaaaaa->aaaaaaa\n"
7056       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7057       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7058   verifyFormat(
7059       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7060       "    aaaaaaaaaaaaaa);");
7061   verifyFormat(
7062       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7063       "    aaaaaa->aaaaaaaaaaaa()\n"
7064       "        ->aaaaaaaaaaaaaaaa(\n"
7065       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7066       "        ->aaaaaaaaaaaaaaaaa();");
7067   verifyGoogleFormat(
7068       "void f() {\n"
7069       "  someo->Add((new util::filetools::Handler(dir))\n"
7070       "                 ->OnEvent1(NewPermanentCallback(\n"
7071       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7072       "                 ->OnEvent2(NewPermanentCallback(\n"
7073       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7074       "                 ->OnEvent3(NewPermanentCallback(\n"
7075       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7076       "                 ->OnEvent5(NewPermanentCallback(\n"
7077       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7078       "                 ->OnEvent6(NewPermanentCallback(\n"
7079       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7080       "}");
7081 
7082   verifyFormat(
7083       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7084   verifyFormat("aaaaaaaaaaaaaaa()\n"
7085                "    .aaaaaaaaaaaaaaa()\n"
7086                "    .aaaaaaaaaaaaaaa()\n"
7087                "    .aaaaaaaaaaaaaaa()\n"
7088                "    .aaaaaaaaaaaaaaa();");
7089   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7090                "    .aaaaaaaaaaaaaaa()\n"
7091                "    .aaaaaaaaaaaaaaa()\n"
7092                "    .aaaaaaaaaaaaaaa();");
7093   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7094                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7095                "    .aaaaaaaaaaaaaaa();");
7096   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7097                "    ->aaaaaaaaaaaaaae(0)\n"
7098                "    ->aaaaaaaaaaaaaaa();");
7099 
7100   // Don't linewrap after very short segments.
7101   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7102                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7103                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7104   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7105                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7106                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7107   verifyFormat("aaa()\n"
7108                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7109                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7110                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7111 
7112   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7113                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7114                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7115   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7116                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7117                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7118 
7119   // Prefer not to break after empty parentheses.
7120   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7121                "    First->LastNewlineOffset);");
7122 
7123   // Prefer not to create "hanging" indents.
7124   verifyFormat(
7125       "return !soooooooooooooome_map\n"
7126       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7127       "            .second;");
7128   verifyFormat(
7129       "return aaaaaaaaaaaaaaaa\n"
7130       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7131       "    .aaaa(aaaaaaaaaaaaaa);");
7132   // No hanging indent here.
7133   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7134                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7135   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7136                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7137   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7138                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7139                getLLVMStyleWithColumns(60));
7140   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7141                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7142                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7143                getLLVMStyleWithColumns(59));
7144   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7145                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7146                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7147 
7148   // Dont break if only closing statements before member call
7149   verifyFormat("test() {\n"
7150                "  ([]() -> {\n"
7151                "    int b = 32;\n"
7152                "    return 3;\n"
7153                "  }).foo();\n"
7154                "}");
7155   verifyFormat("test() {\n"
7156                "  (\n"
7157                "      []() -> {\n"
7158                "        int b = 32;\n"
7159                "        return 3;\n"
7160                "      },\n"
7161                "      foo, bar)\n"
7162                "      .foo();\n"
7163                "}");
7164   verifyFormat("test() {\n"
7165                "  ([]() -> {\n"
7166                "    int b = 32;\n"
7167                "    return 3;\n"
7168                "  })\n"
7169                "      .foo()\n"
7170                "      .bar();\n"
7171                "}");
7172   verifyFormat("test() {\n"
7173                "  ([]() -> {\n"
7174                "    int b = 32;\n"
7175                "    return 3;\n"
7176                "  })\n"
7177                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7178                "           \"bbbb\");\n"
7179                "}",
7180                getLLVMStyleWithColumns(30));
7181 }
7182 
7183 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7184   verifyFormat(
7185       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7186       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7187   verifyFormat(
7188       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7189       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7190 
7191   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7192                "    ccccccccccccccccccccccccc) {\n}");
7193   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7194                "    ccccccccccccccccccccccccc) {\n}");
7195 
7196   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7197                "    ccccccccccccccccccccccccc) {\n}");
7198   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7199                "    ccccccccccccccccccccccccc) {\n}");
7200 
7201   verifyFormat(
7202       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7203       "    ccccccccccccccccccccccccc) {\n}");
7204   verifyFormat(
7205       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7206       "    ccccccccccccccccccccccccc) {\n}");
7207 
7208   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7209                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7210                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7211                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7212   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7213                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7214                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7215                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7216 
7217   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7218                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7219                "    aaaaaaaaaaaaaaa != aa) {\n}");
7220   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7221                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7222                "    aaaaaaaaaaaaaaa != aa) {\n}");
7223 }
7224 
7225 TEST_F(FormatTest, BreaksAfterAssignments) {
7226   verifyFormat(
7227       "unsigned Cost =\n"
7228       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7229       "                        SI->getPointerAddressSpaceee());\n");
7230   verifyFormat(
7231       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7232       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7233 
7234   verifyFormat(
7235       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7236       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7237   verifyFormat("unsigned OriginalStartColumn =\n"
7238                "    SourceMgr.getSpellingColumnNumber(\n"
7239                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7240                "    1;");
7241 }
7242 
7243 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7244   FormatStyle Style = getLLVMStyle();
7245   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7246                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7247                Style);
7248 
7249   Style.PenaltyBreakAssignment = 20;
7250   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7251                "                                 cccccccccccccccccccccccccc;",
7252                Style);
7253 }
7254 
7255 TEST_F(FormatTest, AlignsAfterAssignments) {
7256   verifyFormat(
7257       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7258       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7259   verifyFormat(
7260       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7261       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7262   verifyFormat(
7263       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7264       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7265   verifyFormat(
7266       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7267       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7268   verifyFormat(
7269       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7270       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7271       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7272 }
7273 
7274 TEST_F(FormatTest, AlignsAfterReturn) {
7275   verifyFormat(
7276       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7277       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7278   verifyFormat(
7279       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7280       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7281   verifyFormat(
7282       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7283       "       aaaaaaaaaaaaaaaaaaaaaa();");
7284   verifyFormat(
7285       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7286       "        aaaaaaaaaaaaaaaaaaaaaa());");
7287   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7288                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7289   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7290                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7291                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7292   verifyFormat("return\n"
7293                "    // true if code is one of a or b.\n"
7294                "    code == a || code == b;");
7295 }
7296 
7297 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7298   verifyFormat(
7299       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7300       "                                                aaaaaaaaa aaaaaaa) {}");
7301   verifyFormat(
7302       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7303       "                                               aaaaaaaaaaa aaaaaaaaa);");
7304   verifyFormat(
7305       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7306       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7307   FormatStyle Style = getLLVMStyle();
7308   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7309   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7310                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7311                Style);
7312   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7313                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
7314                Style);
7315   verifyFormat("SomeLongVariableName->someFunction(\n"
7316                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
7317                Style);
7318   verifyFormat(
7319       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7320       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7321       Style);
7322   verifyFormat(
7323       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7324       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7325       Style);
7326   verifyFormat(
7327       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7328       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7329       Style);
7330 
7331   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
7332                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
7333                "        b));",
7334                Style);
7335 
7336   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7337   Style.BinPackArguments = false;
7338   Style.BinPackParameters = false;
7339   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7340                "    aaaaaaaaaaa aaaaaaaa,\n"
7341                "    aaaaaaaaa aaaaaaa,\n"
7342                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7343                Style);
7344   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7345                "    aaaaaaaaaaa aaaaaaaaa,\n"
7346                "    aaaaaaaaaaa aaaaaaaaa,\n"
7347                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7348                Style);
7349   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
7350                "    aaaaaaaaaaaaaaa,\n"
7351                "    aaaaaaaaaaaaaaaaaaaaa,\n"
7352                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7353                Style);
7354   verifyFormat(
7355       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
7356       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7357       Style);
7358   verifyFormat(
7359       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
7360       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7361       Style);
7362   verifyFormat(
7363       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7364       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7365       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
7366       "    aaaaaaaaaaaaaaaa);",
7367       Style);
7368   verifyFormat(
7369       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7370       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7371       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
7372       "    aaaaaaaaaaaaaaaa);",
7373       Style);
7374 }
7375 
7376 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
7377   FormatStyle Style = getLLVMStyleWithColumns(40);
7378   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7379                "          bbbbbbbbbbbbbbbbbbbbbb);",
7380                Style);
7381   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7382   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7383   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7384                "          bbbbbbbbbbbbbbbbbbbbbb);",
7385                Style);
7386   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7387   Style.AlignOperands = FormatStyle::OAS_Align;
7388   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7389                "          bbbbbbbbbbbbbbbbbbbbbb);",
7390                Style);
7391   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7392   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7393   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7394                "    bbbbbbbbbbbbbbbbbbbbbb);",
7395                Style);
7396 }
7397 
7398 TEST_F(FormatTest, BreaksConditionalExpressions) {
7399   verifyFormat(
7400       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7401       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7402       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7403   verifyFormat(
7404       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7405       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7406       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7407   verifyFormat(
7408       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7409       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7410   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
7411                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7412                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7413   verifyFormat(
7414       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
7415       "                                                    : aaaaaaaaaaaaa);");
7416   verifyFormat(
7417       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7418       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7419       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7420       "                   aaaaaaaaaaaaa);");
7421   verifyFormat(
7422       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7423       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7424       "                   aaaaaaaaaaaaa);");
7425   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7426                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7427                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7428                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7429                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7430   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7431                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7432                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7433                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7434                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7435                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7436                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7437   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7438                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7439                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7440                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7441                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7442   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7443                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7444                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7445   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7446                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7447                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7448                "        : aaaaaaaaaaaaaaaa;");
7449   verifyFormat(
7450       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7451       "    ? aaaaaaaaaaaaaaa\n"
7452       "    : aaaaaaaaaaaaaaa;");
7453   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7454                "          aaaaaaaaa\n"
7455                "      ? b\n"
7456                "      : c);");
7457   verifyFormat("return aaaa == bbbb\n"
7458                "           // comment\n"
7459                "           ? aaaa\n"
7460                "           : bbbb;");
7461   verifyFormat("unsigned Indent =\n"
7462                "    format(TheLine.First,\n"
7463                "           IndentForLevel[TheLine.Level] >= 0\n"
7464                "               ? IndentForLevel[TheLine.Level]\n"
7465                "               : TheLine * 2,\n"
7466                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7467                getLLVMStyleWithColumns(60));
7468   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7469                "                  ? aaaaaaaaaaaaaaa\n"
7470                "                  : bbbbbbbbbbbbbbb //\n"
7471                "                        ? ccccccccccccccc\n"
7472                "                        : ddddddddddddddd;");
7473   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7474                "                  ? aaaaaaaaaaaaaaa\n"
7475                "                  : (bbbbbbbbbbbbbbb //\n"
7476                "                         ? ccccccccccccccc\n"
7477                "                         : ddddddddddddddd);");
7478   verifyFormat(
7479       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7480       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7481       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
7482       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
7483       "                                      : aaaaaaaaaa;");
7484   verifyFormat(
7485       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7486       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
7487       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7488 
7489   FormatStyle NoBinPacking = getLLVMStyle();
7490   NoBinPacking.BinPackArguments = false;
7491   verifyFormat(
7492       "void f() {\n"
7493       "  g(aaa,\n"
7494       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7495       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7496       "        ? aaaaaaaaaaaaaaa\n"
7497       "        : aaaaaaaaaaaaaaa);\n"
7498       "}",
7499       NoBinPacking);
7500   verifyFormat(
7501       "void f() {\n"
7502       "  g(aaa,\n"
7503       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7504       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7505       "        ?: aaaaaaaaaaaaaaa);\n"
7506       "}",
7507       NoBinPacking);
7508 
7509   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
7510                "             // comment.\n"
7511                "             ccccccccccccccccccccccccccccccccccccccc\n"
7512                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7513                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
7514 
7515   // Assignments in conditional expressions. Apparently not uncommon :-(.
7516   verifyFormat("return a != b\n"
7517                "           // comment\n"
7518                "           ? a = b\n"
7519                "           : a = b;");
7520   verifyFormat("return a != b\n"
7521                "           // comment\n"
7522                "           ? a = a != b\n"
7523                "                     // comment\n"
7524                "                     ? a = b\n"
7525                "                     : a\n"
7526                "           : a;\n");
7527   verifyFormat("return a != b\n"
7528                "           // comment\n"
7529                "           ? a\n"
7530                "           : a = a != b\n"
7531                "                     // comment\n"
7532                "                     ? a = b\n"
7533                "                     : a;");
7534 
7535   // Chained conditionals
7536   FormatStyle Style = getLLVMStyle();
7537   Style.ColumnLimit = 70;
7538   Style.AlignOperands = FormatStyle::OAS_Align;
7539   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7540                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7541                "                        : 3333333333333333;",
7542                Style);
7543   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7544                "       : bbbbbbbbbb     ? 2222222222222222\n"
7545                "                        : 3333333333333333;",
7546                Style);
7547   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
7548                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
7549                "                          : 3333333333333333;",
7550                Style);
7551   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7552                "       : bbbbbbbbbbbbbb ? 222222\n"
7553                "                        : 333333;",
7554                Style);
7555   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7556                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7557                "       : cccccccccccccc ? 3333333333333333\n"
7558                "                        : 4444444444444444;",
7559                Style);
7560   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
7561                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7562                "                        : 3333333333333333;",
7563                Style);
7564   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7565                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7566                "                        : (aaa ? bbb : ccc);",
7567                Style);
7568   verifyFormat(
7569       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7570       "                                             : cccccccccccccccccc)\n"
7571       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7572       "                        : 3333333333333333;",
7573       Style);
7574   verifyFormat(
7575       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7576       "                                             : cccccccccccccccccc)\n"
7577       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7578       "                        : 3333333333333333;",
7579       Style);
7580   verifyFormat(
7581       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7582       "                                             : dddddddddddddddddd)\n"
7583       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7584       "                        : 3333333333333333;",
7585       Style);
7586   verifyFormat(
7587       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7588       "                                             : dddddddddddddddddd)\n"
7589       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7590       "                        : 3333333333333333;",
7591       Style);
7592   verifyFormat(
7593       "return aaaaaaaaa        ? 1111111111111111\n"
7594       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7595       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7596       "                                             : dddddddddddddddddd)\n",
7597       Style);
7598   verifyFormat(
7599       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7600       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7601       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7602       "                                             : cccccccccccccccccc);",
7603       Style);
7604   verifyFormat(
7605       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7606       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7607       "                                             : eeeeeeeeeeeeeeeeee)\n"
7608       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7609       "                        : 3333333333333333;",
7610       Style);
7611   verifyFormat(
7612       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
7613       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7614       "                                             : eeeeeeeeeeeeeeeeee)\n"
7615       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7616       "                        : 3333333333333333;",
7617       Style);
7618   verifyFormat(
7619       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7620       "                           : cccccccccccc    ? dddddddddddddddddd\n"
7621       "                                             : eeeeeeeeeeeeeeeeee)\n"
7622       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7623       "                        : 3333333333333333;",
7624       Style);
7625   verifyFormat(
7626       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7627       "                                             : cccccccccccccccccc\n"
7628       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7629       "                        : 3333333333333333;",
7630       Style);
7631   verifyFormat(
7632       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7633       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
7634       "                                             : eeeeeeeeeeeeeeeeee\n"
7635       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7636       "                        : 3333333333333333;",
7637       Style);
7638   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
7639                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
7640                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
7641                "                                   : eeeeeeeeeeeeeeeeee)\n"
7642                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7643                "                             : 3333333333333333;",
7644                Style);
7645   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
7646                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7647                "             : cccccccccccccccc ? dddddddddddddddddd\n"
7648                "                                : eeeeeeeeeeeeeeeeee\n"
7649                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7650                "                                 : 3333333333333333;",
7651                Style);
7652 
7653   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7654   Style.BreakBeforeTernaryOperators = false;
7655   // FIXME: Aligning the question marks is weird given DontAlign.
7656   // Consider disabling this alignment in this case. Also check whether this
7657   // will render the adjustment from https://reviews.llvm.org/D82199
7658   // unnecessary.
7659   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
7660                "    bbbb                ? cccccccccccccccccc :\n"
7661                "                          ddddd;\n",
7662                Style);
7663 
7664   EXPECT_EQ(
7665       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7666       "    /*\n"
7667       "     */\n"
7668       "    function() {\n"
7669       "      try {\n"
7670       "        return JJJJJJJJJJJJJJ(\n"
7671       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7672       "      }\n"
7673       "    } :\n"
7674       "    function() {};",
7675       format(
7676           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7677           "     /*\n"
7678           "      */\n"
7679           "     function() {\n"
7680           "      try {\n"
7681           "        return JJJJJJJJJJJJJJ(\n"
7682           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7683           "      }\n"
7684           "    } :\n"
7685           "    function() {};",
7686           getGoogleStyle(FormatStyle::LK_JavaScript)));
7687 }
7688 
7689 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
7690   FormatStyle Style = getLLVMStyle();
7691   Style.BreakBeforeTernaryOperators = false;
7692   Style.ColumnLimit = 70;
7693   verifyFormat(
7694       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7695       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7696       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7697       Style);
7698   verifyFormat(
7699       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7700       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7701       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7702       Style);
7703   verifyFormat(
7704       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7705       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7706       Style);
7707   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
7708                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7709                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7710                Style);
7711   verifyFormat(
7712       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
7713       "                                                      aaaaaaaaaaaaa);",
7714       Style);
7715   verifyFormat(
7716       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7717       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7718       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7719       "                   aaaaaaaaaaaaa);",
7720       Style);
7721   verifyFormat(
7722       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7723       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7724       "                   aaaaaaaaaaaaa);",
7725       Style);
7726   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7727                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7728                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7729                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7730                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7731                Style);
7732   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7733                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7734                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7735                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7736                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7737                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7738                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7739                Style);
7740   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7741                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
7742                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7743                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7744                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7745                Style);
7746   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7747                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7748                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7749                Style);
7750   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7751                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7752                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7753                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7754                Style);
7755   verifyFormat(
7756       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7757       "    aaaaaaaaaaaaaaa :\n"
7758       "    aaaaaaaaaaaaaaa;",
7759       Style);
7760   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7761                "          aaaaaaaaa ?\n"
7762                "      b :\n"
7763                "      c);",
7764                Style);
7765   verifyFormat("unsigned Indent =\n"
7766                "    format(TheLine.First,\n"
7767                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
7768                "               IndentForLevel[TheLine.Level] :\n"
7769                "               TheLine * 2,\n"
7770                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7771                Style);
7772   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
7773                "                  aaaaaaaaaaaaaaa :\n"
7774                "                  bbbbbbbbbbbbbbb ? //\n"
7775                "                      ccccccccccccccc :\n"
7776                "                      ddddddddddddddd;",
7777                Style);
7778   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
7779                "                  aaaaaaaaaaaaaaa :\n"
7780                "                  (bbbbbbbbbbbbbbb ? //\n"
7781                "                       ccccccccccccccc :\n"
7782                "                       ddddddddddddddd);",
7783                Style);
7784   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7785                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
7786                "            ccccccccccccccccccccccccccc;",
7787                Style);
7788   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7789                "           aaaaa :\n"
7790                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
7791                Style);
7792 
7793   // Chained conditionals
7794   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7795                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7796                "                          3333333333333333;",
7797                Style);
7798   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7799                "       bbbbbbbbbb       ? 2222222222222222 :\n"
7800                "                          3333333333333333;",
7801                Style);
7802   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
7803                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7804                "                          3333333333333333;",
7805                Style);
7806   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7807                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
7808                "                          333333;",
7809                Style);
7810   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7811                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7812                "       cccccccccccccccc ? 3333333333333333 :\n"
7813                "                          4444444444444444;",
7814                Style);
7815   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
7816                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7817                "                          3333333333333333;",
7818                Style);
7819   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7820                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7821                "                          (aaa ? bbb : ccc);",
7822                Style);
7823   verifyFormat(
7824       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7825       "                                               cccccccccccccccccc) :\n"
7826       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7827       "                          3333333333333333;",
7828       Style);
7829   verifyFormat(
7830       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7831       "                                               cccccccccccccccccc) :\n"
7832       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7833       "                          3333333333333333;",
7834       Style);
7835   verifyFormat(
7836       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7837       "                                               dddddddddddddddddd) :\n"
7838       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7839       "                          3333333333333333;",
7840       Style);
7841   verifyFormat(
7842       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7843       "                                               dddddddddddddddddd) :\n"
7844       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7845       "                          3333333333333333;",
7846       Style);
7847   verifyFormat(
7848       "return aaaaaaaaa        ? 1111111111111111 :\n"
7849       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7850       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7851       "                                               dddddddddddddddddd)\n",
7852       Style);
7853   verifyFormat(
7854       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7855       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7856       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7857       "                                               cccccccccccccccccc);",
7858       Style);
7859   verifyFormat(
7860       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7861       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
7862       "                                               eeeeeeeeeeeeeeeeee) :\n"
7863       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7864       "                          3333333333333333;",
7865       Style);
7866   verifyFormat(
7867       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7868       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
7869       "                                               eeeeeeeeeeeeeeeeee) :\n"
7870       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7871       "                          3333333333333333;",
7872       Style);
7873   verifyFormat(
7874       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
7875       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
7876       "                                               eeeeeeeeeeeeeeeeee) :\n"
7877       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7878       "                          3333333333333333;",
7879       Style);
7880   verifyFormat(
7881       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7882       "                                               cccccccccccccccccc :\n"
7883       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7884       "                          3333333333333333;",
7885       Style);
7886   verifyFormat(
7887       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7888       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
7889       "                                               eeeeeeeeeeeeeeeeee :\n"
7890       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7891       "                          3333333333333333;",
7892       Style);
7893   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
7894                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7895                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
7896                "                                 eeeeeeeeeeeeeeeeee) :\n"
7897                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7898                "                               3333333333333333;",
7899                Style);
7900   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
7901                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7902                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
7903                "                                  eeeeeeeeeeeeeeeeee :\n"
7904                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7905                "                               3333333333333333;",
7906                Style);
7907 }
7908 
7909 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
7910   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
7911                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
7912   verifyFormat("bool a = true, b = false;");
7913 
7914   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7915                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
7916                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
7917                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
7918   verifyFormat(
7919       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
7920       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
7921       "     d = e && f;");
7922   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
7923                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
7924   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
7925                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
7926   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
7927                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
7928 
7929   FormatStyle Style = getGoogleStyle();
7930   Style.PointerAlignment = FormatStyle::PAS_Left;
7931   Style.DerivePointerAlignment = false;
7932   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7933                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
7934                "    *b = bbbbbbbbbbbbbbbbbbb;",
7935                Style);
7936   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
7937                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
7938                Style);
7939   verifyFormat("vector<int*> a, b;", Style);
7940   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
7941 }
7942 
7943 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
7944   verifyFormat("arr[foo ? bar : baz];");
7945   verifyFormat("f()[foo ? bar : baz];");
7946   verifyFormat("(a + b)[foo ? bar : baz];");
7947   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
7948 }
7949 
7950 TEST_F(FormatTest, AlignsStringLiterals) {
7951   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
7952                "                                      \"short literal\");");
7953   verifyFormat(
7954       "looooooooooooooooooooooooongFunction(\n"
7955       "    \"short literal\"\n"
7956       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
7957   verifyFormat("someFunction(\"Always break between multi-line\"\n"
7958                "             \" string literals\",\n"
7959                "             and, other, parameters);");
7960   EXPECT_EQ("fun + \"1243\" /* comment */\n"
7961             "      \"5678\";",
7962             format("fun + \"1243\" /* comment */\n"
7963                    "    \"5678\";",
7964                    getLLVMStyleWithColumns(28)));
7965   EXPECT_EQ(
7966       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
7967       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
7968       "         \"aaaaaaaaaaaaaaaa\";",
7969       format("aaaaaa ="
7970              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
7971              "aaaaaaaaaaaaaaaaaaaaa\" "
7972              "\"aaaaaaaaaaaaaaaa\";"));
7973   verifyFormat("a = a + \"a\"\n"
7974                "        \"a\"\n"
7975                "        \"a\";");
7976   verifyFormat("f(\"a\", \"b\"\n"
7977                "       \"c\");");
7978 
7979   verifyFormat(
7980       "#define LL_FORMAT \"ll\"\n"
7981       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
7982       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
7983 
7984   verifyFormat("#define A(X)          \\\n"
7985                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
7986                "  \"ccccc\"",
7987                getLLVMStyleWithColumns(23));
7988   verifyFormat("#define A \"def\"\n"
7989                "f(\"abc\" A \"ghi\"\n"
7990                "  \"jkl\");");
7991 
7992   verifyFormat("f(L\"a\"\n"
7993                "  L\"b\");");
7994   verifyFormat("#define A(X)            \\\n"
7995                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
7996                "  L\"ccccc\"",
7997                getLLVMStyleWithColumns(25));
7998 
7999   verifyFormat("f(@\"a\"\n"
8000                "  @\"b\");");
8001   verifyFormat("NSString s = @\"a\"\n"
8002                "             @\"b\"\n"
8003                "             @\"c\";");
8004   verifyFormat("NSString s = @\"a\"\n"
8005                "              \"b\"\n"
8006                "              \"c\";");
8007 }
8008 
8009 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8010   FormatStyle Style = getLLVMStyle();
8011   // No declarations or definitions should be moved to own line.
8012   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8013   verifyFormat("class A {\n"
8014                "  int f() { return 1; }\n"
8015                "  int g();\n"
8016                "};\n"
8017                "int f() { return 1; }\n"
8018                "int g();\n",
8019                Style);
8020 
8021   // All declarations and definitions should have the return type moved to its
8022   // own line.
8023   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8024   Style.TypenameMacros = {"LIST"};
8025   verifyFormat("SomeType\n"
8026                "funcdecl(LIST(uint64_t));",
8027                Style);
8028   verifyFormat("class E {\n"
8029                "  int\n"
8030                "  f() {\n"
8031                "    return 1;\n"
8032                "  }\n"
8033                "  int\n"
8034                "  g();\n"
8035                "};\n"
8036                "int\n"
8037                "f() {\n"
8038                "  return 1;\n"
8039                "}\n"
8040                "int\n"
8041                "g();\n",
8042                Style);
8043 
8044   // Top-level definitions, and no kinds of declarations should have the
8045   // return type moved to its own line.
8046   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8047   verifyFormat("class B {\n"
8048                "  int f() { return 1; }\n"
8049                "  int g();\n"
8050                "};\n"
8051                "int\n"
8052                "f() {\n"
8053                "  return 1;\n"
8054                "}\n"
8055                "int g();\n",
8056                Style);
8057 
8058   // Top-level definitions and declarations should have the return type moved
8059   // to its own line.
8060   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8061   verifyFormat("class C {\n"
8062                "  int f() { return 1; }\n"
8063                "  int g();\n"
8064                "};\n"
8065                "int\n"
8066                "f() {\n"
8067                "  return 1;\n"
8068                "}\n"
8069                "int\n"
8070                "g();\n",
8071                Style);
8072 
8073   // All definitions should have the return type moved to its own line, but no
8074   // kinds of declarations.
8075   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8076   verifyFormat("class D {\n"
8077                "  int\n"
8078                "  f() {\n"
8079                "    return 1;\n"
8080                "  }\n"
8081                "  int g();\n"
8082                "};\n"
8083                "int\n"
8084                "f() {\n"
8085                "  return 1;\n"
8086                "}\n"
8087                "int g();\n",
8088                Style);
8089   verifyFormat("const char *\n"
8090                "f(void) {\n" // Break here.
8091                "  return \"\";\n"
8092                "}\n"
8093                "const char *bar(void);\n", // No break here.
8094                Style);
8095   verifyFormat("template <class T>\n"
8096                "T *\n"
8097                "f(T &c) {\n" // Break here.
8098                "  return NULL;\n"
8099                "}\n"
8100                "template <class T> T *f(T &c);\n", // No break here.
8101                Style);
8102   verifyFormat("class C {\n"
8103                "  int\n"
8104                "  operator+() {\n"
8105                "    return 1;\n"
8106                "  }\n"
8107                "  int\n"
8108                "  operator()() {\n"
8109                "    return 1;\n"
8110                "  }\n"
8111                "};\n",
8112                Style);
8113   verifyFormat("void\n"
8114                "A::operator()() {}\n"
8115                "void\n"
8116                "A::operator>>() {}\n"
8117                "void\n"
8118                "A::operator+() {}\n"
8119                "void\n"
8120                "A::operator*() {}\n"
8121                "void\n"
8122                "A::operator->() {}\n"
8123                "void\n"
8124                "A::operator void *() {}\n"
8125                "void\n"
8126                "A::operator void &() {}\n"
8127                "void\n"
8128                "A::operator void &&() {}\n"
8129                "void\n"
8130                "A::operator char *() {}\n"
8131                "void\n"
8132                "A::operator[]() {}\n"
8133                "void\n"
8134                "A::operator!() {}\n"
8135                "void\n"
8136                "A::operator**() {}\n"
8137                "void\n"
8138                "A::operator<Foo> *() {}\n"
8139                "void\n"
8140                "A::operator<Foo> **() {}\n"
8141                "void\n"
8142                "A::operator<Foo> &() {}\n"
8143                "void\n"
8144                "A::operator void **() {}\n",
8145                Style);
8146   verifyFormat("constexpr auto\n"
8147                "operator()() const -> reference {}\n"
8148                "constexpr auto\n"
8149                "operator>>() const -> reference {}\n"
8150                "constexpr auto\n"
8151                "operator+() const -> reference {}\n"
8152                "constexpr auto\n"
8153                "operator*() const -> reference {}\n"
8154                "constexpr auto\n"
8155                "operator->() const -> reference {}\n"
8156                "constexpr auto\n"
8157                "operator++() const -> reference {}\n"
8158                "constexpr auto\n"
8159                "operator void *() const -> reference {}\n"
8160                "constexpr auto\n"
8161                "operator void **() const -> reference {}\n"
8162                "constexpr auto\n"
8163                "operator void *() const -> reference {}\n"
8164                "constexpr auto\n"
8165                "operator void &() const -> reference {}\n"
8166                "constexpr auto\n"
8167                "operator void &&() const -> reference {}\n"
8168                "constexpr auto\n"
8169                "operator char *() const -> reference {}\n"
8170                "constexpr auto\n"
8171                "operator!() const -> reference {}\n"
8172                "constexpr auto\n"
8173                "operator[]() const -> reference {}\n",
8174                Style);
8175   verifyFormat("void *operator new(std::size_t s);", // No break here.
8176                Style);
8177   verifyFormat("void *\n"
8178                "operator new(std::size_t s) {}",
8179                Style);
8180   verifyFormat("void *\n"
8181                "operator delete[](void *ptr) {}",
8182                Style);
8183   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8184   verifyFormat("const char *\n"
8185                "f(void)\n" // Break here.
8186                "{\n"
8187                "  return \"\";\n"
8188                "}\n"
8189                "const char *bar(void);\n", // No break here.
8190                Style);
8191   verifyFormat("template <class T>\n"
8192                "T *\n"     // Problem here: no line break
8193                "f(T &c)\n" // Break here.
8194                "{\n"
8195                "  return NULL;\n"
8196                "}\n"
8197                "template <class T> T *f(T &c);\n", // No break here.
8198                Style);
8199   verifyFormat("int\n"
8200                "foo(A<bool> a)\n"
8201                "{\n"
8202                "  return a;\n"
8203                "}\n",
8204                Style);
8205   verifyFormat("int\n"
8206                "foo(A<8> a)\n"
8207                "{\n"
8208                "  return a;\n"
8209                "}\n",
8210                Style);
8211   verifyFormat("int\n"
8212                "foo(A<B<bool>, 8> a)\n"
8213                "{\n"
8214                "  return a;\n"
8215                "}\n",
8216                Style);
8217   verifyFormat("int\n"
8218                "foo(A<B<8>, bool> a)\n"
8219                "{\n"
8220                "  return a;\n"
8221                "}\n",
8222                Style);
8223   verifyFormat("int\n"
8224                "foo(A<B<bool>, bool> a)\n"
8225                "{\n"
8226                "  return a;\n"
8227                "}\n",
8228                Style);
8229   verifyFormat("int\n"
8230                "foo(A<B<8>, 8> a)\n"
8231                "{\n"
8232                "  return a;\n"
8233                "}\n",
8234                Style);
8235 
8236   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8237   Style.BraceWrapping.AfterFunction = true;
8238   verifyFormat("int f(i);\n" // No break here.
8239                "int\n"       // Break here.
8240                "f(i)\n"
8241                "{\n"
8242                "  return i + 1;\n"
8243                "}\n"
8244                "int\n" // Break here.
8245                "f(i)\n"
8246                "{\n"
8247                "  return i + 1;\n"
8248                "};",
8249                Style);
8250   verifyFormat("int f(a, b, c);\n" // No break here.
8251                "int\n"             // Break here.
8252                "f(a, b, c)\n"      // Break here.
8253                "short a, b;\n"
8254                "float c;\n"
8255                "{\n"
8256                "  return a + b < c;\n"
8257                "}\n"
8258                "int\n"        // Break here.
8259                "f(a, b, c)\n" // Break here.
8260                "short a, b;\n"
8261                "float c;\n"
8262                "{\n"
8263                "  return a + b < c;\n"
8264                "};",
8265                Style);
8266   verifyFormat("byte *\n" // Break here.
8267                "f(a)\n"   // Break here.
8268                "byte a[];\n"
8269                "{\n"
8270                "  return a;\n"
8271                "}",
8272                Style);
8273   verifyFormat("bool f(int a, int) override;\n"
8274                "Bar g(int a, Bar) final;\n"
8275                "Bar h(a, Bar) final;",
8276                Style);
8277   verifyFormat("int\n"
8278                "f(a)",
8279                Style);
8280   verifyFormat("bool\n"
8281                "f(size_t = 0, bool b = false)\n"
8282                "{\n"
8283                "  return !b;\n"
8284                "}",
8285                Style);
8286 
8287   // The return breaking style doesn't affect:
8288   // * function and object definitions with attribute-like macros
8289   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8290                "    ABSL_GUARDED_BY(mutex) = {};",
8291                getGoogleStyleWithColumns(40));
8292   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8293                "    ABSL_GUARDED_BY(mutex);  // comment",
8294                getGoogleStyleWithColumns(40));
8295   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8296                "    ABSL_GUARDED_BY(mutex1)\n"
8297                "        ABSL_GUARDED_BY(mutex2);",
8298                getGoogleStyleWithColumns(40));
8299   verifyFormat("Tttttt f(int a, int b)\n"
8300                "    ABSL_GUARDED_BY(mutex1)\n"
8301                "        ABSL_GUARDED_BY(mutex2);",
8302                getGoogleStyleWithColumns(40));
8303   // * typedefs
8304   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
8305 
8306   Style = getGNUStyle();
8307 
8308   // Test for comments at the end of function declarations.
8309   verifyFormat("void\n"
8310                "foo (int a, /*abc*/ int b) // def\n"
8311                "{\n"
8312                "}\n",
8313                Style);
8314 
8315   verifyFormat("void\n"
8316                "foo (int a, /* abc */ int b) /* def */\n"
8317                "{\n"
8318                "}\n",
8319                Style);
8320 
8321   // Definitions that should not break after return type
8322   verifyFormat("void foo (int a, int b); // def\n", Style);
8323   verifyFormat("void foo (int a, int b); /* def */\n", Style);
8324   verifyFormat("void foo (int a, int b);\n", Style);
8325 }
8326 
8327 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
8328   FormatStyle NoBreak = getLLVMStyle();
8329   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
8330   FormatStyle Break = getLLVMStyle();
8331   Break.AlwaysBreakBeforeMultilineStrings = true;
8332   verifyFormat("aaaa = \"bbbb\"\n"
8333                "       \"cccc\";",
8334                NoBreak);
8335   verifyFormat("aaaa =\n"
8336                "    \"bbbb\"\n"
8337                "    \"cccc\";",
8338                Break);
8339   verifyFormat("aaaa(\"bbbb\"\n"
8340                "     \"cccc\");",
8341                NoBreak);
8342   verifyFormat("aaaa(\n"
8343                "    \"bbbb\"\n"
8344                "    \"cccc\");",
8345                Break);
8346   verifyFormat("aaaa(qqq, \"bbbb\"\n"
8347                "          \"cccc\");",
8348                NoBreak);
8349   verifyFormat("aaaa(qqq,\n"
8350                "     \"bbbb\"\n"
8351                "     \"cccc\");",
8352                Break);
8353   verifyFormat("aaaa(qqq,\n"
8354                "     L\"bbbb\"\n"
8355                "     L\"cccc\");",
8356                Break);
8357   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
8358                "                      \"bbbb\"));",
8359                Break);
8360   verifyFormat("string s = someFunction(\n"
8361                "    \"abc\"\n"
8362                "    \"abc\");",
8363                Break);
8364 
8365   // As we break before unary operators, breaking right after them is bad.
8366   verifyFormat("string foo = abc ? \"x\"\n"
8367                "                   \"blah blah blah blah blah blah\"\n"
8368                "                 : \"y\";",
8369                Break);
8370 
8371   // Don't break if there is no column gain.
8372   verifyFormat("f(\"aaaa\"\n"
8373                "  \"bbbb\");",
8374                Break);
8375 
8376   // Treat literals with escaped newlines like multi-line string literals.
8377   EXPECT_EQ("x = \"a\\\n"
8378             "b\\\n"
8379             "c\";",
8380             format("x = \"a\\\n"
8381                    "b\\\n"
8382                    "c\";",
8383                    NoBreak));
8384   EXPECT_EQ("xxxx =\n"
8385             "    \"a\\\n"
8386             "b\\\n"
8387             "c\";",
8388             format("xxxx = \"a\\\n"
8389                    "b\\\n"
8390                    "c\";",
8391                    Break));
8392 
8393   EXPECT_EQ("NSString *const kString =\n"
8394             "    @\"aaaa\"\n"
8395             "    @\"bbbb\";",
8396             format("NSString *const kString = @\"aaaa\"\n"
8397                    "@\"bbbb\";",
8398                    Break));
8399 
8400   Break.ColumnLimit = 0;
8401   verifyFormat("const char *hello = \"hello llvm\";", Break);
8402 }
8403 
8404 TEST_F(FormatTest, AlignsPipes) {
8405   verifyFormat(
8406       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8407       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8408       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8409   verifyFormat(
8410       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
8411       "                     << aaaaaaaaaaaaaaaaaaaa;");
8412   verifyFormat(
8413       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8414       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8415   verifyFormat(
8416       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
8417       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8418   verifyFormat(
8419       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
8420       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
8421       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
8422   verifyFormat(
8423       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8424       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8425       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8426   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8427                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8428                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8429                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8430   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
8431                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
8432   verifyFormat(
8433       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8434       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8435   verifyFormat(
8436       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
8437       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
8438 
8439   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
8440                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
8441   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8442                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8443                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
8444                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
8445   verifyFormat("LOG_IF(aaa == //\n"
8446                "       bbb)\n"
8447                "    << a << b;");
8448 
8449   // But sometimes, breaking before the first "<<" is desirable.
8450   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8451                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
8452   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
8453                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8454                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8455   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
8456                "    << BEF << IsTemplate << Description << E->getType();");
8457   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8458                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8459                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8460   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8461                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8462                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8463                "    << aaa;");
8464 
8465   verifyFormat(
8466       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8467       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8468 
8469   // Incomplete string literal.
8470   EXPECT_EQ("llvm::errs() << \"\n"
8471             "             << a;",
8472             format("llvm::errs() << \"\n<<a;"));
8473 
8474   verifyFormat("void f() {\n"
8475                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
8476                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
8477                "}");
8478 
8479   // Handle 'endl'.
8480   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
8481                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8482   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8483 
8484   // Handle '\n'.
8485   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
8486                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8487   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
8488                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
8489   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
8490                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
8491   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8492 }
8493 
8494 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
8495   verifyFormat("return out << \"somepacket = {\\n\"\n"
8496                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
8497                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
8498                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
8499                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
8500                "           << \"}\";");
8501 
8502   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8503                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8504                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
8505   verifyFormat(
8506       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
8507       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
8508       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
8509       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
8510       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
8511   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
8512                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8513   verifyFormat(
8514       "void f() {\n"
8515       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
8516       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
8517       "}");
8518 
8519   // Breaking before the first "<<" is generally not desirable.
8520   verifyFormat(
8521       "llvm::errs()\n"
8522       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8523       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8524       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8525       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8526       getLLVMStyleWithColumns(70));
8527   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8528                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8529                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8530                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8531                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8532                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8533                getLLVMStyleWithColumns(70));
8534 
8535   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8536                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8537                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
8538   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8539                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8540                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
8541   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
8542                "           (aaaa + aaaa);",
8543                getLLVMStyleWithColumns(40));
8544   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
8545                "                  (aaaaaaa + aaaaa));",
8546                getLLVMStyleWithColumns(40));
8547   verifyFormat(
8548       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
8549       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
8550       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
8551 }
8552 
8553 TEST_F(FormatTest, UnderstandsEquals) {
8554   verifyFormat(
8555       "aaaaaaaaaaaaaaaaa =\n"
8556       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8557   verifyFormat(
8558       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8559       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8560   verifyFormat(
8561       "if (a) {\n"
8562       "  f();\n"
8563       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8564       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
8565       "}");
8566 
8567   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8568                "        100000000 + 10000000) {\n}");
8569 }
8570 
8571 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
8572   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8573                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
8574 
8575   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8576                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
8577 
8578   verifyFormat(
8579       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
8580       "                                                          Parameter2);");
8581 
8582   verifyFormat(
8583       "ShortObject->shortFunction(\n"
8584       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
8585       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
8586 
8587   verifyFormat("loooooooooooooongFunction(\n"
8588                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
8589 
8590   verifyFormat(
8591       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
8592       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
8593 
8594   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8595                "    .WillRepeatedly(Return(SomeValue));");
8596   verifyFormat("void f() {\n"
8597                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8598                "      .Times(2)\n"
8599                "      .WillRepeatedly(Return(SomeValue));\n"
8600                "}");
8601   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
8602                "    ccccccccccccccccccccccc);");
8603   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8604                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8605                "          .aaaaa(aaaaa),\n"
8606                "      aaaaaaaaaaaaaaaaaaaaa);");
8607   verifyFormat("void f() {\n"
8608                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8609                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
8610                "}");
8611   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8612                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8613                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8614                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8615                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
8616   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8617                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8618                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8619                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
8620                "}");
8621 
8622   // Here, it is not necessary to wrap at "." or "->".
8623   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
8624                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8625   verifyFormat(
8626       "aaaaaaaaaaa->aaaaaaaaa(\n"
8627       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8628       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
8629 
8630   verifyFormat(
8631       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8632       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
8633   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
8634                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8635   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
8636                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8637 
8638   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8639                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8640                "    .a();");
8641 
8642   FormatStyle NoBinPacking = getLLVMStyle();
8643   NoBinPacking.BinPackParameters = false;
8644   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8645                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8646                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
8647                "                         aaaaaaaaaaaaaaaaaaa,\n"
8648                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8649                NoBinPacking);
8650 
8651   // If there is a subsequent call, change to hanging indentation.
8652   verifyFormat(
8653       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8654       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
8655       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8656   verifyFormat(
8657       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8658       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
8659   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8660                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8661                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8662   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8663                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8664                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
8665 }
8666 
8667 TEST_F(FormatTest, WrapsTemplateDeclarations) {
8668   verifyFormat("template <typename T>\n"
8669                "virtual void loooooooooooongFunction(int Param1, int Param2);");
8670   verifyFormat("template <typename T>\n"
8671                "// T should be one of {A, B}.\n"
8672                "virtual void loooooooooooongFunction(int Param1, int Param2);");
8673   verifyFormat(
8674       "template <typename T>\n"
8675       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
8676   verifyFormat("template <typename T>\n"
8677                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
8678                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
8679   verifyFormat(
8680       "template <typename T>\n"
8681       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
8682       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
8683   verifyFormat(
8684       "template <typename T>\n"
8685       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
8686       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
8687       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8688   verifyFormat("template <typename T>\n"
8689                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8690                "    int aaaaaaaaaaaaaaaaaaaaaa);");
8691   verifyFormat(
8692       "template <typename T1, typename T2 = char, typename T3 = char,\n"
8693       "          typename T4 = char>\n"
8694       "void f();");
8695   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
8696                "          template <typename> class cccccccccccccccccccccc,\n"
8697                "          typename ddddddddddddd>\n"
8698                "class C {};");
8699   verifyFormat(
8700       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
8701       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8702 
8703   verifyFormat("void f() {\n"
8704                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
8705                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
8706                "}");
8707 
8708   verifyFormat("template <typename T> class C {};");
8709   verifyFormat("template <typename T> void f();");
8710   verifyFormat("template <typename T> void f() {}");
8711   verifyFormat(
8712       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8713       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8714       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
8715       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8716       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8717       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
8718       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
8719       getLLVMStyleWithColumns(72));
8720   EXPECT_EQ("static_cast<A< //\n"
8721             "    B> *>(\n"
8722             "\n"
8723             ");",
8724             format("static_cast<A<//\n"
8725                    "    B>*>(\n"
8726                    "\n"
8727                    "    );"));
8728   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8729                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
8730 
8731   FormatStyle AlwaysBreak = getLLVMStyle();
8732   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
8733   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
8734   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
8735   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
8736   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8737                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8738                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
8739   verifyFormat("template <template <typename> class Fooooooo,\n"
8740                "          template <typename> class Baaaaaaar>\n"
8741                "struct C {};",
8742                AlwaysBreak);
8743   verifyFormat("template <typename T> // T can be A, B or C.\n"
8744                "struct C {};",
8745                AlwaysBreak);
8746   verifyFormat("template <enum E> class A {\n"
8747                "public:\n"
8748                "  E *f();\n"
8749                "};");
8750 
8751   FormatStyle NeverBreak = getLLVMStyle();
8752   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
8753   verifyFormat("template <typename T> class C {};", NeverBreak);
8754   verifyFormat("template <typename T> void f();", NeverBreak);
8755   verifyFormat("template <typename T> void f() {}", NeverBreak);
8756   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
8757                "bbbbbbbbbbbbbbbbbbbb) {}",
8758                NeverBreak);
8759   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8760                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8761                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
8762                NeverBreak);
8763   verifyFormat("template <template <typename> class Fooooooo,\n"
8764                "          template <typename> class Baaaaaaar>\n"
8765                "struct C {};",
8766                NeverBreak);
8767   verifyFormat("template <typename T> // T can be A, B or C.\n"
8768                "struct C {};",
8769                NeverBreak);
8770   verifyFormat("template <enum E> class A {\n"
8771                "public:\n"
8772                "  E *f();\n"
8773                "};",
8774                NeverBreak);
8775   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
8776   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
8777                "bbbbbbbbbbbbbbbbbbbb) {}",
8778                NeverBreak);
8779 }
8780 
8781 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
8782   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
8783   Style.ColumnLimit = 60;
8784   EXPECT_EQ("// Baseline - no comments.\n"
8785             "template <\n"
8786             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
8787             "void f() {}",
8788             format("// Baseline - no comments.\n"
8789                    "template <\n"
8790                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
8791                    "void f() {}",
8792                    Style));
8793 
8794   EXPECT_EQ("template <\n"
8795             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
8796             "void f() {}",
8797             format("template <\n"
8798                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8799                    "void f() {}",
8800                    Style));
8801 
8802   EXPECT_EQ(
8803       "template <\n"
8804       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
8805       "void f() {}",
8806       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
8807              "void f() {}",
8808              Style));
8809 
8810   EXPECT_EQ(
8811       "template <\n"
8812       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
8813       "                                               // multiline\n"
8814       "void f() {}",
8815       format("template <\n"
8816              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8817              "                                              // multiline\n"
8818              "void f() {}",
8819              Style));
8820 
8821   EXPECT_EQ(
8822       "template <typename aaaaaaaaaa<\n"
8823       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
8824       "void f() {}",
8825       format(
8826           "template <\n"
8827           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
8828           "void f() {}",
8829           Style));
8830 }
8831 
8832 TEST_F(FormatTest, WrapsTemplateParameters) {
8833   FormatStyle Style = getLLVMStyle();
8834   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8835   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
8836   verifyFormat(
8837       "template <typename... a> struct q {};\n"
8838       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
8839       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
8840       "    y;",
8841       Style);
8842   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8843   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
8844   verifyFormat(
8845       "template <typename... a> struct r {};\n"
8846       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
8847       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
8848       "    y;",
8849       Style);
8850   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8851   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
8852   verifyFormat("template <typename... a> struct s {};\n"
8853                "extern s<\n"
8854                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8855                "aaaaaaaaaaaaaaaaaaaaaa,\n"
8856                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8857                "aaaaaaaaaaaaaaaaaaaaaa>\n"
8858                "    y;",
8859                Style);
8860   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8861   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
8862   verifyFormat("template <typename... a> struct t {};\n"
8863                "extern t<\n"
8864                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8865                "aaaaaaaaaaaaaaaaaaaaaa,\n"
8866                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8867                "aaaaaaaaaaaaaaaaaaaaaa>\n"
8868                "    y;",
8869                Style);
8870 }
8871 
8872 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
8873   verifyFormat(
8874       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8875       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8876   verifyFormat(
8877       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8878       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8879       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
8880 
8881   // FIXME: Should we have the extra indent after the second break?
8882   verifyFormat(
8883       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8884       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8885       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8886 
8887   verifyFormat(
8888       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
8889       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
8890 
8891   // Breaking at nested name specifiers is generally not desirable.
8892   verifyFormat(
8893       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8894       "    aaaaaaaaaaaaaaaaaaaaaaa);");
8895 
8896   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
8897                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8898                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8899                "                   aaaaaaaaaaaaaaaaaaaaa);",
8900                getLLVMStyleWithColumns(74));
8901 
8902   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8903                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8904                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8905 }
8906 
8907 TEST_F(FormatTest, UnderstandsTemplateParameters) {
8908   verifyFormat("A<int> a;");
8909   verifyFormat("A<A<A<int>>> a;");
8910   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
8911   verifyFormat("bool x = a < 1 || 2 > a;");
8912   verifyFormat("bool x = 5 < f<int>();");
8913   verifyFormat("bool x = f<int>() > 5;");
8914   verifyFormat("bool x = 5 < a<int>::x;");
8915   verifyFormat("bool x = a < 4 ? a > 2 : false;");
8916   verifyFormat("bool x = f() ? a < 2 : a > 2;");
8917 
8918   verifyGoogleFormat("A<A<int>> a;");
8919   verifyGoogleFormat("A<A<A<int>>> a;");
8920   verifyGoogleFormat("A<A<A<A<int>>>> a;");
8921   verifyGoogleFormat("A<A<int> > a;");
8922   verifyGoogleFormat("A<A<A<int> > > a;");
8923   verifyGoogleFormat("A<A<A<A<int> > > > a;");
8924   verifyGoogleFormat("A<::A<int>> a;");
8925   verifyGoogleFormat("A<::A> a;");
8926   verifyGoogleFormat("A< ::A> a;");
8927   verifyGoogleFormat("A< ::A<int> > a;");
8928   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
8929   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
8930   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
8931   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
8932   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
8933             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
8934 
8935   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
8936 
8937   // template closer followed by a token that starts with > or =
8938   verifyFormat("bool b = a<1> > 1;");
8939   verifyFormat("bool b = a<1> >= 1;");
8940   verifyFormat("int i = a<1> >> 1;");
8941   FormatStyle Style = getLLVMStyle();
8942   Style.SpaceBeforeAssignmentOperators = false;
8943   verifyFormat("bool b= a<1> == 1;", Style);
8944   verifyFormat("a<int> = 1;", Style);
8945   verifyFormat("a<int> >>= 1;", Style);
8946 
8947   verifyFormat("test < a | b >> c;");
8948   verifyFormat("test<test<a | b>> c;");
8949   verifyFormat("test >> a >> b;");
8950   verifyFormat("test << a >> b;");
8951 
8952   verifyFormat("f<int>();");
8953   verifyFormat("template <typename T> void f() {}");
8954   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
8955   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
8956                "sizeof(char)>::type>;");
8957   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
8958   verifyFormat("f(a.operator()<A>());");
8959   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8960                "      .template operator()<A>());",
8961                getLLVMStyleWithColumns(35));
8962 
8963   // Not template parameters.
8964   verifyFormat("return a < b && c > d;");
8965   verifyFormat("void f() {\n"
8966                "  while (a < b && c > d) {\n"
8967                "  }\n"
8968                "}");
8969   verifyFormat("template <typename... Types>\n"
8970                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
8971 
8972   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8973                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
8974                getLLVMStyleWithColumns(60));
8975   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
8976   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
8977   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
8978   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
8979 }
8980 
8981 TEST_F(FormatTest, UnderstandsShiftOperators) {
8982   verifyFormat("if (i < x >> 1)");
8983   verifyFormat("while (i < x >> 1)");
8984   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
8985   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
8986   verifyFormat(
8987       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
8988   verifyFormat("Foo.call<Bar<Function>>()");
8989   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
8990   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
8991                "++i, v = v >> 1)");
8992   verifyFormat("if (w<u<v<x>>, 1>::t)");
8993 }
8994 
8995 TEST_F(FormatTest, BitshiftOperatorWidth) {
8996   EXPECT_EQ("int a = 1 << 2; /* foo\n"
8997             "                   bar */",
8998             format("int    a=1<<2;  /* foo\n"
8999                    "                   bar */"));
9000 
9001   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9002             "                     bar */",
9003             format("int  b  =256>>1 ;  /* foo\n"
9004                    "                      bar */"));
9005 }
9006 
9007 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9008   verifyFormat("COMPARE(a, ==, b);");
9009   verifyFormat("auto s = sizeof...(Ts) - 1;");
9010 }
9011 
9012 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9013   verifyFormat("int A::*x;");
9014   verifyFormat("int (S::*func)(void *);");
9015   verifyFormat("void f() { int (S::*func)(void *); }");
9016   verifyFormat("typedef bool *(Class::*Member)() const;");
9017   verifyFormat("void f() {\n"
9018                "  (a->*f)();\n"
9019                "  a->*x;\n"
9020                "  (a.*f)();\n"
9021                "  ((*a).*f)();\n"
9022                "  a.*x;\n"
9023                "}");
9024   verifyFormat("void f() {\n"
9025                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9026                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9027                "}");
9028   verifyFormat(
9029       "(aaaaaaaaaa->*bbbbbbb)(\n"
9030       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9031   FormatStyle Style = getLLVMStyle();
9032   Style.PointerAlignment = FormatStyle::PAS_Left;
9033   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9034 }
9035 
9036 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9037   verifyFormat("int a = -2;");
9038   verifyFormat("f(-1, -2, -3);");
9039   verifyFormat("a[-1] = 5;");
9040   verifyFormat("int a = 5 + -2;");
9041   verifyFormat("if (i == -1) {\n}");
9042   verifyFormat("if (i != -1) {\n}");
9043   verifyFormat("if (i > -1) {\n}");
9044   verifyFormat("if (i < -1) {\n}");
9045   verifyFormat("++(a->f());");
9046   verifyFormat("--(a->f());");
9047   verifyFormat("(a->f())++;");
9048   verifyFormat("a[42]++;");
9049   verifyFormat("if (!(a->f())) {\n}");
9050   verifyFormat("if (!+i) {\n}");
9051   verifyFormat("~&a;");
9052 
9053   verifyFormat("a-- > b;");
9054   verifyFormat("b ? -a : c;");
9055   verifyFormat("n * sizeof char16;");
9056   verifyFormat("n * alignof char16;", getGoogleStyle());
9057   verifyFormat("sizeof(char);");
9058   verifyFormat("alignof(char);", getGoogleStyle());
9059 
9060   verifyFormat("return -1;");
9061   verifyFormat("throw -1;");
9062   verifyFormat("switch (a) {\n"
9063                "case -1:\n"
9064                "  break;\n"
9065                "}");
9066   verifyFormat("#define X -1");
9067   verifyFormat("#define X -kConstant");
9068 
9069   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9070   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9071 
9072   verifyFormat("int a = /* confusing comment */ -1;");
9073   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9074   verifyFormat("int a = i /* confusing comment */++;");
9075 
9076   verifyFormat("co_yield -1;");
9077   verifyFormat("co_return -1;");
9078 
9079   // Check that * is not treated as a binary operator when we set
9080   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9081   FormatStyle PASLeftStyle = getLLVMStyle();
9082   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9083   verifyFormat("co_return *a;", PASLeftStyle);
9084   verifyFormat("co_await *a;", PASLeftStyle);
9085   verifyFormat("co_yield *a", PASLeftStyle);
9086   verifyFormat("return *a;", PASLeftStyle);
9087 }
9088 
9089 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9090   verifyFormat("if (!aaaaaaaaaa( // break\n"
9091                "        aaaaa)) {\n"
9092                "}");
9093   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9094                "    aaaaa));");
9095   verifyFormat("*aaa = aaaaaaa( // break\n"
9096                "    bbbbbb);");
9097 }
9098 
9099 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9100   verifyFormat("bool operator<();");
9101   verifyFormat("bool operator>();");
9102   verifyFormat("bool operator=();");
9103   verifyFormat("bool operator==();");
9104   verifyFormat("bool operator!=();");
9105   verifyFormat("int operator+();");
9106   verifyFormat("int operator++();");
9107   verifyFormat("int operator++(int) volatile noexcept;");
9108   verifyFormat("bool operator,();");
9109   verifyFormat("bool operator();");
9110   verifyFormat("bool operator()();");
9111   verifyFormat("bool operator[]();");
9112   verifyFormat("operator bool();");
9113   verifyFormat("operator int();");
9114   verifyFormat("operator void *();");
9115   verifyFormat("operator SomeType<int>();");
9116   verifyFormat("operator SomeType<int, int>();");
9117   verifyFormat("operator SomeType<SomeType<int>>();");
9118   verifyFormat("void *operator new(std::size_t size);");
9119   verifyFormat("void *operator new[](std::size_t size);");
9120   verifyFormat("void operator delete(void *ptr);");
9121   verifyFormat("void operator delete[](void *ptr);");
9122   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9123                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9124   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9125                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9126 
9127   verifyFormat(
9128       "ostream &operator<<(ostream &OutputStream,\n"
9129       "                    SomeReallyLongType WithSomeReallyLongValue);");
9130   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9131                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9132                "  return left.group < right.group;\n"
9133                "}");
9134   verifyFormat("SomeType &operator=(const SomeType &S);");
9135   verifyFormat("f.template operator()<int>();");
9136 
9137   verifyGoogleFormat("operator void*();");
9138   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9139   verifyGoogleFormat("operator ::A();");
9140 
9141   verifyFormat("using A::operator+;");
9142   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9143                "int i;");
9144 
9145   // Calling an operator as a member function.
9146   verifyFormat("void f() { a.operator*(); }");
9147   verifyFormat("void f() { a.operator*(b & b); }");
9148   verifyFormat("void f() { a->operator&(a * b); }");
9149   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9150   // TODO: Calling an operator as a non-member function is hard to distinguish.
9151   // https://llvm.org/PR50629
9152   // verifyFormat("void f() { operator*(a & a); }");
9153   // verifyFormat("void f() { operator&(a, b * b); }");
9154 }
9155 
9156 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9157   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9158   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9159   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9160   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9161   verifyFormat("Deleted &operator=(const Deleted &) &;");
9162   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9163   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9164   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9165   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9166   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9167   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9168   verifyFormat("void Fn(T const &) const &;");
9169   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9170   verifyFormat("template <typename T>\n"
9171                "void F(T) && = delete;",
9172                getGoogleStyle());
9173 
9174   FormatStyle AlignLeft = getLLVMStyle();
9175   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9176   verifyFormat("void A::b() && {}", AlignLeft);
9177   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9178   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9179                AlignLeft);
9180   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9181   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9182   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9183   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9184   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9185   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9186   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9187   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9188 
9189   FormatStyle Spaces = getLLVMStyle();
9190   Spaces.SpacesInCStyleCastParentheses = true;
9191   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9192   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9193   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9194   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9195 
9196   Spaces.SpacesInCStyleCastParentheses = false;
9197   Spaces.SpacesInParentheses = true;
9198   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9199   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9200                Spaces);
9201   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9202   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9203 
9204   FormatStyle BreakTemplate = getLLVMStyle();
9205   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9206 
9207   verifyFormat("struct f {\n"
9208                "  template <class T>\n"
9209                "  int &foo(const std::string &str) &noexcept {}\n"
9210                "};",
9211                BreakTemplate);
9212 
9213   verifyFormat("struct f {\n"
9214                "  template <class T>\n"
9215                "  int &foo(const std::string &str) &&noexcept {}\n"
9216                "};",
9217                BreakTemplate);
9218 
9219   verifyFormat("struct f {\n"
9220                "  template <class T>\n"
9221                "  int &foo(const std::string &str) const &noexcept {}\n"
9222                "};",
9223                BreakTemplate);
9224 
9225   verifyFormat("struct f {\n"
9226                "  template <class T>\n"
9227                "  int &foo(const std::string &str) const &noexcept {}\n"
9228                "};",
9229                BreakTemplate);
9230 
9231   verifyFormat("struct f {\n"
9232                "  template <class T>\n"
9233                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
9234                "};",
9235                BreakTemplate);
9236 
9237   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
9238   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
9239       FormatStyle::BTDS_Yes;
9240   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
9241 
9242   verifyFormat("struct f {\n"
9243                "  template <class T>\n"
9244                "  int& foo(const std::string& str) & noexcept {}\n"
9245                "};",
9246                AlignLeftBreakTemplate);
9247 
9248   verifyFormat("struct f {\n"
9249                "  template <class T>\n"
9250                "  int& foo(const std::string& str) && noexcept {}\n"
9251                "};",
9252                AlignLeftBreakTemplate);
9253 
9254   verifyFormat("struct f {\n"
9255                "  template <class T>\n"
9256                "  int& foo(const std::string& str) const& noexcept {}\n"
9257                "};",
9258                AlignLeftBreakTemplate);
9259 
9260   verifyFormat("struct f {\n"
9261                "  template <class T>\n"
9262                "  int& foo(const std::string& str) const&& noexcept {}\n"
9263                "};",
9264                AlignLeftBreakTemplate);
9265 
9266   verifyFormat("struct f {\n"
9267                "  template <class T>\n"
9268                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
9269                "};",
9270                AlignLeftBreakTemplate);
9271 
9272   // The `&` in `Type&` should not be confused with a trailing `&` of
9273   // DEPRECATED(reason) member function.
9274   verifyFormat("struct f {\n"
9275                "  template <class T>\n"
9276                "  DEPRECATED(reason)\n"
9277                "  Type &foo(arguments) {}\n"
9278                "};",
9279                BreakTemplate);
9280 
9281   verifyFormat("struct f {\n"
9282                "  template <class T>\n"
9283                "  DEPRECATED(reason)\n"
9284                "  Type& foo(arguments) {}\n"
9285                "};",
9286                AlignLeftBreakTemplate);
9287 
9288   verifyFormat("void (*foopt)(int) = &func;");
9289 }
9290 
9291 TEST_F(FormatTest, UnderstandsNewAndDelete) {
9292   verifyFormat("void f() {\n"
9293                "  A *a = new A;\n"
9294                "  A *a = new (placement) A;\n"
9295                "  delete a;\n"
9296                "  delete (A *)a;\n"
9297                "}");
9298   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9299                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9300   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9301                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9302                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9303   verifyFormat("delete[] h->p;");
9304 }
9305 
9306 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
9307   verifyFormat("int *f(int *a) {}");
9308   verifyFormat("int main(int argc, char **argv) {}");
9309   verifyFormat("Test::Test(int b) : a(b * b) {}");
9310   verifyIndependentOfContext("f(a, *a);");
9311   verifyFormat("void g() { f(*a); }");
9312   verifyIndependentOfContext("int a = b * 10;");
9313   verifyIndependentOfContext("int a = 10 * b;");
9314   verifyIndependentOfContext("int a = b * c;");
9315   verifyIndependentOfContext("int a += b * c;");
9316   verifyIndependentOfContext("int a -= b * c;");
9317   verifyIndependentOfContext("int a *= b * c;");
9318   verifyIndependentOfContext("int a /= b * c;");
9319   verifyIndependentOfContext("int a = *b;");
9320   verifyIndependentOfContext("int a = *b * c;");
9321   verifyIndependentOfContext("int a = b * *c;");
9322   verifyIndependentOfContext("int a = b * (10);");
9323   verifyIndependentOfContext("S << b * (10);");
9324   verifyIndependentOfContext("return 10 * b;");
9325   verifyIndependentOfContext("return *b * *c;");
9326   verifyIndependentOfContext("return a & ~b;");
9327   verifyIndependentOfContext("f(b ? *c : *d);");
9328   verifyIndependentOfContext("int a = b ? *c : *d;");
9329   verifyIndependentOfContext("*b = a;");
9330   verifyIndependentOfContext("a * ~b;");
9331   verifyIndependentOfContext("a * !b;");
9332   verifyIndependentOfContext("a * +b;");
9333   verifyIndependentOfContext("a * -b;");
9334   verifyIndependentOfContext("a * ++b;");
9335   verifyIndependentOfContext("a * --b;");
9336   verifyIndependentOfContext("a[4] * b;");
9337   verifyIndependentOfContext("a[a * a] = 1;");
9338   verifyIndependentOfContext("f() * b;");
9339   verifyIndependentOfContext("a * [self dostuff];");
9340   verifyIndependentOfContext("int x = a * (a + b);");
9341   verifyIndependentOfContext("(a *)(a + b);");
9342   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
9343   verifyIndependentOfContext("int *pa = (int *)&a;");
9344   verifyIndependentOfContext("return sizeof(int **);");
9345   verifyIndependentOfContext("return sizeof(int ******);");
9346   verifyIndependentOfContext("return (int **&)a;");
9347   verifyIndependentOfContext("f((*PointerToArray)[10]);");
9348   verifyFormat("void f(Type (*parameter)[10]) {}");
9349   verifyFormat("void f(Type (&parameter)[10]) {}");
9350   verifyGoogleFormat("return sizeof(int**);");
9351   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
9352   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
9353   verifyFormat("auto a = [](int **&, int ***) {};");
9354   verifyFormat("auto PointerBinding = [](const char *S) {};");
9355   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
9356   verifyFormat("[](const decltype(*a) &value) {}");
9357   verifyFormat("[](const typeof(*a) &value) {}");
9358   verifyFormat("[](const _Atomic(a *) &value) {}");
9359   verifyFormat("[](const __underlying_type(a) &value) {}");
9360   verifyFormat("decltype(a * b) F();");
9361   verifyFormat("typeof(a * b) F();");
9362   verifyFormat("#define MACRO() [](A *a) { return 1; }");
9363   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
9364   verifyIndependentOfContext("typedef void (*f)(int *a);");
9365   verifyIndependentOfContext("int i{a * b};");
9366   verifyIndependentOfContext("aaa && aaa->f();");
9367   verifyIndependentOfContext("int x = ~*p;");
9368   verifyFormat("Constructor() : a(a), area(width * height) {}");
9369   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
9370   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
9371   verifyFormat("void f() { f(a, c * d); }");
9372   verifyFormat("void f() { f(new a(), c * d); }");
9373   verifyFormat("void f(const MyOverride &override);");
9374   verifyFormat("void f(const MyFinal &final);");
9375   verifyIndependentOfContext("bool a = f() && override.f();");
9376   verifyIndependentOfContext("bool a = f() && final.f();");
9377 
9378   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
9379 
9380   verifyIndependentOfContext("A<int *> a;");
9381   verifyIndependentOfContext("A<int **> a;");
9382   verifyIndependentOfContext("A<int *, int *> a;");
9383   verifyIndependentOfContext("A<int *[]> a;");
9384   verifyIndependentOfContext(
9385       "const char *const p = reinterpret_cast<const char *const>(q);");
9386   verifyIndependentOfContext("A<int **, int **> a;");
9387   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
9388   verifyFormat("for (char **a = b; *a; ++a) {\n}");
9389   verifyFormat("for (; a && b;) {\n}");
9390   verifyFormat("bool foo = true && [] { return false; }();");
9391 
9392   verifyFormat(
9393       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9394       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9395 
9396   verifyGoogleFormat("int const* a = &b;");
9397   verifyGoogleFormat("**outparam = 1;");
9398   verifyGoogleFormat("*outparam = a * b;");
9399   verifyGoogleFormat("int main(int argc, char** argv) {}");
9400   verifyGoogleFormat("A<int*> a;");
9401   verifyGoogleFormat("A<int**> a;");
9402   verifyGoogleFormat("A<int*, int*> a;");
9403   verifyGoogleFormat("A<int**, int**> a;");
9404   verifyGoogleFormat("f(b ? *c : *d);");
9405   verifyGoogleFormat("int a = b ? *c : *d;");
9406   verifyGoogleFormat("Type* t = **x;");
9407   verifyGoogleFormat("Type* t = *++*x;");
9408   verifyGoogleFormat("*++*x;");
9409   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
9410   verifyGoogleFormat("Type* t = x++ * y;");
9411   verifyGoogleFormat(
9412       "const char* const p = reinterpret_cast<const char* const>(q);");
9413   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
9414   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
9415   verifyGoogleFormat("template <typename T>\n"
9416                      "void f(int i = 0, SomeType** temps = NULL);");
9417 
9418   FormatStyle Left = getLLVMStyle();
9419   Left.PointerAlignment = FormatStyle::PAS_Left;
9420   verifyFormat("x = *a(x) = *a(y);", Left);
9421   verifyFormat("for (;; *a = b) {\n}", Left);
9422   verifyFormat("return *this += 1;", Left);
9423   verifyFormat("throw *x;", Left);
9424   verifyFormat("delete *x;", Left);
9425   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
9426   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
9427   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
9428   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
9429   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
9430   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
9431   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
9432   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
9433   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
9434 
9435   verifyIndependentOfContext("a = *(x + y);");
9436   verifyIndependentOfContext("a = &(x + y);");
9437   verifyIndependentOfContext("*(x + y).call();");
9438   verifyIndependentOfContext("&(x + y)->call();");
9439   verifyFormat("void f() { &(*I).first; }");
9440 
9441   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
9442   verifyFormat(
9443       "int *MyValues = {\n"
9444       "    *A, // Operator detection might be confused by the '{'\n"
9445       "    *BB // Operator detection might be confused by previous comment\n"
9446       "};");
9447 
9448   verifyIndependentOfContext("if (int *a = &b)");
9449   verifyIndependentOfContext("if (int &a = *b)");
9450   verifyIndependentOfContext("if (a & b[i])");
9451   verifyIndependentOfContext("if constexpr (a & b[i])");
9452   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
9453   verifyIndependentOfContext("if (a * (b * c))");
9454   verifyIndependentOfContext("if constexpr (a * (b * c))");
9455   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
9456   verifyIndependentOfContext("if (a::b::c::d & b[i])");
9457   verifyIndependentOfContext("if (*b[i])");
9458   verifyIndependentOfContext("if (int *a = (&b))");
9459   verifyIndependentOfContext("while (int *a = &b)");
9460   verifyIndependentOfContext("while (a * (b * c))");
9461   verifyIndependentOfContext("size = sizeof *a;");
9462   verifyIndependentOfContext("if (a && (b = c))");
9463   verifyFormat("void f() {\n"
9464                "  for (const int &v : Values) {\n"
9465                "  }\n"
9466                "}");
9467   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
9468   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
9469   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
9470 
9471   verifyFormat("#define A (!a * b)");
9472   verifyFormat("#define MACRO     \\\n"
9473                "  int *i = a * b; \\\n"
9474                "  void f(a *b);",
9475                getLLVMStyleWithColumns(19));
9476 
9477   verifyIndependentOfContext("A = new SomeType *[Length];");
9478   verifyIndependentOfContext("A = new SomeType *[Length]();");
9479   verifyIndependentOfContext("T **t = new T *;");
9480   verifyIndependentOfContext("T **t = new T *();");
9481   verifyGoogleFormat("A = new SomeType*[Length]();");
9482   verifyGoogleFormat("A = new SomeType*[Length];");
9483   verifyGoogleFormat("T** t = new T*;");
9484   verifyGoogleFormat("T** t = new T*();");
9485 
9486   verifyFormat("STATIC_ASSERT((a & b) == 0);");
9487   verifyFormat("STATIC_ASSERT(0 == (a & b));");
9488   verifyFormat("template <bool a, bool b> "
9489                "typename t::if<x && y>::type f() {}");
9490   verifyFormat("template <int *y> f() {}");
9491   verifyFormat("vector<int *> v;");
9492   verifyFormat("vector<int *const> v;");
9493   verifyFormat("vector<int *const **const *> v;");
9494   verifyFormat("vector<int *volatile> v;");
9495   verifyFormat("vector<a *_Nonnull> v;");
9496   verifyFormat("vector<a *_Nullable> v;");
9497   verifyFormat("vector<a *_Null_unspecified> v;");
9498   verifyFormat("vector<a *__ptr32> v;");
9499   verifyFormat("vector<a *__ptr64> v;");
9500   verifyFormat("vector<a *__capability> v;");
9501   FormatStyle TypeMacros = getLLVMStyle();
9502   TypeMacros.TypenameMacros = {"LIST"};
9503   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
9504   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
9505   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
9506   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
9507   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
9508 
9509   FormatStyle CustomQualifier = getLLVMStyle();
9510   // Add identifiers that should not be parsed as a qualifier by default.
9511   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9512   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
9513   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
9514   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
9515   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
9516   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
9517   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
9518   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
9519   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
9520   verifyFormat("vector<a * _NotAQualifier> v;");
9521   verifyFormat("vector<a * __not_a_qualifier> v;");
9522   verifyFormat("vector<a * b> v;");
9523   verifyFormat("foo<b && false>();");
9524   verifyFormat("foo<b & 1>();");
9525   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
9526   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
9527   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
9528   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
9529   verifyFormat(
9530       "template <class T, class = typename std::enable_if<\n"
9531       "                       std::is_integral<T>::value &&\n"
9532       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
9533       "void F();",
9534       getLLVMStyleWithColumns(70));
9535   verifyFormat("template <class T,\n"
9536                "          class = typename std::enable_if<\n"
9537                "              std::is_integral<T>::value &&\n"
9538                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
9539                "          class U>\n"
9540                "void F();",
9541                getLLVMStyleWithColumns(70));
9542   verifyFormat(
9543       "template <class T,\n"
9544       "          class = typename ::std::enable_if<\n"
9545       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
9546       "void F();",
9547       getGoogleStyleWithColumns(68));
9548 
9549   verifyIndependentOfContext("MACRO(int *i);");
9550   verifyIndependentOfContext("MACRO(auto *a);");
9551   verifyIndependentOfContext("MACRO(const A *a);");
9552   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
9553   verifyIndependentOfContext("MACRO(decltype(A) *a);");
9554   verifyIndependentOfContext("MACRO(typeof(A) *a);");
9555   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
9556   verifyIndependentOfContext("MACRO(A *const a);");
9557   verifyIndependentOfContext("MACRO(A *restrict a);");
9558   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
9559   verifyIndependentOfContext("MACRO(A *__restrict a);");
9560   verifyIndependentOfContext("MACRO(A *volatile a);");
9561   verifyIndependentOfContext("MACRO(A *__volatile a);");
9562   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
9563   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
9564   verifyIndependentOfContext("MACRO(A *_Nullable a);");
9565   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
9566   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
9567   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
9568   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
9569   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
9570   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
9571   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
9572   verifyIndependentOfContext("MACRO(A *__capability);");
9573   verifyIndependentOfContext("MACRO(A &__capability);");
9574   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
9575   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
9576   // If we add __my_qualifier to AttributeMacros it should always be parsed as
9577   // a type declaration:
9578   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
9579   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
9580   // Also check that TypenameMacros prevents parsing it as multiplication:
9581   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
9582   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
9583 
9584   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
9585   verifyFormat("void f() { f(float{1}, a * a); }");
9586   verifyFormat("void f() { f(float(1), a * a); }");
9587 
9588   verifyFormat("f((void (*)(int))g);");
9589   verifyFormat("f((void (&)(int))g);");
9590   verifyFormat("f((void (^)(int))g);");
9591 
9592   // FIXME: Is there a way to make this work?
9593   // verifyIndependentOfContext("MACRO(A *a);");
9594   verifyFormat("MACRO(A &B);");
9595   verifyFormat("MACRO(A *B);");
9596   verifyFormat("void f() { MACRO(A * B); }");
9597   verifyFormat("void f() { MACRO(A & B); }");
9598 
9599   // This lambda was mis-formatted after D88956 (treating it as a binop):
9600   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
9601   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
9602   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
9603   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
9604 
9605   verifyFormat("DatumHandle const *operator->() const { return input_; }");
9606   verifyFormat("return options != nullptr && operator==(*options);");
9607 
9608   EXPECT_EQ("#define OP(x)                                    \\\n"
9609             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
9610             "    return s << a.DebugString();                 \\\n"
9611             "  }",
9612             format("#define OP(x) \\\n"
9613                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
9614                    "    return s << a.DebugString(); \\\n"
9615                    "  }",
9616                    getLLVMStyleWithColumns(50)));
9617 
9618   // FIXME: We cannot handle this case yet; we might be able to figure out that
9619   // foo<x> d > v; doesn't make sense.
9620   verifyFormat("foo<a<b && c> d> v;");
9621 
9622   FormatStyle PointerMiddle = getLLVMStyle();
9623   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9624   verifyFormat("delete *x;", PointerMiddle);
9625   verifyFormat("int * x;", PointerMiddle);
9626   verifyFormat("int *[] x;", PointerMiddle);
9627   verifyFormat("template <int * y> f() {}", PointerMiddle);
9628   verifyFormat("int * f(int * a) {}", PointerMiddle);
9629   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
9630   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
9631   verifyFormat("A<int *> a;", PointerMiddle);
9632   verifyFormat("A<int **> a;", PointerMiddle);
9633   verifyFormat("A<int *, int *> a;", PointerMiddle);
9634   verifyFormat("A<int *[]> a;", PointerMiddle);
9635   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
9636   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
9637   verifyFormat("T ** t = new T *;", PointerMiddle);
9638 
9639   // Member function reference qualifiers aren't binary operators.
9640   verifyFormat("string // break\n"
9641                "operator()() & {}");
9642   verifyFormat("string // break\n"
9643                "operator()() && {}");
9644   verifyGoogleFormat("template <typename T>\n"
9645                      "auto x() & -> int {}");
9646 
9647   // Should be binary operators when used as an argument expression (overloaded
9648   // operator invoked as a member function).
9649   verifyFormat("void f() { a.operator()(a * a); }");
9650   verifyFormat("void f() { a->operator()(a & a); }");
9651   verifyFormat("void f() { a.operator()(*a & *a); }");
9652   verifyFormat("void f() { a->operator()(*a * *a); }");
9653 }
9654 
9655 TEST_F(FormatTest, UnderstandsAttributes) {
9656   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
9657   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
9658                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9659   FormatStyle AfterType = getLLVMStyle();
9660   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
9661   verifyFormat("__attribute__((nodebug)) void\n"
9662                "foo() {}\n",
9663                AfterType);
9664   verifyFormat("__unused void\n"
9665                "foo() {}",
9666                AfterType);
9667 
9668   FormatStyle CustomAttrs = getLLVMStyle();
9669   CustomAttrs.AttributeMacros.push_back("__unused");
9670   CustomAttrs.AttributeMacros.push_back("__attr1");
9671   CustomAttrs.AttributeMacros.push_back("__attr2");
9672   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
9673   verifyFormat("vector<SomeType *__attribute((foo))> v;");
9674   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
9675   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
9676   // Check that it is parsed as a multiplication without AttributeMacros and
9677   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
9678   verifyFormat("vector<SomeType * __attr1> v;");
9679   verifyFormat("vector<SomeType __attr1 *> v;");
9680   verifyFormat("vector<SomeType __attr1 *const> v;");
9681   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
9682   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
9683   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
9684   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
9685   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
9686   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
9687   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
9688   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
9689 
9690   // Check that these are not parsed as function declarations:
9691   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9692   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
9693   verifyFormat("SomeType s(InitValue);", CustomAttrs);
9694   verifyFormat("SomeType s{InitValue};", CustomAttrs);
9695   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
9696   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
9697   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
9698   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
9699   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
9700   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
9701 }
9702 
9703 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
9704   // Check that qualifiers on pointers don't break parsing of casts.
9705   verifyFormat("x = (foo *const)*v;");
9706   verifyFormat("x = (foo *volatile)*v;");
9707   verifyFormat("x = (foo *restrict)*v;");
9708   verifyFormat("x = (foo *__attribute__((foo)))*v;");
9709   verifyFormat("x = (foo *_Nonnull)*v;");
9710   verifyFormat("x = (foo *_Nullable)*v;");
9711   verifyFormat("x = (foo *_Null_unspecified)*v;");
9712   verifyFormat("x = (foo *_Nonnull)*v;");
9713   verifyFormat("x = (foo *[[clang::attr]])*v;");
9714   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
9715   verifyFormat("x = (foo *__ptr32)*v;");
9716   verifyFormat("x = (foo *__ptr64)*v;");
9717   verifyFormat("x = (foo *__capability)*v;");
9718 
9719   // Check that we handle multiple trailing qualifiers and skip them all to
9720   // determine that the expression is a cast to a pointer type.
9721   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
9722   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
9723   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
9724   StringRef AllQualifiers =
9725       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
9726       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
9727   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
9728   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
9729 
9730   // Also check that address-of is not parsed as a binary bitwise-and:
9731   verifyFormat("x = (foo *const)&v;");
9732   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
9733   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
9734 
9735   // Check custom qualifiers:
9736   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
9737   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9738   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
9739   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
9740   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
9741                CustomQualifier);
9742   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
9743                CustomQualifier);
9744 
9745   // Check that unknown identifiers result in binary operator parsing:
9746   verifyFormat("x = (foo * __unknown_qualifier) * v;");
9747   verifyFormat("x = (foo * __unknown_qualifier) & v;");
9748 }
9749 
9750 TEST_F(FormatTest, UnderstandsSquareAttributes) {
9751   verifyFormat("SomeType s [[unused]] (InitValue);");
9752   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
9753   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
9754   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
9755   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
9756   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9757                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9758   verifyFormat("[[nodiscard]] bool f() { return false; }");
9759   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
9760   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
9761   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
9762 
9763   // Make sure we do not mistake attributes for array subscripts.
9764   verifyFormat("int a() {}\n"
9765                "[[unused]] int b() {}\n");
9766   verifyFormat("NSArray *arr;\n"
9767                "arr[[Foo() bar]];");
9768 
9769   // On the other hand, we still need to correctly find array subscripts.
9770   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
9771 
9772   // Make sure that we do not mistake Objective-C method inside array literals
9773   // as attributes, even if those method names are also keywords.
9774   verifyFormat("@[ [foo bar] ];");
9775   verifyFormat("@[ [NSArray class] ];");
9776   verifyFormat("@[ [foo enum] ];");
9777 
9778   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
9779 
9780   // Make sure we do not parse attributes as lambda introducers.
9781   FormatStyle MultiLineFunctions = getLLVMStyle();
9782   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9783   verifyFormat("[[unused]] int b() {\n"
9784                "  return 42;\n"
9785                "}\n",
9786                MultiLineFunctions);
9787 }
9788 
9789 TEST_F(FormatTest, AttributeClass) {
9790   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
9791   verifyFormat("class S {\n"
9792                "  S(S&&) = default;\n"
9793                "};",
9794                Style);
9795   verifyFormat("class [[nodiscard]] S {\n"
9796                "  S(S&&) = default;\n"
9797                "};",
9798                Style);
9799   verifyFormat("class __attribute((maybeunused)) S {\n"
9800                "  S(S&&) = default;\n"
9801                "};",
9802                Style);
9803   verifyFormat("struct S {\n"
9804                "  S(S&&) = default;\n"
9805                "};",
9806                Style);
9807   verifyFormat("struct [[nodiscard]] S {\n"
9808                "  S(S&&) = default;\n"
9809                "};",
9810                Style);
9811 }
9812 
9813 TEST_F(FormatTest, AttributesAfterMacro) {
9814   FormatStyle Style = getLLVMStyle();
9815   verifyFormat("MACRO;\n"
9816                "__attribute__((maybe_unused)) int foo() {\n"
9817                "  //...\n"
9818                "}");
9819 
9820   verifyFormat("MACRO;\n"
9821                "[[nodiscard]] int foo() {\n"
9822                "  //...\n"
9823                "}");
9824 
9825   EXPECT_EQ("MACRO\n\n"
9826             "__attribute__((maybe_unused)) int foo() {\n"
9827             "  //...\n"
9828             "}",
9829             format("MACRO\n\n"
9830                    "__attribute__((maybe_unused)) int foo() {\n"
9831                    "  //...\n"
9832                    "}"));
9833 
9834   EXPECT_EQ("MACRO\n\n"
9835             "[[nodiscard]] int foo() {\n"
9836             "  //...\n"
9837             "}",
9838             format("MACRO\n\n"
9839                    "[[nodiscard]] int foo() {\n"
9840                    "  //...\n"
9841                    "}"));
9842 }
9843 
9844 TEST_F(FormatTest, AttributePenaltyBreaking) {
9845   FormatStyle Style = getLLVMStyle();
9846   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
9847                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
9848                Style);
9849   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
9850                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
9851                Style);
9852   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
9853                "shared_ptr<ALongTypeName> &C d) {\n}",
9854                Style);
9855 }
9856 
9857 TEST_F(FormatTest, UnderstandsEllipsis) {
9858   FormatStyle Style = getLLVMStyle();
9859   verifyFormat("int printf(const char *fmt, ...);");
9860   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
9861   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
9862 
9863   verifyFormat("template <int *...PP> a;", Style);
9864 
9865   Style.PointerAlignment = FormatStyle::PAS_Left;
9866   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
9867 
9868   verifyFormat("template <int*... PP> a;", Style);
9869 
9870   Style.PointerAlignment = FormatStyle::PAS_Middle;
9871   verifyFormat("template <int *... PP> a;", Style);
9872 }
9873 
9874 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
9875   EXPECT_EQ("int *a;\n"
9876             "int *a;\n"
9877             "int *a;",
9878             format("int *a;\n"
9879                    "int* a;\n"
9880                    "int *a;",
9881                    getGoogleStyle()));
9882   EXPECT_EQ("int* a;\n"
9883             "int* a;\n"
9884             "int* a;",
9885             format("int* a;\n"
9886                    "int* a;\n"
9887                    "int *a;",
9888                    getGoogleStyle()));
9889   EXPECT_EQ("int *a;\n"
9890             "int *a;\n"
9891             "int *a;",
9892             format("int *a;\n"
9893                    "int * a;\n"
9894                    "int *  a;",
9895                    getGoogleStyle()));
9896   EXPECT_EQ("auto x = [] {\n"
9897             "  int *a;\n"
9898             "  int *a;\n"
9899             "  int *a;\n"
9900             "};",
9901             format("auto x=[]{int *a;\n"
9902                    "int * a;\n"
9903                    "int *  a;};",
9904                    getGoogleStyle()));
9905 }
9906 
9907 TEST_F(FormatTest, UnderstandsRvalueReferences) {
9908   verifyFormat("int f(int &&a) {}");
9909   verifyFormat("int f(int a, char &&b) {}");
9910   verifyFormat("void f() { int &&a = b; }");
9911   verifyGoogleFormat("int f(int a, char&& b) {}");
9912   verifyGoogleFormat("void f() { int&& a = b; }");
9913 
9914   verifyIndependentOfContext("A<int &&> a;");
9915   verifyIndependentOfContext("A<int &&, int &&> a;");
9916   verifyGoogleFormat("A<int&&> a;");
9917   verifyGoogleFormat("A<int&&, int&&> a;");
9918 
9919   // Not rvalue references:
9920   verifyFormat("template <bool B, bool C> class A {\n"
9921                "  static_assert(B && C, \"Something is wrong\");\n"
9922                "};");
9923   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
9924   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
9925   verifyFormat("#define A(a, b) (a && b)");
9926 }
9927 
9928 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
9929   verifyFormat("void f() {\n"
9930                "  x[aaaaaaaaa -\n"
9931                "    b] = 23;\n"
9932                "}",
9933                getLLVMStyleWithColumns(15));
9934 }
9935 
9936 TEST_F(FormatTest, FormatsCasts) {
9937   verifyFormat("Type *A = static_cast<Type *>(P);");
9938   verifyFormat("Type *A = (Type *)P;");
9939   verifyFormat("Type *A = (vector<Type *, int *>)P;");
9940   verifyFormat("int a = (int)(2.0f);");
9941   verifyFormat("int a = (int)2.0f;");
9942   verifyFormat("x[(int32)y];");
9943   verifyFormat("x = (int32)y;");
9944   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
9945   verifyFormat("int a = (int)*b;");
9946   verifyFormat("int a = (int)2.0f;");
9947   verifyFormat("int a = (int)~0;");
9948   verifyFormat("int a = (int)++a;");
9949   verifyFormat("int a = (int)sizeof(int);");
9950   verifyFormat("int a = (int)+2;");
9951   verifyFormat("my_int a = (my_int)2.0f;");
9952   verifyFormat("my_int a = (my_int)sizeof(int);");
9953   verifyFormat("return (my_int)aaa;");
9954   verifyFormat("#define x ((int)-1)");
9955   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
9956   verifyFormat("#define p(q) ((int *)&q)");
9957   verifyFormat("fn(a)(b) + 1;");
9958 
9959   verifyFormat("void f() { my_int a = (my_int)*b; }");
9960   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
9961   verifyFormat("my_int a = (my_int)~0;");
9962   verifyFormat("my_int a = (my_int)++a;");
9963   verifyFormat("my_int a = (my_int)-2;");
9964   verifyFormat("my_int a = (my_int)1;");
9965   verifyFormat("my_int a = (my_int *)1;");
9966   verifyFormat("my_int a = (const my_int)-1;");
9967   verifyFormat("my_int a = (const my_int *)-1;");
9968   verifyFormat("my_int a = (my_int)(my_int)-1;");
9969   verifyFormat("my_int a = (ns::my_int)-2;");
9970   verifyFormat("case (my_int)ONE:");
9971   verifyFormat("auto x = (X)this;");
9972   // Casts in Obj-C style calls used to not be recognized as such.
9973   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
9974 
9975   // FIXME: single value wrapped with paren will be treated as cast.
9976   verifyFormat("void f(int i = (kValue)*kMask) {}");
9977 
9978   verifyFormat("{ (void)F; }");
9979 
9980   // Don't break after a cast's
9981   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9982                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
9983                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
9984 
9985   // These are not casts.
9986   verifyFormat("void f(int *) {}");
9987   verifyFormat("f(foo)->b;");
9988   verifyFormat("f(foo).b;");
9989   verifyFormat("f(foo)(b);");
9990   verifyFormat("f(foo)[b];");
9991   verifyFormat("[](foo) { return 4; }(bar);");
9992   verifyFormat("(*funptr)(foo)[4];");
9993   verifyFormat("funptrs[4](foo)[4];");
9994   verifyFormat("void f(int *);");
9995   verifyFormat("void f(int *) = 0;");
9996   verifyFormat("void f(SmallVector<int>) {}");
9997   verifyFormat("void f(SmallVector<int>);");
9998   verifyFormat("void f(SmallVector<int>) = 0;");
9999   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10000   verifyFormat("int a = sizeof(int) * b;");
10001   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10002   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10003   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10004   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10005 
10006   // These are not casts, but at some point were confused with casts.
10007   verifyFormat("virtual void foo(int *) override;");
10008   verifyFormat("virtual void foo(char &) const;");
10009   verifyFormat("virtual void foo(int *a, char *) const;");
10010   verifyFormat("int a = sizeof(int *) + b;");
10011   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10012   verifyFormat("bool b = f(g<int>) && c;");
10013   verifyFormat("typedef void (*f)(int i) func;");
10014   verifyFormat("void operator++(int) noexcept;");
10015   verifyFormat("void operator++(int &) noexcept;");
10016   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10017                "&) noexcept;");
10018   verifyFormat(
10019       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10020   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10021   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10022   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10023   verifyFormat("void operator delete(foo &) noexcept;");
10024   verifyFormat("void operator delete(foo) noexcept;");
10025   verifyFormat("void operator delete(int) noexcept;");
10026   verifyFormat("void operator delete(int &) noexcept;");
10027   verifyFormat("void operator delete(int &) volatile noexcept;");
10028   verifyFormat("void operator delete(int &) const");
10029   verifyFormat("void operator delete(int &) = default");
10030   verifyFormat("void operator delete(int &) = delete");
10031   verifyFormat("void operator delete(int &) [[noreturn]]");
10032   verifyFormat("void operator delete(int &) throw();");
10033   verifyFormat("void operator delete(int &) throw(int);");
10034   verifyFormat("auto operator delete(int &) -> int;");
10035   verifyFormat("auto operator delete(int &) override");
10036   verifyFormat("auto operator delete(int &) final");
10037 
10038   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10039                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10040   // FIXME: The indentation here is not ideal.
10041   verifyFormat(
10042       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10043       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10044       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10045 }
10046 
10047 TEST_F(FormatTest, FormatsFunctionTypes) {
10048   verifyFormat("A<bool()> a;");
10049   verifyFormat("A<SomeType()> a;");
10050   verifyFormat("A<void (*)(int, std::string)> a;");
10051   verifyFormat("A<void *(int)>;");
10052   verifyFormat("void *(*a)(int *, SomeType *);");
10053   verifyFormat("int (*func)(void *);");
10054   verifyFormat("void f() { int (*func)(void *); }");
10055   verifyFormat("template <class CallbackClass>\n"
10056                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10057 
10058   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10059   verifyGoogleFormat("void* (*a)(int);");
10060   verifyGoogleFormat(
10061       "template <class CallbackClass>\n"
10062       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10063 
10064   // Other constructs can look somewhat like function types:
10065   verifyFormat("A<sizeof(*x)> a;");
10066   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10067   verifyFormat("some_var = function(*some_pointer_var)[0];");
10068   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10069   verifyFormat("int x = f(&h)();");
10070   verifyFormat("returnsFunction(&param1, &param2)(param);");
10071   verifyFormat("std::function<\n"
10072                "    LooooooooooongTemplatedType<\n"
10073                "        SomeType>*(\n"
10074                "        LooooooooooooooooongType type)>\n"
10075                "    function;",
10076                getGoogleStyleWithColumns(40));
10077 }
10078 
10079 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10080   verifyFormat("A (*foo_)[6];");
10081   verifyFormat("vector<int> (*foo_)[6];");
10082 }
10083 
10084 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10085   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10086                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10087   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10088                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10089   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10090                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10091 
10092   // Different ways of ()-initializiation.
10093   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10094                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10095   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10096                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10097   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10098                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10099   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10100                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10101 
10102   // Lambdas should not confuse the variable declaration heuristic.
10103   verifyFormat("LooooooooooooooooongType\n"
10104                "    variable(nullptr, [](A *a) {});",
10105                getLLVMStyleWithColumns(40));
10106 }
10107 
10108 TEST_F(FormatTest, BreaksLongDeclarations) {
10109   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10110                "    AnotherNameForTheLongType;");
10111   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10112                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10113   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10114                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10115   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10116                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10117   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10118                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10119   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10120                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10121   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10122                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10123   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10124                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10125   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10126                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10127   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10128                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10129   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10130                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10131   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10132                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10133   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10134                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10135   FormatStyle Indented = getLLVMStyle();
10136   Indented.IndentWrappedFunctionNames = true;
10137   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10138                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10139                Indented);
10140   verifyFormat(
10141       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10142       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10143       Indented);
10144   verifyFormat(
10145       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10146       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10147       Indented);
10148   verifyFormat(
10149       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10150       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10151       Indented);
10152 
10153   // FIXME: Without the comment, this breaks after "(".
10154   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10155                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10156                getGoogleStyle());
10157 
10158   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10159                "                  int LoooooooooooooooooooongParam2) {}");
10160   verifyFormat(
10161       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
10162       "                                   SourceLocation L, IdentifierIn *II,\n"
10163       "                                   Type *T) {}");
10164   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
10165                "ReallyReaaallyLongFunctionName(\n"
10166                "    const std::string &SomeParameter,\n"
10167                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10168                "        &ReallyReallyLongParameterName,\n"
10169                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10170                "        &AnotherLongParameterName) {}");
10171   verifyFormat("template <typename A>\n"
10172                "SomeLoooooooooooooooooooooongType<\n"
10173                "    typename some_namespace::SomeOtherType<A>::Type>\n"
10174                "Function() {}");
10175 
10176   verifyGoogleFormat(
10177       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
10178       "    aaaaaaaaaaaaaaaaaaaaaaa;");
10179   verifyGoogleFormat(
10180       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
10181       "                                   SourceLocation L) {}");
10182   verifyGoogleFormat(
10183       "some_namespace::LongReturnType\n"
10184       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
10185       "    int first_long_parameter, int second_parameter) {}");
10186 
10187   verifyGoogleFormat("template <typename T>\n"
10188                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10189                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
10190   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10191                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
10192 
10193   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
10194                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10195                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10196   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10197                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10198                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
10199   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10200                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
10201                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
10202                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10203 
10204   verifyFormat("template <typename T> // Templates on own line.\n"
10205                "static int            // Some comment.\n"
10206                "MyFunction(int a);",
10207                getLLVMStyle());
10208 }
10209 
10210 TEST_F(FormatTest, FormatsAccessModifiers) {
10211   FormatStyle Style = getLLVMStyle();
10212   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
10213             FormatStyle::ELBAMS_LogicalBlock);
10214   verifyFormat("struct foo {\n"
10215                "private:\n"
10216                "  void f() {}\n"
10217                "\n"
10218                "private:\n"
10219                "  int i;\n"
10220                "\n"
10221                "protected:\n"
10222                "  int j;\n"
10223                "};\n",
10224                Style);
10225   verifyFormat("struct foo {\n"
10226                "private:\n"
10227                "  void f() {}\n"
10228                "\n"
10229                "private:\n"
10230                "  int i;\n"
10231                "\n"
10232                "protected:\n"
10233                "  int j;\n"
10234                "};\n",
10235                "struct foo {\n"
10236                "private:\n"
10237                "  void f() {}\n"
10238                "private:\n"
10239                "  int i;\n"
10240                "protected:\n"
10241                "  int j;\n"
10242                "};\n",
10243                Style);
10244   verifyFormat("struct foo { /* comment */\n"
10245                "private:\n"
10246                "  int i;\n"
10247                "  // comment\n"
10248                "private:\n"
10249                "  int j;\n"
10250                "};\n",
10251                Style);
10252   verifyFormat("struct foo {\n"
10253                "#ifdef FOO\n"
10254                "#endif\n"
10255                "private:\n"
10256                "  int i;\n"
10257                "#ifdef FOO\n"
10258                "private:\n"
10259                "#endif\n"
10260                "  int j;\n"
10261                "};\n",
10262                Style);
10263   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10264   verifyFormat("struct foo {\n"
10265                "private:\n"
10266                "  void f() {}\n"
10267                "private:\n"
10268                "  int i;\n"
10269                "protected:\n"
10270                "  int j;\n"
10271                "};\n",
10272                Style);
10273   verifyFormat("struct foo {\n"
10274                "private:\n"
10275                "  void f() {}\n"
10276                "private:\n"
10277                "  int i;\n"
10278                "protected:\n"
10279                "  int j;\n"
10280                "};\n",
10281                "struct foo {\n"
10282                "\n"
10283                "private:\n"
10284                "  void f() {}\n"
10285                "\n"
10286                "private:\n"
10287                "  int i;\n"
10288                "\n"
10289                "protected:\n"
10290                "  int j;\n"
10291                "};\n",
10292                Style);
10293   verifyFormat("struct foo { /* comment */\n"
10294                "private:\n"
10295                "  int i;\n"
10296                "  // comment\n"
10297                "private:\n"
10298                "  int j;\n"
10299                "};\n",
10300                "struct foo { /* comment */\n"
10301                "\n"
10302                "private:\n"
10303                "  int i;\n"
10304                "  // comment\n"
10305                "\n"
10306                "private:\n"
10307                "  int j;\n"
10308                "};\n",
10309                Style);
10310   verifyFormat("struct foo {\n"
10311                "#ifdef FOO\n"
10312                "#endif\n"
10313                "private:\n"
10314                "  int i;\n"
10315                "#ifdef FOO\n"
10316                "private:\n"
10317                "#endif\n"
10318                "  int j;\n"
10319                "};\n",
10320                "struct foo {\n"
10321                "#ifdef FOO\n"
10322                "#endif\n"
10323                "\n"
10324                "private:\n"
10325                "  int i;\n"
10326                "#ifdef FOO\n"
10327                "\n"
10328                "private:\n"
10329                "#endif\n"
10330                "  int j;\n"
10331                "};\n",
10332                Style);
10333   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10334   verifyFormat("struct foo {\n"
10335                "private:\n"
10336                "  void f() {}\n"
10337                "\n"
10338                "private:\n"
10339                "  int i;\n"
10340                "\n"
10341                "protected:\n"
10342                "  int j;\n"
10343                "};\n",
10344                Style);
10345   verifyFormat("struct foo {\n"
10346                "private:\n"
10347                "  void f() {}\n"
10348                "\n"
10349                "private:\n"
10350                "  int i;\n"
10351                "\n"
10352                "protected:\n"
10353                "  int j;\n"
10354                "};\n",
10355                "struct foo {\n"
10356                "private:\n"
10357                "  void f() {}\n"
10358                "private:\n"
10359                "  int i;\n"
10360                "protected:\n"
10361                "  int j;\n"
10362                "};\n",
10363                Style);
10364   verifyFormat("struct foo { /* comment */\n"
10365                "private:\n"
10366                "  int i;\n"
10367                "  // comment\n"
10368                "\n"
10369                "private:\n"
10370                "  int j;\n"
10371                "};\n",
10372                "struct foo { /* comment */\n"
10373                "private:\n"
10374                "  int i;\n"
10375                "  // comment\n"
10376                "\n"
10377                "private:\n"
10378                "  int j;\n"
10379                "};\n",
10380                Style);
10381   verifyFormat("struct foo {\n"
10382                "#ifdef FOO\n"
10383                "#endif\n"
10384                "\n"
10385                "private:\n"
10386                "  int i;\n"
10387                "#ifdef FOO\n"
10388                "\n"
10389                "private:\n"
10390                "#endif\n"
10391                "  int j;\n"
10392                "};\n",
10393                "struct foo {\n"
10394                "#ifdef FOO\n"
10395                "#endif\n"
10396                "private:\n"
10397                "  int i;\n"
10398                "#ifdef FOO\n"
10399                "private:\n"
10400                "#endif\n"
10401                "  int j;\n"
10402                "};\n",
10403                Style);
10404   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10405   EXPECT_EQ("struct foo {\n"
10406             "\n"
10407             "private:\n"
10408             "  void f() {}\n"
10409             "\n"
10410             "private:\n"
10411             "  int i;\n"
10412             "\n"
10413             "protected:\n"
10414             "  int j;\n"
10415             "};\n",
10416             format("struct foo {\n"
10417                    "\n"
10418                    "private:\n"
10419                    "  void f() {}\n"
10420                    "\n"
10421                    "private:\n"
10422                    "  int i;\n"
10423                    "\n"
10424                    "protected:\n"
10425                    "  int j;\n"
10426                    "};\n",
10427                    Style));
10428   verifyFormat("struct foo {\n"
10429                "private:\n"
10430                "  void f() {}\n"
10431                "private:\n"
10432                "  int i;\n"
10433                "protected:\n"
10434                "  int j;\n"
10435                "};\n",
10436                Style);
10437   EXPECT_EQ("struct foo { /* comment */\n"
10438             "\n"
10439             "private:\n"
10440             "  int i;\n"
10441             "  // comment\n"
10442             "\n"
10443             "private:\n"
10444             "  int j;\n"
10445             "};\n",
10446             format("struct foo { /* comment */\n"
10447                    "\n"
10448                    "private:\n"
10449                    "  int i;\n"
10450                    "  // comment\n"
10451                    "\n"
10452                    "private:\n"
10453                    "  int j;\n"
10454                    "};\n",
10455                    Style));
10456   verifyFormat("struct foo { /* comment */\n"
10457                "private:\n"
10458                "  int i;\n"
10459                "  // comment\n"
10460                "private:\n"
10461                "  int j;\n"
10462                "};\n",
10463                Style);
10464   EXPECT_EQ("struct foo {\n"
10465             "#ifdef FOO\n"
10466             "#endif\n"
10467             "\n"
10468             "private:\n"
10469             "  int i;\n"
10470             "#ifdef FOO\n"
10471             "\n"
10472             "private:\n"
10473             "#endif\n"
10474             "  int j;\n"
10475             "};\n",
10476             format("struct foo {\n"
10477                    "#ifdef FOO\n"
10478                    "#endif\n"
10479                    "\n"
10480                    "private:\n"
10481                    "  int i;\n"
10482                    "#ifdef FOO\n"
10483                    "\n"
10484                    "private:\n"
10485                    "#endif\n"
10486                    "  int j;\n"
10487                    "};\n",
10488                    Style));
10489   verifyFormat("struct foo {\n"
10490                "#ifdef FOO\n"
10491                "#endif\n"
10492                "private:\n"
10493                "  int i;\n"
10494                "#ifdef FOO\n"
10495                "private:\n"
10496                "#endif\n"
10497                "  int j;\n"
10498                "};\n",
10499                Style);
10500 
10501   FormatStyle NoEmptyLines = getLLVMStyle();
10502   NoEmptyLines.MaxEmptyLinesToKeep = 0;
10503   verifyFormat("struct foo {\n"
10504                "private:\n"
10505                "  void f() {}\n"
10506                "\n"
10507                "private:\n"
10508                "  int i;\n"
10509                "\n"
10510                "public:\n"
10511                "protected:\n"
10512                "  int j;\n"
10513                "};\n",
10514                NoEmptyLines);
10515 
10516   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10517   verifyFormat("struct foo {\n"
10518                "private:\n"
10519                "  void f() {}\n"
10520                "private:\n"
10521                "  int i;\n"
10522                "public:\n"
10523                "protected:\n"
10524                "  int j;\n"
10525                "};\n",
10526                NoEmptyLines);
10527 
10528   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10529   verifyFormat("struct foo {\n"
10530                "private:\n"
10531                "  void f() {}\n"
10532                "\n"
10533                "private:\n"
10534                "  int i;\n"
10535                "\n"
10536                "public:\n"
10537                "\n"
10538                "protected:\n"
10539                "  int j;\n"
10540                "};\n",
10541                NoEmptyLines);
10542 }
10543 
10544 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
10545 
10546   FormatStyle Style = getLLVMStyle();
10547   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
10548   verifyFormat("struct foo {\n"
10549                "private:\n"
10550                "  void f() {}\n"
10551                "\n"
10552                "private:\n"
10553                "  int i;\n"
10554                "\n"
10555                "protected:\n"
10556                "  int j;\n"
10557                "};\n",
10558                Style);
10559 
10560   // Check if lines are removed.
10561   verifyFormat("struct foo {\n"
10562                "private:\n"
10563                "  void f() {}\n"
10564                "\n"
10565                "private:\n"
10566                "  int i;\n"
10567                "\n"
10568                "protected:\n"
10569                "  int j;\n"
10570                "};\n",
10571                "struct foo {\n"
10572                "private:\n"
10573                "\n"
10574                "  void f() {}\n"
10575                "\n"
10576                "private:\n"
10577                "\n"
10578                "  int i;\n"
10579                "\n"
10580                "protected:\n"
10581                "\n"
10582                "  int j;\n"
10583                "};\n",
10584                Style);
10585 
10586   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10587   verifyFormat("struct foo {\n"
10588                "private:\n"
10589                "\n"
10590                "  void f() {}\n"
10591                "\n"
10592                "private:\n"
10593                "\n"
10594                "  int i;\n"
10595                "\n"
10596                "protected:\n"
10597                "\n"
10598                "  int j;\n"
10599                "};\n",
10600                Style);
10601 
10602   // Check if lines are added.
10603   verifyFormat("struct foo {\n"
10604                "private:\n"
10605                "\n"
10606                "  void f() {}\n"
10607                "\n"
10608                "private:\n"
10609                "\n"
10610                "  int i;\n"
10611                "\n"
10612                "protected:\n"
10613                "\n"
10614                "  int j;\n"
10615                "};\n",
10616                "struct foo {\n"
10617                "private:\n"
10618                "  void f() {}\n"
10619                "\n"
10620                "private:\n"
10621                "  int i;\n"
10622                "\n"
10623                "protected:\n"
10624                "  int j;\n"
10625                "};\n",
10626                Style);
10627 
10628   // Leave tests rely on the code layout, test::messUp can not be used.
10629   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10630   Style.MaxEmptyLinesToKeep = 0u;
10631   verifyFormat("struct foo {\n"
10632                "private:\n"
10633                "  void f() {}\n"
10634                "\n"
10635                "private:\n"
10636                "  int i;\n"
10637                "\n"
10638                "protected:\n"
10639                "  int j;\n"
10640                "};\n",
10641                Style);
10642 
10643   // Check if MaxEmptyLinesToKeep is respected.
10644   EXPECT_EQ("struct foo {\n"
10645             "private:\n"
10646             "  void f() {}\n"
10647             "\n"
10648             "private:\n"
10649             "  int i;\n"
10650             "\n"
10651             "protected:\n"
10652             "  int j;\n"
10653             "};\n",
10654             format("struct foo {\n"
10655                    "private:\n"
10656                    "\n\n\n"
10657                    "  void f() {}\n"
10658                    "\n"
10659                    "private:\n"
10660                    "\n\n\n"
10661                    "  int i;\n"
10662                    "\n"
10663                    "protected:\n"
10664                    "\n\n\n"
10665                    "  int j;\n"
10666                    "};\n",
10667                    Style));
10668 
10669   Style.MaxEmptyLinesToKeep = 1u;
10670   EXPECT_EQ("struct foo {\n"
10671             "private:\n"
10672             "\n"
10673             "  void f() {}\n"
10674             "\n"
10675             "private:\n"
10676             "\n"
10677             "  int i;\n"
10678             "\n"
10679             "protected:\n"
10680             "\n"
10681             "  int j;\n"
10682             "};\n",
10683             format("struct foo {\n"
10684                    "private:\n"
10685                    "\n"
10686                    "  void f() {}\n"
10687                    "\n"
10688                    "private:\n"
10689                    "\n"
10690                    "  int i;\n"
10691                    "\n"
10692                    "protected:\n"
10693                    "\n"
10694                    "  int j;\n"
10695                    "};\n",
10696                    Style));
10697   // Check if no lines are kept.
10698   EXPECT_EQ("struct foo {\n"
10699             "private:\n"
10700             "  void f() {}\n"
10701             "\n"
10702             "private:\n"
10703             "  int i;\n"
10704             "\n"
10705             "protected:\n"
10706             "  int j;\n"
10707             "};\n",
10708             format("struct foo {\n"
10709                    "private:\n"
10710                    "  void f() {}\n"
10711                    "\n"
10712                    "private:\n"
10713                    "  int i;\n"
10714                    "\n"
10715                    "protected:\n"
10716                    "  int j;\n"
10717                    "};\n",
10718                    Style));
10719   // Check if MaxEmptyLinesToKeep is respected.
10720   EXPECT_EQ("struct foo {\n"
10721             "private:\n"
10722             "\n"
10723             "  void f() {}\n"
10724             "\n"
10725             "private:\n"
10726             "\n"
10727             "  int i;\n"
10728             "\n"
10729             "protected:\n"
10730             "\n"
10731             "  int j;\n"
10732             "};\n",
10733             format("struct foo {\n"
10734                    "private:\n"
10735                    "\n\n\n"
10736                    "  void f() {}\n"
10737                    "\n"
10738                    "private:\n"
10739                    "\n\n\n"
10740                    "  int i;\n"
10741                    "\n"
10742                    "protected:\n"
10743                    "\n\n\n"
10744                    "  int j;\n"
10745                    "};\n",
10746                    Style));
10747 
10748   Style.MaxEmptyLinesToKeep = 10u;
10749   EXPECT_EQ("struct foo {\n"
10750             "private:\n"
10751             "\n\n\n"
10752             "  void f() {}\n"
10753             "\n"
10754             "private:\n"
10755             "\n\n\n"
10756             "  int i;\n"
10757             "\n"
10758             "protected:\n"
10759             "\n\n\n"
10760             "  int j;\n"
10761             "};\n",
10762             format("struct foo {\n"
10763                    "private:\n"
10764                    "\n\n\n"
10765                    "  void f() {}\n"
10766                    "\n"
10767                    "private:\n"
10768                    "\n\n\n"
10769                    "  int i;\n"
10770                    "\n"
10771                    "protected:\n"
10772                    "\n\n\n"
10773                    "  int j;\n"
10774                    "};\n",
10775                    Style));
10776 
10777   // Test with comments.
10778   Style = getLLVMStyle();
10779   verifyFormat("struct foo {\n"
10780                "private:\n"
10781                "  // comment\n"
10782                "  void f() {}\n"
10783                "\n"
10784                "private: /* comment */\n"
10785                "  int i;\n"
10786                "};\n",
10787                Style);
10788   verifyFormat("struct foo {\n"
10789                "private:\n"
10790                "  // comment\n"
10791                "  void f() {}\n"
10792                "\n"
10793                "private: /* comment */\n"
10794                "  int i;\n"
10795                "};\n",
10796                "struct foo {\n"
10797                "private:\n"
10798                "\n"
10799                "  // comment\n"
10800                "  void f() {}\n"
10801                "\n"
10802                "private: /* comment */\n"
10803                "\n"
10804                "  int i;\n"
10805                "};\n",
10806                Style);
10807 
10808   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10809   verifyFormat("struct foo {\n"
10810                "private:\n"
10811                "\n"
10812                "  // comment\n"
10813                "  void f() {}\n"
10814                "\n"
10815                "private: /* comment */\n"
10816                "\n"
10817                "  int i;\n"
10818                "};\n",
10819                "struct foo {\n"
10820                "private:\n"
10821                "  // comment\n"
10822                "  void f() {}\n"
10823                "\n"
10824                "private: /* comment */\n"
10825                "  int i;\n"
10826                "};\n",
10827                Style);
10828   verifyFormat("struct foo {\n"
10829                "private:\n"
10830                "\n"
10831                "  // comment\n"
10832                "  void f() {}\n"
10833                "\n"
10834                "private: /* comment */\n"
10835                "\n"
10836                "  int i;\n"
10837                "};\n",
10838                Style);
10839 
10840   // Test with preprocessor defines.
10841   Style = getLLVMStyle();
10842   verifyFormat("struct foo {\n"
10843                "private:\n"
10844                "#ifdef FOO\n"
10845                "#endif\n"
10846                "  void f() {}\n"
10847                "};\n",
10848                Style);
10849   verifyFormat("struct foo {\n"
10850                "private:\n"
10851                "#ifdef FOO\n"
10852                "#endif\n"
10853                "  void f() {}\n"
10854                "};\n",
10855                "struct foo {\n"
10856                "private:\n"
10857                "\n"
10858                "#ifdef FOO\n"
10859                "#endif\n"
10860                "  void f() {}\n"
10861                "};\n",
10862                Style);
10863 
10864   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10865   verifyFormat("struct foo {\n"
10866                "private:\n"
10867                "\n"
10868                "#ifdef FOO\n"
10869                "#endif\n"
10870                "  void f() {}\n"
10871                "};\n",
10872                "struct foo {\n"
10873                "private:\n"
10874                "#ifdef FOO\n"
10875                "#endif\n"
10876                "  void f() {}\n"
10877                "};\n",
10878                Style);
10879   verifyFormat("struct foo {\n"
10880                "private:\n"
10881                "\n"
10882                "#ifdef FOO\n"
10883                "#endif\n"
10884                "  void f() {}\n"
10885                "};\n",
10886                Style);
10887 }
10888 
10889 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
10890   // Combined tests of EmptyLineAfterAccessModifier and
10891   // EmptyLineBeforeAccessModifier.
10892   FormatStyle Style = getLLVMStyle();
10893   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10894   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10895   verifyFormat("struct foo {\n"
10896                "private:\n"
10897                "\n"
10898                "protected:\n"
10899                "};\n",
10900                Style);
10901 
10902   Style.MaxEmptyLinesToKeep = 10u;
10903   // Both remove all new lines.
10904   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10905   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
10906   verifyFormat("struct foo {\n"
10907                "private:\n"
10908                "protected:\n"
10909                "};\n",
10910                "struct foo {\n"
10911                "private:\n"
10912                "\n\n\n"
10913                "protected:\n"
10914                "};\n",
10915                Style);
10916 
10917   // Leave tests rely on the code layout, test::messUp can not be used.
10918   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10919   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10920   Style.MaxEmptyLinesToKeep = 10u;
10921   EXPECT_EQ("struct foo {\n"
10922             "private:\n"
10923             "\n\n\n"
10924             "protected:\n"
10925             "};\n",
10926             format("struct foo {\n"
10927                    "private:\n"
10928                    "\n\n\n"
10929                    "protected:\n"
10930                    "};\n",
10931                    Style));
10932   Style.MaxEmptyLinesToKeep = 3u;
10933   EXPECT_EQ("struct foo {\n"
10934             "private:\n"
10935             "\n\n\n"
10936             "protected:\n"
10937             "};\n",
10938             format("struct foo {\n"
10939                    "private:\n"
10940                    "\n\n\n"
10941                    "protected:\n"
10942                    "};\n",
10943                    Style));
10944   Style.MaxEmptyLinesToKeep = 1u;
10945   EXPECT_EQ("struct foo {\n"
10946             "private:\n"
10947             "\n\n\n"
10948             "protected:\n"
10949             "};\n",
10950             format("struct foo {\n"
10951                    "private:\n"
10952                    "\n\n\n"
10953                    "protected:\n"
10954                    "};\n",
10955                    Style)); // Based on new lines in original document and not
10956                             // on the setting.
10957 
10958   Style.MaxEmptyLinesToKeep = 10u;
10959   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10960   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10961   // Newlines are kept if they are greater than zero,
10962   // test::messUp removes all new lines which changes the logic
10963   EXPECT_EQ("struct foo {\n"
10964             "private:\n"
10965             "\n\n\n"
10966             "protected:\n"
10967             "};\n",
10968             format("struct foo {\n"
10969                    "private:\n"
10970                    "\n\n\n"
10971                    "protected:\n"
10972                    "};\n",
10973                    Style));
10974 
10975   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10976   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10977   // test::messUp removes all new lines which changes the logic
10978   EXPECT_EQ("struct foo {\n"
10979             "private:\n"
10980             "\n\n\n"
10981             "protected:\n"
10982             "};\n",
10983             format("struct foo {\n"
10984                    "private:\n"
10985                    "\n\n\n"
10986                    "protected:\n"
10987                    "};\n",
10988                    Style));
10989 
10990   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10991   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
10992   EXPECT_EQ("struct foo {\n"
10993             "private:\n"
10994             "\n\n\n"
10995             "protected:\n"
10996             "};\n",
10997             format("struct foo {\n"
10998                    "private:\n"
10999                    "\n\n\n"
11000                    "protected:\n"
11001                    "};\n",
11002                    Style)); // test::messUp removes all new lines which changes
11003                             // the logic.
11004 
11005   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11006   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11007   verifyFormat("struct foo {\n"
11008                "private:\n"
11009                "protected:\n"
11010                "};\n",
11011                "struct foo {\n"
11012                "private:\n"
11013                "\n\n\n"
11014                "protected:\n"
11015                "};\n",
11016                Style);
11017 
11018   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11019   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11020   EXPECT_EQ("struct foo {\n"
11021             "private:\n"
11022             "\n\n\n"
11023             "protected:\n"
11024             "};\n",
11025             format("struct foo {\n"
11026                    "private:\n"
11027                    "\n\n\n"
11028                    "protected:\n"
11029                    "};\n",
11030                    Style)); // test::messUp removes all new lines which changes
11031                             // the logic.
11032 
11033   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11034   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11035   verifyFormat("struct foo {\n"
11036                "private:\n"
11037                "protected:\n"
11038                "};\n",
11039                "struct foo {\n"
11040                "private:\n"
11041                "\n\n\n"
11042                "protected:\n"
11043                "};\n",
11044                Style);
11045 
11046   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11047   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11048   verifyFormat("struct foo {\n"
11049                "private:\n"
11050                "protected:\n"
11051                "};\n",
11052                "struct foo {\n"
11053                "private:\n"
11054                "\n\n\n"
11055                "protected:\n"
11056                "};\n",
11057                Style);
11058 
11059   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11060   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11061   verifyFormat("struct foo {\n"
11062                "private:\n"
11063                "protected:\n"
11064                "};\n",
11065                "struct foo {\n"
11066                "private:\n"
11067                "\n\n\n"
11068                "protected:\n"
11069                "};\n",
11070                Style);
11071 
11072   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11073   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11074   verifyFormat("struct foo {\n"
11075                "private:\n"
11076                "protected:\n"
11077                "};\n",
11078                "struct foo {\n"
11079                "private:\n"
11080                "\n\n\n"
11081                "protected:\n"
11082                "};\n",
11083                Style);
11084 }
11085 
11086 TEST_F(FormatTest, FormatsArrays) {
11087   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11088                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11089   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11090                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11091   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11092                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11093   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11094                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11095   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11096                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11097   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11098                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11099                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11100   verifyFormat(
11101       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11102       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11103       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11104   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11105                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11106 
11107   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11108                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11109   verifyFormat(
11110       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11111       "                                  .aaaaaaa[0]\n"
11112       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11113   verifyFormat("a[::b::c];");
11114 
11115   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11116 
11117   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11118   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11119 }
11120 
11121 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11122   verifyFormat("(a)->b();");
11123   verifyFormat("--a;");
11124 }
11125 
11126 TEST_F(FormatTest, HandlesIncludeDirectives) {
11127   verifyFormat("#include <string>\n"
11128                "#include <a/b/c.h>\n"
11129                "#include \"a/b/string\"\n"
11130                "#include \"string.h\"\n"
11131                "#include \"string.h\"\n"
11132                "#include <a-a>\n"
11133                "#include < path with space >\n"
11134                "#include_next <test.h>"
11135                "#include \"abc.h\" // this is included for ABC\n"
11136                "#include \"some long include\" // with a comment\n"
11137                "#include \"some very long include path\"\n"
11138                "#include <some/very/long/include/path>\n",
11139                getLLVMStyleWithColumns(35));
11140   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11141   EXPECT_EQ("#include <a>", format("#include<a>"));
11142 
11143   verifyFormat("#import <string>");
11144   verifyFormat("#import <a/b/c.h>");
11145   verifyFormat("#import \"a/b/string\"");
11146   verifyFormat("#import \"string.h\"");
11147   verifyFormat("#import \"string.h\"");
11148   verifyFormat("#if __has_include(<strstream>)\n"
11149                "#include <strstream>\n"
11150                "#endif");
11151 
11152   verifyFormat("#define MY_IMPORT <a/b>");
11153 
11154   verifyFormat("#if __has_include(<a/b>)");
11155   verifyFormat("#if __has_include_next(<a/b>)");
11156   verifyFormat("#define F __has_include(<a/b>)");
11157   verifyFormat("#define F __has_include_next(<a/b>)");
11158 
11159   // Protocol buffer definition or missing "#".
11160   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
11161                getLLVMStyleWithColumns(30));
11162 
11163   FormatStyle Style = getLLVMStyle();
11164   Style.AlwaysBreakBeforeMultilineStrings = true;
11165   Style.ColumnLimit = 0;
11166   verifyFormat("#import \"abc.h\"", Style);
11167 
11168   // But 'import' might also be a regular C++ namespace.
11169   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11170                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11171 }
11172 
11173 //===----------------------------------------------------------------------===//
11174 // Error recovery tests.
11175 //===----------------------------------------------------------------------===//
11176 
11177 TEST_F(FormatTest, IncompleteParameterLists) {
11178   FormatStyle NoBinPacking = getLLVMStyle();
11179   NoBinPacking.BinPackParameters = false;
11180   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
11181                "                        double *min_x,\n"
11182                "                        double *max_x,\n"
11183                "                        double *min_y,\n"
11184                "                        double *max_y,\n"
11185                "                        double *min_z,\n"
11186                "                        double *max_z, ) {}",
11187                NoBinPacking);
11188 }
11189 
11190 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
11191   verifyFormat("void f() { return; }\n42");
11192   verifyFormat("void f() {\n"
11193                "  if (0)\n"
11194                "    return;\n"
11195                "}\n"
11196                "42");
11197   verifyFormat("void f() { return }\n42");
11198   verifyFormat("void f() {\n"
11199                "  if (0)\n"
11200                "    return\n"
11201                "}\n"
11202                "42");
11203 }
11204 
11205 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
11206   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
11207   EXPECT_EQ("void f() {\n"
11208             "  if (a)\n"
11209             "    return\n"
11210             "}",
11211             format("void  f  (  )  {  if  ( a )  return  }"));
11212   EXPECT_EQ("namespace N {\n"
11213             "void f()\n"
11214             "}",
11215             format("namespace  N  {  void f()  }"));
11216   EXPECT_EQ("namespace N {\n"
11217             "void f() {}\n"
11218             "void g()\n"
11219             "} // namespace N",
11220             format("namespace N  { void f( ) { } void g( ) }"));
11221 }
11222 
11223 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
11224   verifyFormat("int aaaaaaaa =\n"
11225                "    // Overlylongcomment\n"
11226                "    b;",
11227                getLLVMStyleWithColumns(20));
11228   verifyFormat("function(\n"
11229                "    ShortArgument,\n"
11230                "    LoooooooooooongArgument);\n",
11231                getLLVMStyleWithColumns(20));
11232 }
11233 
11234 TEST_F(FormatTest, IncorrectAccessSpecifier) {
11235   verifyFormat("public:");
11236   verifyFormat("class A {\n"
11237                "public\n"
11238                "  void f() {}\n"
11239                "};");
11240   verifyFormat("public\n"
11241                "int qwerty;");
11242   verifyFormat("public\n"
11243                "B {}");
11244   verifyFormat("public\n"
11245                "{}");
11246   verifyFormat("public\n"
11247                "B { int x; }");
11248 }
11249 
11250 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
11251   verifyFormat("{");
11252   verifyFormat("#})");
11253   verifyNoCrash("(/**/[:!] ?[).");
11254 }
11255 
11256 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
11257   // Found by oss-fuzz:
11258   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
11259   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
11260   Style.ColumnLimit = 60;
11261   verifyNoCrash(
11262       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
11263       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
11264       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
11265       Style);
11266 }
11267 
11268 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
11269   verifyFormat("do {\n}");
11270   verifyFormat("do {\n}\n"
11271                "f();");
11272   verifyFormat("do {\n}\n"
11273                "wheeee(fun);");
11274   verifyFormat("do {\n"
11275                "  f();\n"
11276                "}");
11277 }
11278 
11279 TEST_F(FormatTest, IncorrectCodeMissingParens) {
11280   verifyFormat("if {\n  foo;\n  foo();\n}");
11281   verifyFormat("switch {\n  foo;\n  foo();\n}");
11282   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
11283   verifyFormat("while {\n  foo;\n  foo();\n}");
11284   verifyFormat("do {\n  foo;\n  foo();\n} while;");
11285 }
11286 
11287 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
11288   verifyIncompleteFormat("namespace {\n"
11289                          "class Foo { Foo (\n"
11290                          "};\n"
11291                          "} // namespace");
11292 }
11293 
11294 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
11295   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
11296   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
11297   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
11298   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
11299 
11300   EXPECT_EQ("{\n"
11301             "  {\n"
11302             "    breakme(\n"
11303             "        qwe);\n"
11304             "  }\n",
11305             format("{\n"
11306                    "    {\n"
11307                    " breakme(qwe);\n"
11308                    "}\n",
11309                    getLLVMStyleWithColumns(10)));
11310 }
11311 
11312 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
11313   verifyFormat("int x = {\n"
11314                "    avariable,\n"
11315                "    b(alongervariable)};",
11316                getLLVMStyleWithColumns(25));
11317 }
11318 
11319 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
11320   verifyFormat("return (a)(b){1, 2, 3};");
11321 }
11322 
11323 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
11324   verifyFormat("vector<int> x{1, 2, 3, 4};");
11325   verifyFormat("vector<int> x{\n"
11326                "    1,\n"
11327                "    2,\n"
11328                "    3,\n"
11329                "    4,\n"
11330                "};");
11331   verifyFormat("vector<T> x{{}, {}, {}, {}};");
11332   verifyFormat("f({1, 2});");
11333   verifyFormat("auto v = Foo{-1};");
11334   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
11335   verifyFormat("Class::Class : member{1, 2, 3} {}");
11336   verifyFormat("new vector<int>{1, 2, 3};");
11337   verifyFormat("new int[3]{1, 2, 3};");
11338   verifyFormat("new int{1};");
11339   verifyFormat("return {arg1, arg2};");
11340   verifyFormat("return {arg1, SomeType{parameter}};");
11341   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
11342   verifyFormat("new T{arg1, arg2};");
11343   verifyFormat("f(MyMap[{composite, key}]);");
11344   verifyFormat("class Class {\n"
11345                "  T member = {arg1, arg2};\n"
11346                "};");
11347   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
11348   verifyFormat("const struct A a = {.a = 1, .b = 2};");
11349   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
11350   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
11351   verifyFormat("int a = std::is_integral<int>{} + 0;");
11352 
11353   verifyFormat("int foo(int i) { return fo1{}(i); }");
11354   verifyFormat("int foo(int i) { return fo1{}(i); }");
11355   verifyFormat("auto i = decltype(x){};");
11356   verifyFormat("auto i = typeof(x){};");
11357   verifyFormat("auto i = _Atomic(x){};");
11358   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
11359   verifyFormat("Node n{1, Node{1000}, //\n"
11360                "       2};");
11361   verifyFormat("Aaaa aaaaaaa{\n"
11362                "    {\n"
11363                "        aaaa,\n"
11364                "    },\n"
11365                "};");
11366   verifyFormat("class C : public D {\n"
11367                "  SomeClass SC{2};\n"
11368                "};");
11369   verifyFormat("class C : public A {\n"
11370                "  class D : public B {\n"
11371                "    void f() { int i{2}; }\n"
11372                "  };\n"
11373                "};");
11374   verifyFormat("#define A {a, a},");
11375 
11376   // Avoid breaking between equal sign and opening brace
11377   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
11378   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
11379   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
11380                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
11381                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
11382                "     {\"ccccccccccccccccccccc\", 2}};",
11383                AvoidBreakingFirstArgument);
11384 
11385   // Binpacking only if there is no trailing comma
11386   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
11387                "                      cccccccccc, dddddddddd};",
11388                getLLVMStyleWithColumns(50));
11389   verifyFormat("const Aaaaaa aaaaa = {\n"
11390                "    aaaaaaaaaaa,\n"
11391                "    bbbbbbbbbbb,\n"
11392                "    ccccccccccc,\n"
11393                "    ddddddddddd,\n"
11394                "};",
11395                getLLVMStyleWithColumns(50));
11396 
11397   // Cases where distinguising braced lists and blocks is hard.
11398   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
11399   verifyFormat("void f() {\n"
11400                "  return; // comment\n"
11401                "}\n"
11402                "SomeType t;");
11403   verifyFormat("void f() {\n"
11404                "  if (a) {\n"
11405                "    f();\n"
11406                "  }\n"
11407                "}\n"
11408                "SomeType t;");
11409 
11410   // In combination with BinPackArguments = false.
11411   FormatStyle NoBinPacking = getLLVMStyle();
11412   NoBinPacking.BinPackArguments = false;
11413   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
11414                "                      bbbbb,\n"
11415                "                      ccccc,\n"
11416                "                      ddddd,\n"
11417                "                      eeeee,\n"
11418                "                      ffffff,\n"
11419                "                      ggggg,\n"
11420                "                      hhhhhh,\n"
11421                "                      iiiiii,\n"
11422                "                      jjjjjj,\n"
11423                "                      kkkkkk};",
11424                NoBinPacking);
11425   verifyFormat("const Aaaaaa aaaaa = {\n"
11426                "    aaaaa,\n"
11427                "    bbbbb,\n"
11428                "    ccccc,\n"
11429                "    ddddd,\n"
11430                "    eeeee,\n"
11431                "    ffffff,\n"
11432                "    ggggg,\n"
11433                "    hhhhhh,\n"
11434                "    iiiiii,\n"
11435                "    jjjjjj,\n"
11436                "    kkkkkk,\n"
11437                "};",
11438                NoBinPacking);
11439   verifyFormat(
11440       "const Aaaaaa aaaaa = {\n"
11441       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
11442       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
11443       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
11444       "};",
11445       NoBinPacking);
11446 
11447   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11448   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
11449             "    CDDDP83848_BMCR_REGISTER,\n"
11450             "    CDDDP83848_BMSR_REGISTER,\n"
11451             "    CDDDP83848_RBR_REGISTER};",
11452             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
11453                    "                                CDDDP83848_BMSR_REGISTER,\n"
11454                    "                                CDDDP83848_RBR_REGISTER};",
11455                    NoBinPacking));
11456 
11457   // FIXME: The alignment of these trailing comments might be bad. Then again,
11458   // this might be utterly useless in real code.
11459   verifyFormat("Constructor::Constructor()\n"
11460                "    : some_value{         //\n"
11461                "                 aaaaaaa, //\n"
11462                "                 bbbbbbb} {}");
11463 
11464   // In braced lists, the first comment is always assumed to belong to the
11465   // first element. Thus, it can be moved to the next or previous line as
11466   // appropriate.
11467   EXPECT_EQ("function({// First element:\n"
11468             "          1,\n"
11469             "          // Second element:\n"
11470             "          2});",
11471             format("function({\n"
11472                    "    // First element:\n"
11473                    "    1,\n"
11474                    "    // Second element:\n"
11475                    "    2});"));
11476   EXPECT_EQ("std::vector<int> MyNumbers{\n"
11477             "    // First element:\n"
11478             "    1,\n"
11479             "    // Second element:\n"
11480             "    2};",
11481             format("std::vector<int> MyNumbers{// First element:\n"
11482                    "                           1,\n"
11483                    "                           // Second element:\n"
11484                    "                           2};",
11485                    getLLVMStyleWithColumns(30)));
11486   // A trailing comma should still lead to an enforced line break and no
11487   // binpacking.
11488   EXPECT_EQ("vector<int> SomeVector = {\n"
11489             "    // aaa\n"
11490             "    1,\n"
11491             "    2,\n"
11492             "};",
11493             format("vector<int> SomeVector = { // aaa\n"
11494                    "    1, 2, };"));
11495 
11496   // C++11 brace initializer list l-braces should not be treated any differently
11497   // when breaking before lambda bodies is enabled
11498   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
11499   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
11500   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
11501   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
11502   verifyFormat(
11503       "std::runtime_error{\n"
11504       "    \"Long string which will force a break onto the next line...\"};",
11505       BreakBeforeLambdaBody);
11506 
11507   FormatStyle ExtraSpaces = getLLVMStyle();
11508   ExtraSpaces.Cpp11BracedListStyle = false;
11509   ExtraSpaces.ColumnLimit = 75;
11510   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
11511   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
11512   verifyFormat("f({ 1, 2 });", ExtraSpaces);
11513   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
11514   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
11515   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
11516   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
11517   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
11518   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
11519   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
11520   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
11521   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
11522   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
11523   verifyFormat("class Class {\n"
11524                "  T member = { arg1, arg2 };\n"
11525                "};",
11526                ExtraSpaces);
11527   verifyFormat(
11528       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11529       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
11530       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
11531       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
11532       ExtraSpaces);
11533   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
11534   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
11535                ExtraSpaces);
11536   verifyFormat(
11537       "someFunction(OtherParam,\n"
11538       "             BracedList{ // comment 1 (Forcing interesting break)\n"
11539       "                         param1, param2,\n"
11540       "                         // comment 2\n"
11541       "                         param3, param4 });",
11542       ExtraSpaces);
11543   verifyFormat(
11544       "std::this_thread::sleep_for(\n"
11545       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
11546       ExtraSpaces);
11547   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
11548                "    aaaaaaa,\n"
11549                "    aaaaaaaaaa,\n"
11550                "    aaaaa,\n"
11551                "    aaaaaaaaaaaaaaa,\n"
11552                "    aaa,\n"
11553                "    aaaaaaaaaa,\n"
11554                "    a,\n"
11555                "    aaaaaaaaaaaaaaaaaaaaa,\n"
11556                "    aaaaaaaaaaaa,\n"
11557                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
11558                "    aaaaaaa,\n"
11559                "    a};");
11560   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
11561   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
11562   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
11563 
11564   // Avoid breaking between initializer/equal sign and opening brace
11565   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
11566   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
11567                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11568                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11569                "  { \"ccccccccccccccccccccc\", 2 }\n"
11570                "};",
11571                ExtraSpaces);
11572   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
11573                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11574                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11575                "  { \"ccccccccccccccccccccc\", 2 }\n"
11576                "};",
11577                ExtraSpaces);
11578 
11579   FormatStyle SpaceBeforeBrace = getLLVMStyle();
11580   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
11581   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
11582   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
11583 
11584   FormatStyle SpaceBetweenBraces = getLLVMStyle();
11585   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
11586   SpaceBetweenBraces.SpacesInParentheses = true;
11587   SpaceBetweenBraces.SpacesInSquareBrackets = true;
11588   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
11589   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
11590   verifyFormat("vector< int > x{ // comment 1\n"
11591                "                 1, 2, 3, 4 };",
11592                SpaceBetweenBraces);
11593   SpaceBetweenBraces.ColumnLimit = 20;
11594   EXPECT_EQ("vector< int > x{\n"
11595             "    1, 2, 3, 4 };",
11596             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11597   SpaceBetweenBraces.ColumnLimit = 24;
11598   EXPECT_EQ("vector< int > x{ 1, 2,\n"
11599             "                 3, 4 };",
11600             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11601   EXPECT_EQ("vector< int > x{\n"
11602             "    1,\n"
11603             "    2,\n"
11604             "    3,\n"
11605             "    4,\n"
11606             "};",
11607             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
11608   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
11609   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
11610   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
11611 }
11612 
11613 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
11614   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11615                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11616                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11617                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11618                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11619                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
11620   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
11621                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11622                "                 1, 22, 333, 4444, 55555, //\n"
11623                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11624                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
11625   verifyFormat(
11626       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
11627       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
11628       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
11629       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11630       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11631       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11632       "                 7777777};");
11633   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11634                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11635                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
11636   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11637                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11638                "    // Separating comment.\n"
11639                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
11640   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11641                "    // Leading comment\n"
11642                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11643                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
11644   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11645                "                 1, 1, 1, 1};",
11646                getLLVMStyleWithColumns(39));
11647   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11648                "                 1, 1, 1, 1};",
11649                getLLVMStyleWithColumns(38));
11650   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
11651                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
11652                getLLVMStyleWithColumns(43));
11653   verifyFormat(
11654       "static unsigned SomeValues[10][3] = {\n"
11655       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
11656       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
11657   verifyFormat("static auto fields = new vector<string>{\n"
11658                "    \"aaaaaaaaaaaaa\",\n"
11659                "    \"aaaaaaaaaaaaa\",\n"
11660                "    \"aaaaaaaaaaaa\",\n"
11661                "    \"aaaaaaaaaaaaaa\",\n"
11662                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11663                "    \"aaaaaaaaaaaa\",\n"
11664                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11665                "};");
11666   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
11667   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
11668                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
11669                "                 3, cccccccccccccccccccccc};",
11670                getLLVMStyleWithColumns(60));
11671 
11672   // Trailing commas.
11673   verifyFormat("vector<int> x = {\n"
11674                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
11675                "};",
11676                getLLVMStyleWithColumns(39));
11677   verifyFormat("vector<int> x = {\n"
11678                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
11679                "};",
11680                getLLVMStyleWithColumns(39));
11681   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11682                "                 1, 1, 1, 1,\n"
11683                "                 /**/ /**/};",
11684                getLLVMStyleWithColumns(39));
11685 
11686   // Trailing comment in the first line.
11687   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
11688                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
11689                "    111111111,  222222222,  3333333333,  444444444,  //\n"
11690                "    11111111,   22222222,   333333333,   44444444};");
11691   // Trailing comment in the last line.
11692   verifyFormat("int aaaaa[] = {\n"
11693                "    1, 2, 3, // comment\n"
11694                "    4, 5, 6  // comment\n"
11695                "};");
11696 
11697   // With nested lists, we should either format one item per line or all nested
11698   // lists one on line.
11699   // FIXME: For some nested lists, we can do better.
11700   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
11701                "        {aaaaaaaaaaaaaaaaaaa},\n"
11702                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
11703                "        {aaaaaaaaaaaaaaaaa}};",
11704                getLLVMStyleWithColumns(60));
11705   verifyFormat(
11706       "SomeStruct my_struct_array = {\n"
11707       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
11708       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
11709       "    {aaa, aaa},\n"
11710       "    {aaa, aaa},\n"
11711       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
11712       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
11713       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
11714 
11715   // No column layout should be used here.
11716   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
11717                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
11718 
11719   verifyNoCrash("a<,");
11720 
11721   // No braced initializer here.
11722   verifyFormat("void f() {\n"
11723                "  struct Dummy {};\n"
11724                "  f(v);\n"
11725                "}");
11726 
11727   // Long lists should be formatted in columns even if they are nested.
11728   verifyFormat(
11729       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11730       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11731       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11732       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11733       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11734       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
11735 
11736   // Allow "single-column" layout even if that violates the column limit. There
11737   // isn't going to be a better way.
11738   verifyFormat("std::vector<int> a = {\n"
11739                "    aaaaaaaa,\n"
11740                "    aaaaaaaa,\n"
11741                "    aaaaaaaa,\n"
11742                "    aaaaaaaa,\n"
11743                "    aaaaaaaaaa,\n"
11744                "    aaaaaaaa,\n"
11745                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
11746                getLLVMStyleWithColumns(30));
11747   verifyFormat("vector<int> aaaa = {\n"
11748                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11749                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11750                "    aaaaaa.aaaaaaa,\n"
11751                "    aaaaaa.aaaaaaa,\n"
11752                "    aaaaaa.aaaaaaa,\n"
11753                "    aaaaaa.aaaaaaa,\n"
11754                "};");
11755 
11756   // Don't create hanging lists.
11757   verifyFormat("someFunction(Param, {List1, List2,\n"
11758                "                     List3});",
11759                getLLVMStyleWithColumns(35));
11760   verifyFormat("someFunction(Param, Param,\n"
11761                "             {List1, List2,\n"
11762                "              List3});",
11763                getLLVMStyleWithColumns(35));
11764   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
11765                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
11766 }
11767 
11768 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
11769   FormatStyle DoNotMerge = getLLVMStyle();
11770   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
11771 
11772   verifyFormat("void f() { return 42; }");
11773   verifyFormat("void f() {\n"
11774                "  return 42;\n"
11775                "}",
11776                DoNotMerge);
11777   verifyFormat("void f() {\n"
11778                "  // Comment\n"
11779                "}");
11780   verifyFormat("{\n"
11781                "#error {\n"
11782                "  int a;\n"
11783                "}");
11784   verifyFormat("{\n"
11785                "  int a;\n"
11786                "#error {\n"
11787                "}");
11788   verifyFormat("void f() {} // comment");
11789   verifyFormat("void f() { int a; } // comment");
11790   verifyFormat("void f() {\n"
11791                "} // comment",
11792                DoNotMerge);
11793   verifyFormat("void f() {\n"
11794                "  int a;\n"
11795                "} // comment",
11796                DoNotMerge);
11797   verifyFormat("void f() {\n"
11798                "} // comment",
11799                getLLVMStyleWithColumns(15));
11800 
11801   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
11802   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
11803 
11804   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
11805   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
11806   verifyFormat("class C {\n"
11807                "  C()\n"
11808                "      : iiiiiiii(nullptr),\n"
11809                "        kkkkkkk(nullptr),\n"
11810                "        mmmmmmm(nullptr),\n"
11811                "        nnnnnnn(nullptr) {}\n"
11812                "};",
11813                getGoogleStyle());
11814 
11815   FormatStyle NoColumnLimit = getLLVMStyle();
11816   NoColumnLimit.ColumnLimit = 0;
11817   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
11818   EXPECT_EQ("class C {\n"
11819             "  A() : b(0) {}\n"
11820             "};",
11821             format("class C{A():b(0){}};", NoColumnLimit));
11822   EXPECT_EQ("A()\n"
11823             "    : b(0) {\n"
11824             "}",
11825             format("A()\n:b(0)\n{\n}", NoColumnLimit));
11826 
11827   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
11828   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
11829       FormatStyle::SFS_None;
11830   EXPECT_EQ("A()\n"
11831             "    : b(0) {\n"
11832             "}",
11833             format("A():b(0){}", DoNotMergeNoColumnLimit));
11834   EXPECT_EQ("A()\n"
11835             "    : b(0) {\n"
11836             "}",
11837             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
11838 
11839   verifyFormat("#define A          \\\n"
11840                "  void f() {       \\\n"
11841                "    int i;         \\\n"
11842                "  }",
11843                getLLVMStyleWithColumns(20));
11844   verifyFormat("#define A           \\\n"
11845                "  void f() { int i; }",
11846                getLLVMStyleWithColumns(21));
11847   verifyFormat("#define A            \\\n"
11848                "  void f() {         \\\n"
11849                "    int i;           \\\n"
11850                "  }                  \\\n"
11851                "  int j;",
11852                getLLVMStyleWithColumns(22));
11853   verifyFormat("#define A             \\\n"
11854                "  void f() { int i; } \\\n"
11855                "  int j;",
11856                getLLVMStyleWithColumns(23));
11857 }
11858 
11859 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
11860   FormatStyle MergeEmptyOnly = getLLVMStyle();
11861   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
11862   verifyFormat("class C {\n"
11863                "  int f() {}\n"
11864                "};",
11865                MergeEmptyOnly);
11866   verifyFormat("class C {\n"
11867                "  int f() {\n"
11868                "    return 42;\n"
11869                "  }\n"
11870                "};",
11871                MergeEmptyOnly);
11872   verifyFormat("int f() {}", MergeEmptyOnly);
11873   verifyFormat("int f() {\n"
11874                "  return 42;\n"
11875                "}",
11876                MergeEmptyOnly);
11877 
11878   // Also verify behavior when BraceWrapping.AfterFunction = true
11879   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11880   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
11881   verifyFormat("int f() {}", MergeEmptyOnly);
11882   verifyFormat("class C {\n"
11883                "  int f() {}\n"
11884                "};",
11885                MergeEmptyOnly);
11886 }
11887 
11888 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
11889   FormatStyle MergeInlineOnly = getLLVMStyle();
11890   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
11891   verifyFormat("class C {\n"
11892                "  int f() { return 42; }\n"
11893                "};",
11894                MergeInlineOnly);
11895   verifyFormat("int f() {\n"
11896                "  return 42;\n"
11897                "}",
11898                MergeInlineOnly);
11899 
11900   // SFS_Inline implies SFS_Empty
11901   verifyFormat("class C {\n"
11902                "  int f() {}\n"
11903                "};",
11904                MergeInlineOnly);
11905   verifyFormat("int f() {}", MergeInlineOnly);
11906 
11907   // Also verify behavior when BraceWrapping.AfterFunction = true
11908   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11909   MergeInlineOnly.BraceWrapping.AfterFunction = true;
11910   verifyFormat("class C {\n"
11911                "  int f() { return 42; }\n"
11912                "};",
11913                MergeInlineOnly);
11914   verifyFormat("int f()\n"
11915                "{\n"
11916                "  return 42;\n"
11917                "}",
11918                MergeInlineOnly);
11919 
11920   // SFS_Inline implies SFS_Empty
11921   verifyFormat("int f() {}", MergeInlineOnly);
11922   verifyFormat("class C {\n"
11923                "  int f() {}\n"
11924                "};",
11925                MergeInlineOnly);
11926 }
11927 
11928 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
11929   FormatStyle MergeInlineOnly = getLLVMStyle();
11930   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
11931       FormatStyle::SFS_InlineOnly;
11932   verifyFormat("class C {\n"
11933                "  int f() { return 42; }\n"
11934                "};",
11935                MergeInlineOnly);
11936   verifyFormat("int f() {\n"
11937                "  return 42;\n"
11938                "}",
11939                MergeInlineOnly);
11940 
11941   // SFS_InlineOnly does not imply SFS_Empty
11942   verifyFormat("class C {\n"
11943                "  int f() {}\n"
11944                "};",
11945                MergeInlineOnly);
11946   verifyFormat("int f() {\n"
11947                "}",
11948                MergeInlineOnly);
11949 
11950   // Also verify behavior when BraceWrapping.AfterFunction = true
11951   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11952   MergeInlineOnly.BraceWrapping.AfterFunction = true;
11953   verifyFormat("class C {\n"
11954                "  int f() { return 42; }\n"
11955                "};",
11956                MergeInlineOnly);
11957   verifyFormat("int f()\n"
11958                "{\n"
11959                "  return 42;\n"
11960                "}",
11961                MergeInlineOnly);
11962 
11963   // SFS_InlineOnly does not imply SFS_Empty
11964   verifyFormat("int f()\n"
11965                "{\n"
11966                "}",
11967                MergeInlineOnly);
11968   verifyFormat("class C {\n"
11969                "  int f() {}\n"
11970                "};",
11971                MergeInlineOnly);
11972 }
11973 
11974 TEST_F(FormatTest, SplitEmptyFunction) {
11975   FormatStyle Style = getLLVMStyle();
11976   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
11977   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
11978   Style.BraceWrapping.AfterFunction = true;
11979   Style.BraceWrapping.SplitEmptyFunction = false;
11980   Style.ColumnLimit = 40;
11981 
11982   verifyFormat("int f()\n"
11983                "{}",
11984                Style);
11985   verifyFormat("int f()\n"
11986                "{\n"
11987                "  return 42;\n"
11988                "}",
11989                Style);
11990   verifyFormat("int f()\n"
11991                "{\n"
11992                "  // some comment\n"
11993                "}",
11994                Style);
11995 
11996   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
11997   verifyFormat("int f() {}", Style);
11998   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
11999                "{}",
12000                Style);
12001   verifyFormat("int f()\n"
12002                "{\n"
12003                "  return 0;\n"
12004                "}",
12005                Style);
12006 
12007   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12008   verifyFormat("class Foo {\n"
12009                "  int f() {}\n"
12010                "};\n",
12011                Style);
12012   verifyFormat("class Foo {\n"
12013                "  int f() { return 0; }\n"
12014                "};\n",
12015                Style);
12016   verifyFormat("class Foo {\n"
12017                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12018                "  {}\n"
12019                "};\n",
12020                Style);
12021   verifyFormat("class Foo {\n"
12022                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12023                "  {\n"
12024                "    return 0;\n"
12025                "  }\n"
12026                "};\n",
12027                Style);
12028 
12029   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12030   verifyFormat("int f() {}", Style);
12031   verifyFormat("int f() { return 0; }", Style);
12032   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12033                "{}",
12034                Style);
12035   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12036                "{\n"
12037                "  return 0;\n"
12038                "}",
12039                Style);
12040 }
12041 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12042   FormatStyle Style = getLLVMStyle();
12043   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12044   verifyFormat("#ifdef A\n"
12045                "int f() {}\n"
12046                "#else\n"
12047                "int g() {}\n"
12048                "#endif",
12049                Style);
12050 }
12051 
12052 TEST_F(FormatTest, SplitEmptyClass) {
12053   FormatStyle Style = getLLVMStyle();
12054   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12055   Style.BraceWrapping.AfterClass = true;
12056   Style.BraceWrapping.SplitEmptyRecord = false;
12057 
12058   verifyFormat("class Foo\n"
12059                "{};",
12060                Style);
12061   verifyFormat("/* something */ class Foo\n"
12062                "{};",
12063                Style);
12064   verifyFormat("template <typename X> class Foo\n"
12065                "{};",
12066                Style);
12067   verifyFormat("class Foo\n"
12068                "{\n"
12069                "  Foo();\n"
12070                "};",
12071                Style);
12072   verifyFormat("typedef class Foo\n"
12073                "{\n"
12074                "} Foo_t;",
12075                Style);
12076 
12077   Style.BraceWrapping.SplitEmptyRecord = true;
12078   Style.BraceWrapping.AfterStruct = true;
12079   verifyFormat("class rep\n"
12080                "{\n"
12081                "};",
12082                Style);
12083   verifyFormat("struct rep\n"
12084                "{\n"
12085                "};",
12086                Style);
12087   verifyFormat("template <typename T> class rep\n"
12088                "{\n"
12089                "};",
12090                Style);
12091   verifyFormat("template <typename T> struct rep\n"
12092                "{\n"
12093                "};",
12094                Style);
12095   verifyFormat("class rep\n"
12096                "{\n"
12097                "  int x;\n"
12098                "};",
12099                Style);
12100   verifyFormat("struct rep\n"
12101                "{\n"
12102                "  int x;\n"
12103                "};",
12104                Style);
12105   verifyFormat("template <typename T> class rep\n"
12106                "{\n"
12107                "  int x;\n"
12108                "};",
12109                Style);
12110   verifyFormat("template <typename T> struct rep\n"
12111                "{\n"
12112                "  int x;\n"
12113                "};",
12114                Style);
12115   verifyFormat("template <typename T> class rep // Foo\n"
12116                "{\n"
12117                "  int x;\n"
12118                "};",
12119                Style);
12120   verifyFormat("template <typename T> struct rep // Bar\n"
12121                "{\n"
12122                "  int x;\n"
12123                "};",
12124                Style);
12125 
12126   verifyFormat("template <typename T> class rep<T>\n"
12127                "{\n"
12128                "  int x;\n"
12129                "};",
12130                Style);
12131 
12132   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12133                "{\n"
12134                "  int x;\n"
12135                "};",
12136                Style);
12137   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12138                "{\n"
12139                "};",
12140                Style);
12141 
12142   verifyFormat("#include \"stdint.h\"\n"
12143                "namespace rep {}",
12144                Style);
12145   verifyFormat("#include <stdint.h>\n"
12146                "namespace rep {}",
12147                Style);
12148   verifyFormat("#include <stdint.h>\n"
12149                "namespace rep {}",
12150                "#include <stdint.h>\n"
12151                "namespace rep {\n"
12152                "\n"
12153                "\n"
12154                "}",
12155                Style);
12156 }
12157 
12158 TEST_F(FormatTest, SplitEmptyStruct) {
12159   FormatStyle Style = getLLVMStyle();
12160   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12161   Style.BraceWrapping.AfterStruct = true;
12162   Style.BraceWrapping.SplitEmptyRecord = false;
12163 
12164   verifyFormat("struct Foo\n"
12165                "{};",
12166                Style);
12167   verifyFormat("/* something */ struct Foo\n"
12168                "{};",
12169                Style);
12170   verifyFormat("template <typename X> struct Foo\n"
12171                "{};",
12172                Style);
12173   verifyFormat("struct Foo\n"
12174                "{\n"
12175                "  Foo();\n"
12176                "};",
12177                Style);
12178   verifyFormat("typedef struct Foo\n"
12179                "{\n"
12180                "} Foo_t;",
12181                Style);
12182   // typedef struct Bar {} Bar_t;
12183 }
12184 
12185 TEST_F(FormatTest, SplitEmptyUnion) {
12186   FormatStyle Style = getLLVMStyle();
12187   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12188   Style.BraceWrapping.AfterUnion = true;
12189   Style.BraceWrapping.SplitEmptyRecord = false;
12190 
12191   verifyFormat("union Foo\n"
12192                "{};",
12193                Style);
12194   verifyFormat("/* something */ union Foo\n"
12195                "{};",
12196                Style);
12197   verifyFormat("union Foo\n"
12198                "{\n"
12199                "  A,\n"
12200                "};",
12201                Style);
12202   verifyFormat("typedef union Foo\n"
12203                "{\n"
12204                "} Foo_t;",
12205                Style);
12206 }
12207 
12208 TEST_F(FormatTest, SplitEmptyNamespace) {
12209   FormatStyle Style = getLLVMStyle();
12210   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12211   Style.BraceWrapping.AfterNamespace = true;
12212   Style.BraceWrapping.SplitEmptyNamespace = false;
12213 
12214   verifyFormat("namespace Foo\n"
12215                "{};",
12216                Style);
12217   verifyFormat("/* something */ namespace Foo\n"
12218                "{};",
12219                Style);
12220   verifyFormat("inline namespace Foo\n"
12221                "{};",
12222                Style);
12223   verifyFormat("/* something */ inline namespace Foo\n"
12224                "{};",
12225                Style);
12226   verifyFormat("export namespace Foo\n"
12227                "{};",
12228                Style);
12229   verifyFormat("namespace Foo\n"
12230                "{\n"
12231                "void Bar();\n"
12232                "};",
12233                Style);
12234 }
12235 
12236 TEST_F(FormatTest, NeverMergeShortRecords) {
12237   FormatStyle Style = getLLVMStyle();
12238 
12239   verifyFormat("class Foo {\n"
12240                "  Foo();\n"
12241                "};",
12242                Style);
12243   verifyFormat("typedef class Foo {\n"
12244                "  Foo();\n"
12245                "} Foo_t;",
12246                Style);
12247   verifyFormat("struct Foo {\n"
12248                "  Foo();\n"
12249                "};",
12250                Style);
12251   verifyFormat("typedef struct Foo {\n"
12252                "  Foo();\n"
12253                "} Foo_t;",
12254                Style);
12255   verifyFormat("union Foo {\n"
12256                "  A,\n"
12257                "};",
12258                Style);
12259   verifyFormat("typedef union Foo {\n"
12260                "  A,\n"
12261                "} Foo_t;",
12262                Style);
12263   verifyFormat("namespace Foo {\n"
12264                "void Bar();\n"
12265                "};",
12266                Style);
12267 
12268   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12269   Style.BraceWrapping.AfterClass = true;
12270   Style.BraceWrapping.AfterStruct = true;
12271   Style.BraceWrapping.AfterUnion = true;
12272   Style.BraceWrapping.AfterNamespace = true;
12273   verifyFormat("class Foo\n"
12274                "{\n"
12275                "  Foo();\n"
12276                "};",
12277                Style);
12278   verifyFormat("typedef class Foo\n"
12279                "{\n"
12280                "  Foo();\n"
12281                "} Foo_t;",
12282                Style);
12283   verifyFormat("struct Foo\n"
12284                "{\n"
12285                "  Foo();\n"
12286                "};",
12287                Style);
12288   verifyFormat("typedef struct Foo\n"
12289                "{\n"
12290                "  Foo();\n"
12291                "} Foo_t;",
12292                Style);
12293   verifyFormat("union Foo\n"
12294                "{\n"
12295                "  A,\n"
12296                "};",
12297                Style);
12298   verifyFormat("typedef union Foo\n"
12299                "{\n"
12300                "  A,\n"
12301                "} Foo_t;",
12302                Style);
12303   verifyFormat("namespace Foo\n"
12304                "{\n"
12305                "void Bar();\n"
12306                "};",
12307                Style);
12308 }
12309 
12310 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
12311   // Elaborate type variable declarations.
12312   verifyFormat("struct foo a = {bar};\nint n;");
12313   verifyFormat("class foo a = {bar};\nint n;");
12314   verifyFormat("union foo a = {bar};\nint n;");
12315 
12316   // Elaborate types inside function definitions.
12317   verifyFormat("struct foo f() {}\nint n;");
12318   verifyFormat("class foo f() {}\nint n;");
12319   verifyFormat("union foo f() {}\nint n;");
12320 
12321   // Templates.
12322   verifyFormat("template <class X> void f() {}\nint n;");
12323   verifyFormat("template <struct X> void f() {}\nint n;");
12324   verifyFormat("template <union X> void f() {}\nint n;");
12325 
12326   // Actual definitions...
12327   verifyFormat("struct {\n} n;");
12328   verifyFormat(
12329       "template <template <class T, class Y>, class Z> class X {\n} n;");
12330   verifyFormat("union Z {\n  int n;\n} x;");
12331   verifyFormat("class MACRO Z {\n} n;");
12332   verifyFormat("class MACRO(X) Z {\n} n;");
12333   verifyFormat("class __attribute__(X) Z {\n} n;");
12334   verifyFormat("class __declspec(X) Z {\n} n;");
12335   verifyFormat("class A##B##C {\n} n;");
12336   verifyFormat("class alignas(16) Z {\n} n;");
12337   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
12338   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
12339 
12340   // Redefinition from nested context:
12341   verifyFormat("class A::B::C {\n} n;");
12342 
12343   // Template definitions.
12344   verifyFormat(
12345       "template <typename F>\n"
12346       "Matcher(const Matcher<F> &Other,\n"
12347       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
12348       "                             !is_same<F, T>::value>::type * = 0)\n"
12349       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
12350 
12351   // FIXME: This is still incorrectly handled at the formatter side.
12352   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
12353   verifyFormat("int i = SomeFunction(a<b, a> b);");
12354 
12355   // FIXME:
12356   // This now gets parsed incorrectly as class definition.
12357   // verifyFormat("class A<int> f() {\n}\nint n;");
12358 
12359   // Elaborate types where incorrectly parsing the structural element would
12360   // break the indent.
12361   verifyFormat("if (true)\n"
12362                "  class X x;\n"
12363                "else\n"
12364                "  f();\n");
12365 
12366   // This is simply incomplete. Formatting is not important, but must not crash.
12367   verifyFormat("class A:");
12368 }
12369 
12370 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
12371   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
12372             format("#error Leave     all         white!!!!! space* alone!\n"));
12373   EXPECT_EQ(
12374       "#warning Leave     all         white!!!!! space* alone!\n",
12375       format("#warning Leave     all         white!!!!! space* alone!\n"));
12376   EXPECT_EQ("#error 1", format("  #  error   1"));
12377   EXPECT_EQ("#warning 1", format("  #  warning 1"));
12378 }
12379 
12380 TEST_F(FormatTest, FormatHashIfExpressions) {
12381   verifyFormat("#if AAAA && BBBB");
12382   verifyFormat("#if (AAAA && BBBB)");
12383   verifyFormat("#elif (AAAA && BBBB)");
12384   // FIXME: Come up with a better indentation for #elif.
12385   verifyFormat(
12386       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
12387       "    defined(BBBBBBBB)\n"
12388       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
12389       "    defined(BBBBBBBB)\n"
12390       "#endif",
12391       getLLVMStyleWithColumns(65));
12392 }
12393 
12394 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
12395   FormatStyle AllowsMergedIf = getGoogleStyle();
12396   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
12397       FormatStyle::SIS_WithoutElse;
12398   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
12399   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
12400   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
12401   EXPECT_EQ("if (true) return 42;",
12402             format("if (true)\nreturn 42;", AllowsMergedIf));
12403   FormatStyle ShortMergedIf = AllowsMergedIf;
12404   ShortMergedIf.ColumnLimit = 25;
12405   verifyFormat("#define A \\\n"
12406                "  if (true) return 42;",
12407                ShortMergedIf);
12408   verifyFormat("#define A \\\n"
12409                "  f();    \\\n"
12410                "  if (true)\n"
12411                "#define B",
12412                ShortMergedIf);
12413   verifyFormat("#define A \\\n"
12414                "  f();    \\\n"
12415                "  if (true)\n"
12416                "g();",
12417                ShortMergedIf);
12418   verifyFormat("{\n"
12419                "#ifdef A\n"
12420                "  // Comment\n"
12421                "  if (true) continue;\n"
12422                "#endif\n"
12423                "  // Comment\n"
12424                "  if (true) continue;\n"
12425                "}",
12426                ShortMergedIf);
12427   ShortMergedIf.ColumnLimit = 33;
12428   verifyFormat("#define A \\\n"
12429                "  if constexpr (true) return 42;",
12430                ShortMergedIf);
12431   verifyFormat("#define A \\\n"
12432                "  if CONSTEXPR (true) return 42;",
12433                ShortMergedIf);
12434   ShortMergedIf.ColumnLimit = 29;
12435   verifyFormat("#define A                   \\\n"
12436                "  if (aaaaaaaaaa) return 1; \\\n"
12437                "  return 2;",
12438                ShortMergedIf);
12439   ShortMergedIf.ColumnLimit = 28;
12440   verifyFormat("#define A         \\\n"
12441                "  if (aaaaaaaaaa) \\\n"
12442                "    return 1;     \\\n"
12443                "  return 2;",
12444                ShortMergedIf);
12445   verifyFormat("#define A                \\\n"
12446                "  if constexpr (aaaaaaa) \\\n"
12447                "    return 1;            \\\n"
12448                "  return 2;",
12449                ShortMergedIf);
12450   verifyFormat("#define A                \\\n"
12451                "  if CONSTEXPR (aaaaaaa) \\\n"
12452                "    return 1;            \\\n"
12453                "  return 2;",
12454                ShortMergedIf);
12455 }
12456 
12457 TEST_F(FormatTest, FormatStarDependingOnContext) {
12458   verifyFormat("void f(int *a);");
12459   verifyFormat("void f() { f(fint * b); }");
12460   verifyFormat("class A {\n  void f(int *a);\n};");
12461   verifyFormat("class A {\n  int *a;\n};");
12462   verifyFormat("namespace a {\n"
12463                "namespace b {\n"
12464                "class A {\n"
12465                "  void f() {}\n"
12466                "  int *a;\n"
12467                "};\n"
12468                "} // namespace b\n"
12469                "} // namespace a");
12470 }
12471 
12472 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
12473   verifyFormat("while");
12474   verifyFormat("operator");
12475 }
12476 
12477 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
12478   // This code would be painfully slow to format if we didn't skip it.
12479   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
12480                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12481                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12482                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12483                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12484                    "A(1, 1)\n"
12485                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
12486                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12487                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12488                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12489                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12490                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12491                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12492                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12493                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12494                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
12495   // Deeply nested part is untouched, rest is formatted.
12496   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
12497             format(std::string("int    i;\n") + Code + "int    j;\n",
12498                    getLLVMStyle(), SC_ExpectIncomplete));
12499 }
12500 
12501 //===----------------------------------------------------------------------===//
12502 // Objective-C tests.
12503 //===----------------------------------------------------------------------===//
12504 
12505 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
12506   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
12507   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
12508             format("-(NSUInteger)indexOfObject:(id)anObject;"));
12509   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
12510   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
12511   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
12512             format("-(NSInteger)Method3:(id)anObject;"));
12513   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
12514             format("-(NSInteger)Method4:(id)anObject;"));
12515   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
12516             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
12517   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
12518             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
12519   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12520             "forAllCells:(BOOL)flag;",
12521             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12522                    "forAllCells:(BOOL)flag;"));
12523 
12524   // Very long objectiveC method declaration.
12525   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
12526                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
12527   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
12528                "                    inRange:(NSRange)range\n"
12529                "                   outRange:(NSRange)out_range\n"
12530                "                  outRange1:(NSRange)out_range1\n"
12531                "                  outRange2:(NSRange)out_range2\n"
12532                "                  outRange3:(NSRange)out_range3\n"
12533                "                  outRange4:(NSRange)out_range4\n"
12534                "                  outRange5:(NSRange)out_range5\n"
12535                "                  outRange6:(NSRange)out_range6\n"
12536                "                  outRange7:(NSRange)out_range7\n"
12537                "                  outRange8:(NSRange)out_range8\n"
12538                "                  outRange9:(NSRange)out_range9;");
12539 
12540   // When the function name has to be wrapped.
12541   FormatStyle Style = getLLVMStyle();
12542   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
12543   // and always indents instead.
12544   Style.IndentWrappedFunctionNames = false;
12545   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12546                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
12547                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
12548                "}",
12549                Style);
12550   Style.IndentWrappedFunctionNames = true;
12551   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12552                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
12553                "               anotherName:(NSString)dddddddddddddd {\n"
12554                "}",
12555                Style);
12556 
12557   verifyFormat("- (int)sum:(vector<int>)numbers;");
12558   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
12559   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
12560   // protocol lists (but not for template classes):
12561   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
12562 
12563   verifyFormat("- (int (*)())foo:(int (*)())f;");
12564   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
12565 
12566   // If there's no return type (very rare in practice!), LLVM and Google style
12567   // agree.
12568   verifyFormat("- foo;");
12569   verifyFormat("- foo:(int)f;");
12570   verifyGoogleFormat("- foo:(int)foo;");
12571 }
12572 
12573 TEST_F(FormatTest, BreaksStringLiterals) {
12574   EXPECT_EQ("\"some text \"\n"
12575             "\"other\";",
12576             format("\"some text other\";", getLLVMStyleWithColumns(12)));
12577   EXPECT_EQ("\"some text \"\n"
12578             "\"other\";",
12579             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
12580   EXPECT_EQ(
12581       "#define A  \\\n"
12582       "  \"some \"  \\\n"
12583       "  \"text \"  \\\n"
12584       "  \"other\";",
12585       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
12586   EXPECT_EQ(
12587       "#define A  \\\n"
12588       "  \"so \"    \\\n"
12589       "  \"text \"  \\\n"
12590       "  \"other\";",
12591       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
12592 
12593   EXPECT_EQ("\"some text\"",
12594             format("\"some text\"", getLLVMStyleWithColumns(1)));
12595   EXPECT_EQ("\"some text\"",
12596             format("\"some text\"", getLLVMStyleWithColumns(11)));
12597   EXPECT_EQ("\"some \"\n"
12598             "\"text\"",
12599             format("\"some text\"", getLLVMStyleWithColumns(10)));
12600   EXPECT_EQ("\"some \"\n"
12601             "\"text\"",
12602             format("\"some text\"", getLLVMStyleWithColumns(7)));
12603   EXPECT_EQ("\"some\"\n"
12604             "\" tex\"\n"
12605             "\"t\"",
12606             format("\"some text\"", getLLVMStyleWithColumns(6)));
12607   EXPECT_EQ("\"some\"\n"
12608             "\" tex\"\n"
12609             "\" and\"",
12610             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
12611   EXPECT_EQ("\"some\"\n"
12612             "\"/tex\"\n"
12613             "\"/and\"",
12614             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
12615 
12616   EXPECT_EQ("variable =\n"
12617             "    \"long string \"\n"
12618             "    \"literal\";",
12619             format("variable = \"long string literal\";",
12620                    getLLVMStyleWithColumns(20)));
12621 
12622   EXPECT_EQ("variable = f(\n"
12623             "    \"long string \"\n"
12624             "    \"literal\",\n"
12625             "    short,\n"
12626             "    loooooooooooooooooooong);",
12627             format("variable = f(\"long string literal\", short, "
12628                    "loooooooooooooooooooong);",
12629                    getLLVMStyleWithColumns(20)));
12630 
12631   EXPECT_EQ(
12632       "f(g(\"long string \"\n"
12633       "    \"literal\"),\n"
12634       "  b);",
12635       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
12636   EXPECT_EQ("f(g(\"long string \"\n"
12637             "    \"literal\",\n"
12638             "    a),\n"
12639             "  b);",
12640             format("f(g(\"long string literal\", a), b);",
12641                    getLLVMStyleWithColumns(20)));
12642   EXPECT_EQ(
12643       "f(\"one two\".split(\n"
12644       "    variable));",
12645       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
12646   EXPECT_EQ("f(\"one two three four five six \"\n"
12647             "  \"seven\".split(\n"
12648             "      really_looooong_variable));",
12649             format("f(\"one two three four five six seven\"."
12650                    "split(really_looooong_variable));",
12651                    getLLVMStyleWithColumns(33)));
12652 
12653   EXPECT_EQ("f(\"some \"\n"
12654             "  \"text\",\n"
12655             "  other);",
12656             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
12657 
12658   // Only break as a last resort.
12659   verifyFormat(
12660       "aaaaaaaaaaaaaaaaaaaa(\n"
12661       "    aaaaaaaaaaaaaaaaaaaa,\n"
12662       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
12663 
12664   EXPECT_EQ("\"splitmea\"\n"
12665             "\"trandomp\"\n"
12666             "\"oint\"",
12667             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
12668 
12669   EXPECT_EQ("\"split/\"\n"
12670             "\"pathat/\"\n"
12671             "\"slashes\"",
12672             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
12673 
12674   EXPECT_EQ("\"split/\"\n"
12675             "\"pathat/\"\n"
12676             "\"slashes\"",
12677             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
12678   EXPECT_EQ("\"split at \"\n"
12679             "\"spaces/at/\"\n"
12680             "\"slashes.at.any$\"\n"
12681             "\"non-alphanumeric%\"\n"
12682             "\"1111111111characte\"\n"
12683             "\"rs\"",
12684             format("\"split at "
12685                    "spaces/at/"
12686                    "slashes.at."
12687                    "any$non-"
12688                    "alphanumeric%"
12689                    "1111111111characte"
12690                    "rs\"",
12691                    getLLVMStyleWithColumns(20)));
12692 
12693   // Verify that splitting the strings understands
12694   // Style::AlwaysBreakBeforeMultilineStrings.
12695   EXPECT_EQ("aaaaaaaaaaaa(\n"
12696             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
12697             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
12698             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
12699                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
12700                    "aaaaaaaaaaaaaaaaaaaaaa\");",
12701                    getGoogleStyle()));
12702   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12703             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
12704             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
12705                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
12706                    "aaaaaaaaaaaaaaaaaaaaaa\";",
12707                    getGoogleStyle()));
12708   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12709             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
12710             format("llvm::outs() << "
12711                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
12712                    "aaaaaaaaaaaaaaaaaaa\";"));
12713   EXPECT_EQ("ffff(\n"
12714             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12715             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
12716             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
12717                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
12718                    getGoogleStyle()));
12719 
12720   FormatStyle Style = getLLVMStyleWithColumns(12);
12721   Style.BreakStringLiterals = false;
12722   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
12723 
12724   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
12725   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
12726   EXPECT_EQ("#define A \\\n"
12727             "  \"some \" \\\n"
12728             "  \"text \" \\\n"
12729             "  \"other\";",
12730             format("#define A \"some text other\";", AlignLeft));
12731 }
12732 
12733 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
12734   EXPECT_EQ("C a = \"some more \"\n"
12735             "      \"text\";",
12736             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
12737 }
12738 
12739 TEST_F(FormatTest, FullyRemoveEmptyLines) {
12740   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
12741   NoEmptyLines.MaxEmptyLinesToKeep = 0;
12742   EXPECT_EQ("int i = a(b());",
12743             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
12744 }
12745 
12746 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
12747   EXPECT_EQ(
12748       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12749       "(\n"
12750       "    \"x\t\");",
12751       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12752              "aaaaaaa("
12753              "\"x\t\");"));
12754 }
12755 
12756 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
12757   EXPECT_EQ(
12758       "u8\"utf8 string \"\n"
12759       "u8\"literal\";",
12760       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
12761   EXPECT_EQ(
12762       "u\"utf16 string \"\n"
12763       "u\"literal\";",
12764       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
12765   EXPECT_EQ(
12766       "U\"utf32 string \"\n"
12767       "U\"literal\";",
12768       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
12769   EXPECT_EQ("L\"wide string \"\n"
12770             "L\"literal\";",
12771             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
12772   EXPECT_EQ("@\"NSString \"\n"
12773             "@\"literal\";",
12774             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
12775   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
12776 
12777   // This input makes clang-format try to split the incomplete unicode escape
12778   // sequence, which used to lead to a crasher.
12779   verifyNoCrash(
12780       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
12781       getLLVMStyleWithColumns(60));
12782 }
12783 
12784 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
12785   FormatStyle Style = getGoogleStyleWithColumns(15);
12786   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
12787   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
12788   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
12789   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
12790   EXPECT_EQ("u8R\"x(raw literal)x\";",
12791             format("u8R\"x(raw literal)x\";", Style));
12792 }
12793 
12794 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
12795   FormatStyle Style = getLLVMStyleWithColumns(20);
12796   EXPECT_EQ(
12797       "_T(\"aaaaaaaaaaaaaa\")\n"
12798       "_T(\"aaaaaaaaaaaaaa\")\n"
12799       "_T(\"aaaaaaaaaaaa\")",
12800       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
12801   EXPECT_EQ("f(x,\n"
12802             "  _T(\"aaaaaaaaaaaa\")\n"
12803             "  _T(\"aaa\"),\n"
12804             "  z);",
12805             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
12806 
12807   // FIXME: Handle embedded spaces in one iteration.
12808   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
12809   //            "_T(\"aaaaaaaaaaaaa\")\n"
12810   //            "_T(\"aaaaaaaaaaaaa\")\n"
12811   //            "_T(\"a\")",
12812   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
12813   //                   getLLVMStyleWithColumns(20)));
12814   EXPECT_EQ(
12815       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
12816       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
12817   EXPECT_EQ("f(\n"
12818             "#if !TEST\n"
12819             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
12820             "#endif\n"
12821             ");",
12822             format("f(\n"
12823                    "#if !TEST\n"
12824                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
12825                    "#endif\n"
12826                    ");"));
12827   EXPECT_EQ("f(\n"
12828             "\n"
12829             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
12830             format("f(\n"
12831                    "\n"
12832                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
12833 }
12834 
12835 TEST_F(FormatTest, BreaksStringLiteralOperands) {
12836   // In a function call with two operands, the second can be broken with no line
12837   // break before it.
12838   EXPECT_EQ(
12839       "func(a, \"long long \"\n"
12840       "        \"long long\");",
12841       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
12842   // In a function call with three operands, the second must be broken with a
12843   // line break before it.
12844   EXPECT_EQ("func(a,\n"
12845             "     \"long long long \"\n"
12846             "     \"long\",\n"
12847             "     c);",
12848             format("func(a, \"long long long long\", c);",
12849                    getLLVMStyleWithColumns(24)));
12850   // In a function call with three operands, the third must be broken with a
12851   // line break before it.
12852   EXPECT_EQ("func(a, b,\n"
12853             "     \"long long long \"\n"
12854             "     \"long\");",
12855             format("func(a, b, \"long long long long\");",
12856                    getLLVMStyleWithColumns(24)));
12857   // In a function call with three operands, both the second and the third must
12858   // be broken with a line break before them.
12859   EXPECT_EQ("func(a,\n"
12860             "     \"long long long \"\n"
12861             "     \"long\",\n"
12862             "     \"long long long \"\n"
12863             "     \"long\");",
12864             format("func(a, \"long long long long\", \"long long long long\");",
12865                    getLLVMStyleWithColumns(24)));
12866   // In a chain of << with two operands, the second can be broken with no line
12867   // break before it.
12868   EXPECT_EQ("a << \"line line \"\n"
12869             "     \"line\";",
12870             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
12871   // In a chain of << with three operands, the second can be broken with no line
12872   // break before it.
12873   EXPECT_EQ(
12874       "abcde << \"line \"\n"
12875       "         \"line line\"\n"
12876       "      << c;",
12877       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
12878   // In a chain of << with three operands, the third must be broken with a line
12879   // break before it.
12880   EXPECT_EQ(
12881       "a << b\n"
12882       "  << \"line line \"\n"
12883       "     \"line\";",
12884       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
12885   // In a chain of << with three operands, the second can be broken with no line
12886   // break before it and the third must be broken with a line break before it.
12887   EXPECT_EQ("abcd << \"line line \"\n"
12888             "        \"line\"\n"
12889             "     << \"line line \"\n"
12890             "        \"line\";",
12891             format("abcd << \"line line line\" << \"line line line\";",
12892                    getLLVMStyleWithColumns(20)));
12893   // In a chain of binary operators with two operands, the second can be broken
12894   // with no line break before it.
12895   EXPECT_EQ(
12896       "abcd + \"line line \"\n"
12897       "       \"line line\";",
12898       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
12899   // In a chain of binary operators with three operands, the second must be
12900   // broken with a line break before it.
12901   EXPECT_EQ("abcd +\n"
12902             "    \"line line \"\n"
12903             "    \"line line\" +\n"
12904             "    e;",
12905             format("abcd + \"line line line line\" + e;",
12906                    getLLVMStyleWithColumns(20)));
12907   // In a function call with two operands, with AlignAfterOpenBracket enabled,
12908   // the first must be broken with a line break before it.
12909   FormatStyle Style = getLLVMStyleWithColumns(25);
12910   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12911   EXPECT_EQ("someFunction(\n"
12912             "    \"long long long \"\n"
12913             "    \"long\",\n"
12914             "    a);",
12915             format("someFunction(\"long long long long\", a);", Style));
12916 }
12917 
12918 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
12919   EXPECT_EQ(
12920       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12921       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12922       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
12923       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12924              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12925              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
12926 }
12927 
12928 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
12929   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
12930             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
12931   EXPECT_EQ("fffffffffff(g(R\"x(\n"
12932             "multiline raw string literal xxxxxxxxxxxxxx\n"
12933             ")x\",\n"
12934             "              a),\n"
12935             "            b);",
12936             format("fffffffffff(g(R\"x(\n"
12937                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12938                    ")x\", a), b);",
12939                    getGoogleStyleWithColumns(20)));
12940   EXPECT_EQ("fffffffffff(\n"
12941             "    g(R\"x(qqq\n"
12942             "multiline raw string literal xxxxxxxxxxxxxx\n"
12943             ")x\",\n"
12944             "      a),\n"
12945             "    b);",
12946             format("fffffffffff(g(R\"x(qqq\n"
12947                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12948                    ")x\", a), b);",
12949                    getGoogleStyleWithColumns(20)));
12950 
12951   EXPECT_EQ("fffffffffff(R\"x(\n"
12952             "multiline raw string literal xxxxxxxxxxxxxx\n"
12953             ")x\");",
12954             format("fffffffffff(R\"x(\n"
12955                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12956                    ")x\");",
12957                    getGoogleStyleWithColumns(20)));
12958   EXPECT_EQ("fffffffffff(R\"x(\n"
12959             "multiline raw string literal xxxxxxxxxxxxxx\n"
12960             ")x\" + bbbbbb);",
12961             format("fffffffffff(R\"x(\n"
12962                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12963                    ")x\" +   bbbbbb);",
12964                    getGoogleStyleWithColumns(20)));
12965   EXPECT_EQ("fffffffffff(\n"
12966             "    R\"x(\n"
12967             "multiline raw string literal xxxxxxxxxxxxxx\n"
12968             ")x\" +\n"
12969             "    bbbbbb);",
12970             format("fffffffffff(\n"
12971                    " R\"x(\n"
12972                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12973                    ")x\" + bbbbbb);",
12974                    getGoogleStyleWithColumns(20)));
12975   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
12976             format("fffffffffff(\n"
12977                    " R\"(single line raw string)\" + bbbbbb);"));
12978 }
12979 
12980 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
12981   verifyFormat("string a = \"unterminated;");
12982   EXPECT_EQ("function(\"unterminated,\n"
12983             "         OtherParameter);",
12984             format("function(  \"unterminated,\n"
12985                    "    OtherParameter);"));
12986 }
12987 
12988 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
12989   FormatStyle Style = getLLVMStyle();
12990   Style.Standard = FormatStyle::LS_Cpp03;
12991   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
12992             format("#define x(_a) printf(\"foo\"_a);", Style));
12993 }
12994 
12995 TEST_F(FormatTest, CppLexVersion) {
12996   FormatStyle Style = getLLVMStyle();
12997   // Formatting of x * y differs if x is a type.
12998   verifyFormat("void foo() { MACRO(a * b); }", Style);
12999   verifyFormat("void foo() { MACRO(int *b); }", Style);
13000 
13001   // LLVM style uses latest lexer.
13002   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13003   Style.Standard = FormatStyle::LS_Cpp17;
13004   // But in c++17, char8_t isn't a keyword.
13005   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13006 }
13007 
13008 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13009 
13010 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13011   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13012             "             \"ddeeefff\");",
13013             format("someFunction(\"aaabbbcccdddeeefff\");",
13014                    getLLVMStyleWithColumns(25)));
13015   EXPECT_EQ("someFunction1234567890(\n"
13016             "    \"aaabbbcccdddeeefff\");",
13017             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13018                    getLLVMStyleWithColumns(26)));
13019   EXPECT_EQ("someFunction1234567890(\n"
13020             "    \"aaabbbcccdddeeeff\"\n"
13021             "    \"f\");",
13022             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13023                    getLLVMStyleWithColumns(25)));
13024   EXPECT_EQ("someFunction1234567890(\n"
13025             "    \"aaabbbcccdddeeeff\"\n"
13026             "    \"f\");",
13027             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13028                    getLLVMStyleWithColumns(24)));
13029   EXPECT_EQ("someFunction(\n"
13030             "    \"aaabbbcc ddde \"\n"
13031             "    \"efff\");",
13032             format("someFunction(\"aaabbbcc ddde efff\");",
13033                    getLLVMStyleWithColumns(25)));
13034   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13035             "             \"ddeeefff\");",
13036             format("someFunction(\"aaabbbccc ddeeefff\");",
13037                    getLLVMStyleWithColumns(25)));
13038   EXPECT_EQ("someFunction1234567890(\n"
13039             "    \"aaabb \"\n"
13040             "    \"cccdddeeefff\");",
13041             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13042                    getLLVMStyleWithColumns(25)));
13043   EXPECT_EQ("#define A          \\\n"
13044             "  string s =       \\\n"
13045             "      \"123456789\"  \\\n"
13046             "      \"0\";         \\\n"
13047             "  int i;",
13048             format("#define A string s = \"1234567890\"; int i;",
13049                    getLLVMStyleWithColumns(20)));
13050   EXPECT_EQ("someFunction(\n"
13051             "    \"aaabbbcc \"\n"
13052             "    \"dddeeefff\");",
13053             format("someFunction(\"aaabbbcc dddeeefff\");",
13054                    getLLVMStyleWithColumns(25)));
13055 }
13056 
13057 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13058   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13059   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13060   EXPECT_EQ("\"test\"\n"
13061             "\"\\n\"",
13062             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13063   EXPECT_EQ("\"tes\\\\\"\n"
13064             "\"n\"",
13065             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
13066   EXPECT_EQ("\"\\\\\\\\\"\n"
13067             "\"\\n\"",
13068             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
13069   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
13070   EXPECT_EQ("\"\\uff01\"\n"
13071             "\"test\"",
13072             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
13073   EXPECT_EQ("\"\\Uff01ff02\"",
13074             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
13075   EXPECT_EQ("\"\\x000000000001\"\n"
13076             "\"next\"",
13077             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
13078   EXPECT_EQ("\"\\x000000000001next\"",
13079             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
13080   EXPECT_EQ("\"\\x000000000001\"",
13081             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
13082   EXPECT_EQ("\"test\"\n"
13083             "\"\\000000\"\n"
13084             "\"000001\"",
13085             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
13086   EXPECT_EQ("\"test\\000\"\n"
13087             "\"00000000\"\n"
13088             "\"1\"",
13089             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
13090 }
13091 
13092 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
13093   verifyFormat("void f() {\n"
13094                "  return g() {}\n"
13095                "  void h() {}");
13096   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
13097                "g();\n"
13098                "}");
13099 }
13100 
13101 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
13102   verifyFormat(
13103       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
13104 }
13105 
13106 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
13107   verifyFormat("class X {\n"
13108                "  void f() {\n"
13109                "  }\n"
13110                "};",
13111                getLLVMStyleWithColumns(12));
13112 }
13113 
13114 TEST_F(FormatTest, ConfigurableIndentWidth) {
13115   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
13116   EightIndent.IndentWidth = 8;
13117   EightIndent.ContinuationIndentWidth = 8;
13118   verifyFormat("void f() {\n"
13119                "        someFunction();\n"
13120                "        if (true) {\n"
13121                "                f();\n"
13122                "        }\n"
13123                "}",
13124                EightIndent);
13125   verifyFormat("class X {\n"
13126                "        void f() {\n"
13127                "        }\n"
13128                "};",
13129                EightIndent);
13130   verifyFormat("int x[] = {\n"
13131                "        call(),\n"
13132                "        call()};",
13133                EightIndent);
13134 }
13135 
13136 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
13137   verifyFormat("double\n"
13138                "f();",
13139                getLLVMStyleWithColumns(8));
13140 }
13141 
13142 TEST_F(FormatTest, ConfigurableUseOfTab) {
13143   FormatStyle Tab = getLLVMStyleWithColumns(42);
13144   Tab.IndentWidth = 8;
13145   Tab.UseTab = FormatStyle::UT_Always;
13146   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13147 
13148   EXPECT_EQ("if (aaaaaaaa && // q\n"
13149             "    bb)\t\t// w\n"
13150             "\t;",
13151             format("if (aaaaaaaa &&// q\n"
13152                    "bb)// w\n"
13153                    ";",
13154                    Tab));
13155   EXPECT_EQ("if (aaa && bbb) // w\n"
13156             "\t;",
13157             format("if(aaa&&bbb)// w\n"
13158                    ";",
13159                    Tab));
13160 
13161   verifyFormat("class X {\n"
13162                "\tvoid f() {\n"
13163                "\t\tsomeFunction(parameter1,\n"
13164                "\t\t\t     parameter2);\n"
13165                "\t}\n"
13166                "};",
13167                Tab);
13168   verifyFormat("#define A                        \\\n"
13169                "\tvoid f() {               \\\n"
13170                "\t\tsomeFunction(    \\\n"
13171                "\t\t    parameter1,  \\\n"
13172                "\t\t    parameter2); \\\n"
13173                "\t}",
13174                Tab);
13175   verifyFormat("int a;\t      // x\n"
13176                "int bbbbbbbb; // x\n",
13177                Tab);
13178 
13179   Tab.TabWidth = 4;
13180   Tab.IndentWidth = 8;
13181   verifyFormat("class TabWidth4Indent8 {\n"
13182                "\t\tvoid f() {\n"
13183                "\t\t\t\tsomeFunction(parameter1,\n"
13184                "\t\t\t\t\t\t\t parameter2);\n"
13185                "\t\t}\n"
13186                "};",
13187                Tab);
13188 
13189   Tab.TabWidth = 4;
13190   Tab.IndentWidth = 4;
13191   verifyFormat("class TabWidth4Indent4 {\n"
13192                "\tvoid f() {\n"
13193                "\t\tsomeFunction(parameter1,\n"
13194                "\t\t\t\t\t parameter2);\n"
13195                "\t}\n"
13196                "};",
13197                Tab);
13198 
13199   Tab.TabWidth = 8;
13200   Tab.IndentWidth = 4;
13201   verifyFormat("class TabWidth8Indent4 {\n"
13202                "    void f() {\n"
13203                "\tsomeFunction(parameter1,\n"
13204                "\t\t     parameter2);\n"
13205                "    }\n"
13206                "};",
13207                Tab);
13208 
13209   Tab.TabWidth = 8;
13210   Tab.IndentWidth = 8;
13211   EXPECT_EQ("/*\n"
13212             "\t      a\t\tcomment\n"
13213             "\t      in multiple lines\n"
13214             "       */",
13215             format("   /*\t \t \n"
13216                    " \t \t a\t\tcomment\t \t\n"
13217                    " \t \t in multiple lines\t\n"
13218                    " \t  */",
13219                    Tab));
13220 
13221   Tab.UseTab = FormatStyle::UT_ForIndentation;
13222   verifyFormat("{\n"
13223                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13224                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13225                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13226                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13227                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13228                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13229                "};",
13230                Tab);
13231   verifyFormat("enum AA {\n"
13232                "\ta1, // Force multiple lines\n"
13233                "\ta2,\n"
13234                "\ta3\n"
13235                "};",
13236                Tab);
13237   EXPECT_EQ("if (aaaaaaaa && // q\n"
13238             "    bb)         // w\n"
13239             "\t;",
13240             format("if (aaaaaaaa &&// q\n"
13241                    "bb)// w\n"
13242                    ";",
13243                    Tab));
13244   verifyFormat("class X {\n"
13245                "\tvoid f() {\n"
13246                "\t\tsomeFunction(parameter1,\n"
13247                "\t\t             parameter2);\n"
13248                "\t}\n"
13249                "};",
13250                Tab);
13251   verifyFormat("{\n"
13252                "\tQ(\n"
13253                "\t    {\n"
13254                "\t\t    int a;\n"
13255                "\t\t    someFunction(aaaaaaaa,\n"
13256                "\t\t                 bbbbbbb);\n"
13257                "\t    },\n"
13258                "\t    p);\n"
13259                "}",
13260                Tab);
13261   EXPECT_EQ("{\n"
13262             "\t/* aaaa\n"
13263             "\t   bbbb */\n"
13264             "}",
13265             format("{\n"
13266                    "/* aaaa\n"
13267                    "   bbbb */\n"
13268                    "}",
13269                    Tab));
13270   EXPECT_EQ("{\n"
13271             "\t/*\n"
13272             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13273             "\t  bbbbbbbbbbbbb\n"
13274             "\t*/\n"
13275             "}",
13276             format("{\n"
13277                    "/*\n"
13278                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13279                    "*/\n"
13280                    "}",
13281                    Tab));
13282   EXPECT_EQ("{\n"
13283             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13284             "\t// bbbbbbbbbbbbb\n"
13285             "}",
13286             format("{\n"
13287                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13288                    "}",
13289                    Tab));
13290   EXPECT_EQ("{\n"
13291             "\t/*\n"
13292             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13293             "\t  bbbbbbbbbbbbb\n"
13294             "\t*/\n"
13295             "}",
13296             format("{\n"
13297                    "\t/*\n"
13298                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13299                    "\t*/\n"
13300                    "}",
13301                    Tab));
13302   EXPECT_EQ("{\n"
13303             "\t/*\n"
13304             "\n"
13305             "\t*/\n"
13306             "}",
13307             format("{\n"
13308                    "\t/*\n"
13309                    "\n"
13310                    "\t*/\n"
13311                    "}",
13312                    Tab));
13313   EXPECT_EQ("{\n"
13314             "\t/*\n"
13315             " asdf\n"
13316             "\t*/\n"
13317             "}",
13318             format("{\n"
13319                    "\t/*\n"
13320                    " asdf\n"
13321                    "\t*/\n"
13322                    "}",
13323                    Tab));
13324 
13325   Tab.UseTab = FormatStyle::UT_Never;
13326   EXPECT_EQ("/*\n"
13327             "              a\t\tcomment\n"
13328             "              in multiple lines\n"
13329             "       */",
13330             format("   /*\t \t \n"
13331                    " \t \t a\t\tcomment\t \t\n"
13332                    " \t \t in multiple lines\t\n"
13333                    " \t  */",
13334                    Tab));
13335   EXPECT_EQ("/* some\n"
13336             "   comment */",
13337             format(" \t \t /* some\n"
13338                    " \t \t    comment */",
13339                    Tab));
13340   EXPECT_EQ("int a; /* some\n"
13341             "   comment */",
13342             format(" \t \t int a; /* some\n"
13343                    " \t \t    comment */",
13344                    Tab));
13345 
13346   EXPECT_EQ("int a; /* some\n"
13347             "comment */",
13348             format(" \t \t int\ta; /* some\n"
13349                    " \t \t    comment */",
13350                    Tab));
13351   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13352             "    comment */",
13353             format(" \t \t f(\"\t\t\"); /* some\n"
13354                    " \t \t    comment */",
13355                    Tab));
13356   EXPECT_EQ("{\n"
13357             "        /*\n"
13358             "         * Comment\n"
13359             "         */\n"
13360             "        int i;\n"
13361             "}",
13362             format("{\n"
13363                    "\t/*\n"
13364                    "\t * Comment\n"
13365                    "\t */\n"
13366                    "\t int i;\n"
13367                    "}",
13368                    Tab));
13369 
13370   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13371   Tab.TabWidth = 8;
13372   Tab.IndentWidth = 8;
13373   EXPECT_EQ("if (aaaaaaaa && // q\n"
13374             "    bb)         // w\n"
13375             "\t;",
13376             format("if (aaaaaaaa &&// q\n"
13377                    "bb)// w\n"
13378                    ";",
13379                    Tab));
13380   EXPECT_EQ("if (aaa && bbb) // w\n"
13381             "\t;",
13382             format("if(aaa&&bbb)// w\n"
13383                    ";",
13384                    Tab));
13385   verifyFormat("class X {\n"
13386                "\tvoid f() {\n"
13387                "\t\tsomeFunction(parameter1,\n"
13388                "\t\t\t     parameter2);\n"
13389                "\t}\n"
13390                "};",
13391                Tab);
13392   verifyFormat("#define A                        \\\n"
13393                "\tvoid f() {               \\\n"
13394                "\t\tsomeFunction(    \\\n"
13395                "\t\t    parameter1,  \\\n"
13396                "\t\t    parameter2); \\\n"
13397                "\t}",
13398                Tab);
13399   Tab.TabWidth = 4;
13400   Tab.IndentWidth = 8;
13401   verifyFormat("class TabWidth4Indent8 {\n"
13402                "\t\tvoid f() {\n"
13403                "\t\t\t\tsomeFunction(parameter1,\n"
13404                "\t\t\t\t\t\t\t parameter2);\n"
13405                "\t\t}\n"
13406                "};",
13407                Tab);
13408   Tab.TabWidth = 4;
13409   Tab.IndentWidth = 4;
13410   verifyFormat("class TabWidth4Indent4 {\n"
13411                "\tvoid f() {\n"
13412                "\t\tsomeFunction(parameter1,\n"
13413                "\t\t\t\t\t parameter2);\n"
13414                "\t}\n"
13415                "};",
13416                Tab);
13417   Tab.TabWidth = 8;
13418   Tab.IndentWidth = 4;
13419   verifyFormat("class TabWidth8Indent4 {\n"
13420                "    void f() {\n"
13421                "\tsomeFunction(parameter1,\n"
13422                "\t\t     parameter2);\n"
13423                "    }\n"
13424                "};",
13425                Tab);
13426   Tab.TabWidth = 8;
13427   Tab.IndentWidth = 8;
13428   EXPECT_EQ("/*\n"
13429             "\t      a\t\tcomment\n"
13430             "\t      in multiple lines\n"
13431             "       */",
13432             format("   /*\t \t \n"
13433                    " \t \t a\t\tcomment\t \t\n"
13434                    " \t \t in multiple lines\t\n"
13435                    " \t  */",
13436                    Tab));
13437   verifyFormat("{\n"
13438                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13439                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13440                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13441                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13442                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13443                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13444                "};",
13445                Tab);
13446   verifyFormat("enum AA {\n"
13447                "\ta1, // Force multiple lines\n"
13448                "\ta2,\n"
13449                "\ta3\n"
13450                "};",
13451                Tab);
13452   EXPECT_EQ("if (aaaaaaaa && // q\n"
13453             "    bb)         // w\n"
13454             "\t;",
13455             format("if (aaaaaaaa &&// q\n"
13456                    "bb)// w\n"
13457                    ";",
13458                    Tab));
13459   verifyFormat("class X {\n"
13460                "\tvoid f() {\n"
13461                "\t\tsomeFunction(parameter1,\n"
13462                "\t\t\t     parameter2);\n"
13463                "\t}\n"
13464                "};",
13465                Tab);
13466   verifyFormat("{\n"
13467                "\tQ(\n"
13468                "\t    {\n"
13469                "\t\t    int a;\n"
13470                "\t\t    someFunction(aaaaaaaa,\n"
13471                "\t\t\t\t bbbbbbb);\n"
13472                "\t    },\n"
13473                "\t    p);\n"
13474                "}",
13475                Tab);
13476   EXPECT_EQ("{\n"
13477             "\t/* aaaa\n"
13478             "\t   bbbb */\n"
13479             "}",
13480             format("{\n"
13481                    "/* aaaa\n"
13482                    "   bbbb */\n"
13483                    "}",
13484                    Tab));
13485   EXPECT_EQ("{\n"
13486             "\t/*\n"
13487             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13488             "\t  bbbbbbbbbbbbb\n"
13489             "\t*/\n"
13490             "}",
13491             format("{\n"
13492                    "/*\n"
13493                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13494                    "*/\n"
13495                    "}",
13496                    Tab));
13497   EXPECT_EQ("{\n"
13498             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13499             "\t// bbbbbbbbbbbbb\n"
13500             "}",
13501             format("{\n"
13502                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13503                    "}",
13504                    Tab));
13505   EXPECT_EQ("{\n"
13506             "\t/*\n"
13507             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13508             "\t  bbbbbbbbbbbbb\n"
13509             "\t*/\n"
13510             "}",
13511             format("{\n"
13512                    "\t/*\n"
13513                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13514                    "\t*/\n"
13515                    "}",
13516                    Tab));
13517   EXPECT_EQ("{\n"
13518             "\t/*\n"
13519             "\n"
13520             "\t*/\n"
13521             "}",
13522             format("{\n"
13523                    "\t/*\n"
13524                    "\n"
13525                    "\t*/\n"
13526                    "}",
13527                    Tab));
13528   EXPECT_EQ("{\n"
13529             "\t/*\n"
13530             " asdf\n"
13531             "\t*/\n"
13532             "}",
13533             format("{\n"
13534                    "\t/*\n"
13535                    " asdf\n"
13536                    "\t*/\n"
13537                    "}",
13538                    Tab));
13539   EXPECT_EQ("/* some\n"
13540             "   comment */",
13541             format(" \t \t /* some\n"
13542                    " \t \t    comment */",
13543                    Tab));
13544   EXPECT_EQ("int a; /* some\n"
13545             "   comment */",
13546             format(" \t \t int a; /* some\n"
13547                    " \t \t    comment */",
13548                    Tab));
13549   EXPECT_EQ("int a; /* some\n"
13550             "comment */",
13551             format(" \t \t int\ta; /* some\n"
13552                    " \t \t    comment */",
13553                    Tab));
13554   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13555             "    comment */",
13556             format(" \t \t f(\"\t\t\"); /* some\n"
13557                    " \t \t    comment */",
13558                    Tab));
13559   EXPECT_EQ("{\n"
13560             "\t/*\n"
13561             "\t * Comment\n"
13562             "\t */\n"
13563             "\tint i;\n"
13564             "}",
13565             format("{\n"
13566                    "\t/*\n"
13567                    "\t * Comment\n"
13568                    "\t */\n"
13569                    "\t int i;\n"
13570                    "}",
13571                    Tab));
13572   Tab.TabWidth = 2;
13573   Tab.IndentWidth = 2;
13574   EXPECT_EQ("{\n"
13575             "\t/* aaaa\n"
13576             "\t\t bbbb */\n"
13577             "}",
13578             format("{\n"
13579                    "/* aaaa\n"
13580                    "\t bbbb */\n"
13581                    "}",
13582                    Tab));
13583   EXPECT_EQ("{\n"
13584             "\t/*\n"
13585             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13586             "\t\tbbbbbbbbbbbbb\n"
13587             "\t*/\n"
13588             "}",
13589             format("{\n"
13590                    "/*\n"
13591                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13592                    "*/\n"
13593                    "}",
13594                    Tab));
13595   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13596   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13597   Tab.TabWidth = 4;
13598   Tab.IndentWidth = 4;
13599   verifyFormat("class Assign {\n"
13600                "\tvoid f() {\n"
13601                "\t\tint         x      = 123;\n"
13602                "\t\tint         random = 4;\n"
13603                "\t\tstd::string alphabet =\n"
13604                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
13605                "\t}\n"
13606                "};",
13607                Tab);
13608 
13609   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
13610   Tab.TabWidth = 8;
13611   Tab.IndentWidth = 8;
13612   EXPECT_EQ("if (aaaaaaaa && // q\n"
13613             "    bb)         // w\n"
13614             "\t;",
13615             format("if (aaaaaaaa &&// q\n"
13616                    "bb)// w\n"
13617                    ";",
13618                    Tab));
13619   EXPECT_EQ("if (aaa && bbb) // w\n"
13620             "\t;",
13621             format("if(aaa&&bbb)// w\n"
13622                    ";",
13623                    Tab));
13624   verifyFormat("class X {\n"
13625                "\tvoid f() {\n"
13626                "\t\tsomeFunction(parameter1,\n"
13627                "\t\t             parameter2);\n"
13628                "\t}\n"
13629                "};",
13630                Tab);
13631   verifyFormat("#define A                        \\\n"
13632                "\tvoid f() {               \\\n"
13633                "\t\tsomeFunction(    \\\n"
13634                "\t\t    parameter1,  \\\n"
13635                "\t\t    parameter2); \\\n"
13636                "\t}",
13637                Tab);
13638   Tab.TabWidth = 4;
13639   Tab.IndentWidth = 8;
13640   verifyFormat("class TabWidth4Indent8 {\n"
13641                "\t\tvoid f() {\n"
13642                "\t\t\t\tsomeFunction(parameter1,\n"
13643                "\t\t\t\t             parameter2);\n"
13644                "\t\t}\n"
13645                "};",
13646                Tab);
13647   Tab.TabWidth = 4;
13648   Tab.IndentWidth = 4;
13649   verifyFormat("class TabWidth4Indent4 {\n"
13650                "\tvoid f() {\n"
13651                "\t\tsomeFunction(parameter1,\n"
13652                "\t\t             parameter2);\n"
13653                "\t}\n"
13654                "};",
13655                Tab);
13656   Tab.TabWidth = 8;
13657   Tab.IndentWidth = 4;
13658   verifyFormat("class TabWidth8Indent4 {\n"
13659                "    void f() {\n"
13660                "\tsomeFunction(parameter1,\n"
13661                "\t             parameter2);\n"
13662                "    }\n"
13663                "};",
13664                Tab);
13665   Tab.TabWidth = 8;
13666   Tab.IndentWidth = 8;
13667   EXPECT_EQ("/*\n"
13668             "              a\t\tcomment\n"
13669             "              in multiple lines\n"
13670             "       */",
13671             format("   /*\t \t \n"
13672                    " \t \t a\t\tcomment\t \t\n"
13673                    " \t \t in multiple lines\t\n"
13674                    " \t  */",
13675                    Tab));
13676   verifyFormat("{\n"
13677                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13678                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13679                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13680                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13681                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13682                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13683                "};",
13684                Tab);
13685   verifyFormat("enum AA {\n"
13686                "\ta1, // Force multiple lines\n"
13687                "\ta2,\n"
13688                "\ta3\n"
13689                "};",
13690                Tab);
13691   EXPECT_EQ("if (aaaaaaaa && // q\n"
13692             "    bb)         // w\n"
13693             "\t;",
13694             format("if (aaaaaaaa &&// q\n"
13695                    "bb)// w\n"
13696                    ";",
13697                    Tab));
13698   verifyFormat("class X {\n"
13699                "\tvoid f() {\n"
13700                "\t\tsomeFunction(parameter1,\n"
13701                "\t\t             parameter2);\n"
13702                "\t}\n"
13703                "};",
13704                Tab);
13705   verifyFormat("{\n"
13706                "\tQ(\n"
13707                "\t    {\n"
13708                "\t\t    int a;\n"
13709                "\t\t    someFunction(aaaaaaaa,\n"
13710                "\t\t                 bbbbbbb);\n"
13711                "\t    },\n"
13712                "\t    p);\n"
13713                "}",
13714                Tab);
13715   EXPECT_EQ("{\n"
13716             "\t/* aaaa\n"
13717             "\t   bbbb */\n"
13718             "}",
13719             format("{\n"
13720                    "/* aaaa\n"
13721                    "   bbbb */\n"
13722                    "}",
13723                    Tab));
13724   EXPECT_EQ("{\n"
13725             "\t/*\n"
13726             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13727             "\t  bbbbbbbbbbbbb\n"
13728             "\t*/\n"
13729             "}",
13730             format("{\n"
13731                    "/*\n"
13732                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13733                    "*/\n"
13734                    "}",
13735                    Tab));
13736   EXPECT_EQ("{\n"
13737             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13738             "\t// bbbbbbbbbbbbb\n"
13739             "}",
13740             format("{\n"
13741                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13742                    "}",
13743                    Tab));
13744   EXPECT_EQ("{\n"
13745             "\t/*\n"
13746             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13747             "\t  bbbbbbbbbbbbb\n"
13748             "\t*/\n"
13749             "}",
13750             format("{\n"
13751                    "\t/*\n"
13752                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13753                    "\t*/\n"
13754                    "}",
13755                    Tab));
13756   EXPECT_EQ("{\n"
13757             "\t/*\n"
13758             "\n"
13759             "\t*/\n"
13760             "}",
13761             format("{\n"
13762                    "\t/*\n"
13763                    "\n"
13764                    "\t*/\n"
13765                    "}",
13766                    Tab));
13767   EXPECT_EQ("{\n"
13768             "\t/*\n"
13769             " asdf\n"
13770             "\t*/\n"
13771             "}",
13772             format("{\n"
13773                    "\t/*\n"
13774                    " asdf\n"
13775                    "\t*/\n"
13776                    "}",
13777                    Tab));
13778   EXPECT_EQ("/* some\n"
13779             "   comment */",
13780             format(" \t \t /* some\n"
13781                    " \t \t    comment */",
13782                    Tab));
13783   EXPECT_EQ("int a; /* some\n"
13784             "   comment */",
13785             format(" \t \t int a; /* some\n"
13786                    " \t \t    comment */",
13787                    Tab));
13788   EXPECT_EQ("int a; /* some\n"
13789             "comment */",
13790             format(" \t \t int\ta; /* some\n"
13791                    " \t \t    comment */",
13792                    Tab));
13793   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13794             "    comment */",
13795             format(" \t \t f(\"\t\t\"); /* some\n"
13796                    " \t \t    comment */",
13797                    Tab));
13798   EXPECT_EQ("{\n"
13799             "\t/*\n"
13800             "\t * Comment\n"
13801             "\t */\n"
13802             "\tint i;\n"
13803             "}",
13804             format("{\n"
13805                    "\t/*\n"
13806                    "\t * Comment\n"
13807                    "\t */\n"
13808                    "\t int i;\n"
13809                    "}",
13810                    Tab));
13811   Tab.TabWidth = 2;
13812   Tab.IndentWidth = 2;
13813   EXPECT_EQ("{\n"
13814             "\t/* aaaa\n"
13815             "\t   bbbb */\n"
13816             "}",
13817             format("{\n"
13818                    "/* aaaa\n"
13819                    "   bbbb */\n"
13820                    "}",
13821                    Tab));
13822   EXPECT_EQ("{\n"
13823             "\t/*\n"
13824             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13825             "\t  bbbbbbbbbbbbb\n"
13826             "\t*/\n"
13827             "}",
13828             format("{\n"
13829                    "/*\n"
13830                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13831                    "*/\n"
13832                    "}",
13833                    Tab));
13834   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13835   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13836   Tab.TabWidth = 4;
13837   Tab.IndentWidth = 4;
13838   verifyFormat("class Assign {\n"
13839                "\tvoid f() {\n"
13840                "\t\tint         x      = 123;\n"
13841                "\t\tint         random = 4;\n"
13842                "\t\tstd::string alphabet =\n"
13843                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
13844                "\t}\n"
13845                "};",
13846                Tab);
13847   Tab.AlignOperands = FormatStyle::OAS_Align;
13848   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
13849                "                 cccccccccccccccccccc;",
13850                Tab);
13851   // no alignment
13852   verifyFormat("int aaaaaaaaaa =\n"
13853                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
13854                Tab);
13855   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
13856                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
13857                "                        : 333333333333333;",
13858                Tab);
13859   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
13860   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
13861   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
13862                "               + cccccccccccccccccccc;",
13863                Tab);
13864 }
13865 
13866 TEST_F(FormatTest, ZeroTabWidth) {
13867   FormatStyle Tab = getLLVMStyleWithColumns(42);
13868   Tab.IndentWidth = 8;
13869   Tab.UseTab = FormatStyle::UT_Never;
13870   Tab.TabWidth = 0;
13871   EXPECT_EQ("void a(){\n"
13872             "    // line starts with '\t'\n"
13873             "};",
13874             format("void a(){\n"
13875                    "\t// line starts with '\t'\n"
13876                    "};",
13877                    Tab));
13878 
13879   EXPECT_EQ("void a(){\n"
13880             "    // line starts with '\t'\n"
13881             "};",
13882             format("void a(){\n"
13883                    "\t\t// line starts with '\t'\n"
13884                    "};",
13885                    Tab));
13886 
13887   Tab.UseTab = FormatStyle::UT_ForIndentation;
13888   EXPECT_EQ("void a(){\n"
13889             "    // line starts with '\t'\n"
13890             "};",
13891             format("void a(){\n"
13892                    "\t// line starts with '\t'\n"
13893                    "};",
13894                    Tab));
13895 
13896   EXPECT_EQ("void a(){\n"
13897             "    // line starts with '\t'\n"
13898             "};",
13899             format("void a(){\n"
13900                    "\t\t// line starts with '\t'\n"
13901                    "};",
13902                    Tab));
13903 
13904   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13905   EXPECT_EQ("void a(){\n"
13906             "    // line starts with '\t'\n"
13907             "};",
13908             format("void a(){\n"
13909                    "\t// line starts with '\t'\n"
13910                    "};",
13911                    Tab));
13912 
13913   EXPECT_EQ("void a(){\n"
13914             "    // line starts with '\t'\n"
13915             "};",
13916             format("void a(){\n"
13917                    "\t\t// line starts with '\t'\n"
13918                    "};",
13919                    Tab));
13920 
13921   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
13922   EXPECT_EQ("void a(){\n"
13923             "    // line starts with '\t'\n"
13924             "};",
13925             format("void a(){\n"
13926                    "\t// line starts with '\t'\n"
13927                    "};",
13928                    Tab));
13929 
13930   EXPECT_EQ("void a(){\n"
13931             "    // line starts with '\t'\n"
13932             "};",
13933             format("void a(){\n"
13934                    "\t\t// line starts with '\t'\n"
13935                    "};",
13936                    Tab));
13937 
13938   Tab.UseTab = FormatStyle::UT_Always;
13939   EXPECT_EQ("void a(){\n"
13940             "// line starts with '\t'\n"
13941             "};",
13942             format("void a(){\n"
13943                    "\t// line starts with '\t'\n"
13944                    "};",
13945                    Tab));
13946 
13947   EXPECT_EQ("void a(){\n"
13948             "// line starts with '\t'\n"
13949             "};",
13950             format("void a(){\n"
13951                    "\t\t// line starts with '\t'\n"
13952                    "};",
13953                    Tab));
13954 }
13955 
13956 TEST_F(FormatTest, CalculatesOriginalColumn) {
13957   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13958             "q\"; /* some\n"
13959             "       comment */",
13960             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13961                    "q\"; /* some\n"
13962                    "       comment */",
13963                    getLLVMStyle()));
13964   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
13965             "/* some\n"
13966             "   comment */",
13967             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
13968                    " /* some\n"
13969                    "    comment */",
13970                    getLLVMStyle()));
13971   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13972             "qqq\n"
13973             "/* some\n"
13974             "   comment */",
13975             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13976                    "qqq\n"
13977                    " /* some\n"
13978                    "    comment */",
13979                    getLLVMStyle()));
13980   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13981             "wwww; /* some\n"
13982             "         comment */",
13983             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13984                    "wwww; /* some\n"
13985                    "         comment */",
13986                    getLLVMStyle()));
13987 }
13988 
13989 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
13990   FormatStyle NoSpace = getLLVMStyle();
13991   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
13992 
13993   verifyFormat("while(true)\n"
13994                "  continue;",
13995                NoSpace);
13996   verifyFormat("for(;;)\n"
13997                "  continue;",
13998                NoSpace);
13999   verifyFormat("if(true)\n"
14000                "  f();\n"
14001                "else if(true)\n"
14002                "  f();",
14003                NoSpace);
14004   verifyFormat("do {\n"
14005                "  do_something();\n"
14006                "} while(something());",
14007                NoSpace);
14008   verifyFormat("switch(x) {\n"
14009                "default:\n"
14010                "  break;\n"
14011                "}",
14012                NoSpace);
14013   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14014   verifyFormat("size_t x = sizeof(x);", NoSpace);
14015   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14016   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14017   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14018   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14019   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14020   verifyFormat("alignas(128) char a[128];", NoSpace);
14021   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14022   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14023   verifyFormat("int f() throw(Deprecated);", NoSpace);
14024   verifyFormat("typedef void (*cb)(int);", NoSpace);
14025   verifyFormat("T A::operator()();", NoSpace);
14026   verifyFormat("X A::operator++(T);", NoSpace);
14027   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14028 
14029   FormatStyle Space = getLLVMStyle();
14030   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14031 
14032   verifyFormat("int f ();", Space);
14033   verifyFormat("void f (int a, T b) {\n"
14034                "  while (true)\n"
14035                "    continue;\n"
14036                "}",
14037                Space);
14038   verifyFormat("if (true)\n"
14039                "  f ();\n"
14040                "else if (true)\n"
14041                "  f ();",
14042                Space);
14043   verifyFormat("do {\n"
14044                "  do_something ();\n"
14045                "} while (something ());",
14046                Space);
14047   verifyFormat("switch (x) {\n"
14048                "default:\n"
14049                "  break;\n"
14050                "}",
14051                Space);
14052   verifyFormat("A::A () : a (1) {}", Space);
14053   verifyFormat("void f () __attribute__ ((asdf));", Space);
14054   verifyFormat("*(&a + 1);\n"
14055                "&((&a)[1]);\n"
14056                "a[(b + c) * d];\n"
14057                "(((a + 1) * 2) + 3) * 4;",
14058                Space);
14059   verifyFormat("#define A(x) x", Space);
14060   verifyFormat("#define A (x) x", Space);
14061   verifyFormat("#if defined(x)\n"
14062                "#endif",
14063                Space);
14064   verifyFormat("auto i = std::make_unique<int> (5);", Space);
14065   verifyFormat("size_t x = sizeof (x);", Space);
14066   verifyFormat("auto f (int x) -> decltype (x);", Space);
14067   verifyFormat("auto f (int x) -> typeof (x);", Space);
14068   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
14069   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
14070   verifyFormat("int f (T x) noexcept (x.create ());", Space);
14071   verifyFormat("alignas (128) char a[128];", Space);
14072   verifyFormat("size_t x = alignof (MyType);", Space);
14073   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
14074   verifyFormat("int f () throw (Deprecated);", Space);
14075   verifyFormat("typedef void (*cb) (int);", Space);
14076   verifyFormat("T A::operator() ();", Space);
14077   verifyFormat("X A::operator++ (T);", Space);
14078   verifyFormat("auto lambda = [] () { return 0; };", Space);
14079   verifyFormat("int x = int (y);", Space);
14080 
14081   FormatStyle SomeSpace = getLLVMStyle();
14082   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
14083 
14084   verifyFormat("[]() -> float {}", SomeSpace);
14085   verifyFormat("[] (auto foo) {}", SomeSpace);
14086   verifyFormat("[foo]() -> int {}", SomeSpace);
14087   verifyFormat("int f();", SomeSpace);
14088   verifyFormat("void f (int a, T b) {\n"
14089                "  while (true)\n"
14090                "    continue;\n"
14091                "}",
14092                SomeSpace);
14093   verifyFormat("if (true)\n"
14094                "  f();\n"
14095                "else if (true)\n"
14096                "  f();",
14097                SomeSpace);
14098   verifyFormat("do {\n"
14099                "  do_something();\n"
14100                "} while (something());",
14101                SomeSpace);
14102   verifyFormat("switch (x) {\n"
14103                "default:\n"
14104                "  break;\n"
14105                "}",
14106                SomeSpace);
14107   verifyFormat("A::A() : a (1) {}", SomeSpace);
14108   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
14109   verifyFormat("*(&a + 1);\n"
14110                "&((&a)[1]);\n"
14111                "a[(b + c) * d];\n"
14112                "(((a + 1) * 2) + 3) * 4;",
14113                SomeSpace);
14114   verifyFormat("#define A(x) x", SomeSpace);
14115   verifyFormat("#define A (x) x", SomeSpace);
14116   verifyFormat("#if defined(x)\n"
14117                "#endif",
14118                SomeSpace);
14119   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
14120   verifyFormat("size_t x = sizeof (x);", SomeSpace);
14121   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
14122   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
14123   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
14124   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
14125   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
14126   verifyFormat("alignas (128) char a[128];", SomeSpace);
14127   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
14128   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14129                SomeSpace);
14130   verifyFormat("int f() throw (Deprecated);", SomeSpace);
14131   verifyFormat("typedef void (*cb) (int);", SomeSpace);
14132   verifyFormat("T A::operator()();", SomeSpace);
14133   verifyFormat("X A::operator++ (T);", SomeSpace);
14134   verifyFormat("int x = int (y);", SomeSpace);
14135   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
14136 }
14137 
14138 TEST_F(FormatTest, SpaceAfterLogicalNot) {
14139   FormatStyle Spaces = getLLVMStyle();
14140   Spaces.SpaceAfterLogicalNot = true;
14141 
14142   verifyFormat("bool x = ! y", Spaces);
14143   verifyFormat("if (! isFailure())", Spaces);
14144   verifyFormat("if (! (a && b))", Spaces);
14145   verifyFormat("\"Error!\"", Spaces);
14146   verifyFormat("! ! x", Spaces);
14147 }
14148 
14149 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
14150   FormatStyle Spaces = getLLVMStyle();
14151 
14152   Spaces.SpacesInParentheses = true;
14153   verifyFormat("do_something( ::globalVar );", Spaces);
14154   verifyFormat("call( x, y, z );", Spaces);
14155   verifyFormat("call();", Spaces);
14156   verifyFormat("std::function<void( int, int )> callback;", Spaces);
14157   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
14158                Spaces);
14159   verifyFormat("while ( (bool)1 )\n"
14160                "  continue;",
14161                Spaces);
14162   verifyFormat("for ( ;; )\n"
14163                "  continue;",
14164                Spaces);
14165   verifyFormat("if ( true )\n"
14166                "  f();\n"
14167                "else if ( true )\n"
14168                "  f();",
14169                Spaces);
14170   verifyFormat("do {\n"
14171                "  do_something( (int)i );\n"
14172                "} while ( something() );",
14173                Spaces);
14174   verifyFormat("switch ( x ) {\n"
14175                "default:\n"
14176                "  break;\n"
14177                "}",
14178                Spaces);
14179 
14180   Spaces.SpacesInParentheses = false;
14181   Spaces.SpacesInCStyleCastParentheses = true;
14182   verifyFormat("Type *A = ( Type * )P;", Spaces);
14183   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
14184   verifyFormat("x = ( int32 )y;", Spaces);
14185   verifyFormat("int a = ( int )(2.0f);", Spaces);
14186   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
14187   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
14188   verifyFormat("#define x (( int )-1)", Spaces);
14189 
14190   // Run the first set of tests again with:
14191   Spaces.SpacesInParentheses = false;
14192   Spaces.SpaceInEmptyParentheses = true;
14193   Spaces.SpacesInCStyleCastParentheses = true;
14194   verifyFormat("call(x, y, z);", Spaces);
14195   verifyFormat("call( );", Spaces);
14196   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14197   verifyFormat("while (( bool )1)\n"
14198                "  continue;",
14199                Spaces);
14200   verifyFormat("for (;;)\n"
14201                "  continue;",
14202                Spaces);
14203   verifyFormat("if (true)\n"
14204                "  f( );\n"
14205                "else if (true)\n"
14206                "  f( );",
14207                Spaces);
14208   verifyFormat("do {\n"
14209                "  do_something(( int )i);\n"
14210                "} while (something( ));",
14211                Spaces);
14212   verifyFormat("switch (x) {\n"
14213                "default:\n"
14214                "  break;\n"
14215                "}",
14216                Spaces);
14217 
14218   // Run the first set of tests again with:
14219   Spaces.SpaceAfterCStyleCast = true;
14220   verifyFormat("call(x, y, z);", Spaces);
14221   verifyFormat("call( );", Spaces);
14222   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14223   verifyFormat("while (( bool ) 1)\n"
14224                "  continue;",
14225                Spaces);
14226   verifyFormat("for (;;)\n"
14227                "  continue;",
14228                Spaces);
14229   verifyFormat("if (true)\n"
14230                "  f( );\n"
14231                "else if (true)\n"
14232                "  f( );",
14233                Spaces);
14234   verifyFormat("do {\n"
14235                "  do_something(( int ) i);\n"
14236                "} while (something( ));",
14237                Spaces);
14238   verifyFormat("switch (x) {\n"
14239                "default:\n"
14240                "  break;\n"
14241                "}",
14242                Spaces);
14243 
14244   // Run subset of tests again with:
14245   Spaces.SpacesInCStyleCastParentheses = false;
14246   Spaces.SpaceAfterCStyleCast = true;
14247   verifyFormat("while ((bool) 1)\n"
14248                "  continue;",
14249                Spaces);
14250   verifyFormat("do {\n"
14251                "  do_something((int) i);\n"
14252                "} while (something( ));",
14253                Spaces);
14254 
14255   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
14256   verifyFormat("size_t idx = (size_t) a;", Spaces);
14257   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
14258   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14259   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14260   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14261   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14262   Spaces.ColumnLimit = 80;
14263   Spaces.IndentWidth = 4;
14264   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14265   verifyFormat("void foo( ) {\n"
14266                "    size_t foo = (*(function))(\n"
14267                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14268                "BarrrrrrrrrrrrLong,\n"
14269                "        FoooooooooLooooong);\n"
14270                "}",
14271                Spaces);
14272   Spaces.SpaceAfterCStyleCast = false;
14273   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
14274   verifyFormat("size_t idx = (size_t)a;", Spaces);
14275   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
14276   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14277   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14278   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14279   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14280 
14281   verifyFormat("void foo( ) {\n"
14282                "    size_t foo = (*(function))(\n"
14283                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14284                "BarrrrrrrrrrrrLong,\n"
14285                "        FoooooooooLooooong);\n"
14286                "}",
14287                Spaces);
14288 }
14289 
14290 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
14291   verifyFormat("int a[5];");
14292   verifyFormat("a[3] += 42;");
14293 
14294   FormatStyle Spaces = getLLVMStyle();
14295   Spaces.SpacesInSquareBrackets = true;
14296   // Not lambdas.
14297   verifyFormat("int a[ 5 ];", Spaces);
14298   verifyFormat("a[ 3 ] += 42;", Spaces);
14299   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
14300   verifyFormat("double &operator[](int i) { return 0; }\n"
14301                "int i;",
14302                Spaces);
14303   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
14304   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
14305   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
14306   // Lambdas.
14307   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
14308   verifyFormat("return [ i, args... ] {};", Spaces);
14309   verifyFormat("int foo = [ &bar ]() {};", Spaces);
14310   verifyFormat("int foo = [ = ]() {};", Spaces);
14311   verifyFormat("int foo = [ & ]() {};", Spaces);
14312   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
14313   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
14314 }
14315 
14316 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
14317   FormatStyle NoSpaceStyle = getLLVMStyle();
14318   verifyFormat("int a[5];", NoSpaceStyle);
14319   verifyFormat("a[3] += 42;", NoSpaceStyle);
14320 
14321   verifyFormat("int a[1];", NoSpaceStyle);
14322   verifyFormat("int 1 [a];", NoSpaceStyle);
14323   verifyFormat("int a[1][2];", NoSpaceStyle);
14324   verifyFormat("a[7] = 5;", NoSpaceStyle);
14325   verifyFormat("int a = (f())[23];", NoSpaceStyle);
14326   verifyFormat("f([] {})", NoSpaceStyle);
14327 
14328   FormatStyle Space = getLLVMStyle();
14329   Space.SpaceBeforeSquareBrackets = true;
14330   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
14331   verifyFormat("return [i, args...] {};", Space);
14332 
14333   verifyFormat("int a [5];", Space);
14334   verifyFormat("a [3] += 42;", Space);
14335   verifyFormat("constexpr char hello []{\"hello\"};", Space);
14336   verifyFormat("double &operator[](int i) { return 0; }\n"
14337                "int i;",
14338                Space);
14339   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
14340   verifyFormat("int i = a [a][a]->f();", Space);
14341   verifyFormat("int i = (*b) [a]->f();", Space);
14342 
14343   verifyFormat("int a [1];", Space);
14344   verifyFormat("int 1 [a];", Space);
14345   verifyFormat("int a [1][2];", Space);
14346   verifyFormat("a [7] = 5;", Space);
14347   verifyFormat("int a = (f()) [23];", Space);
14348   verifyFormat("f([] {})", Space);
14349 }
14350 
14351 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
14352   verifyFormat("int a = 5;");
14353   verifyFormat("a += 42;");
14354   verifyFormat("a or_eq 8;");
14355 
14356   FormatStyle Spaces = getLLVMStyle();
14357   Spaces.SpaceBeforeAssignmentOperators = false;
14358   verifyFormat("int a= 5;", Spaces);
14359   verifyFormat("a+= 42;", Spaces);
14360   verifyFormat("a or_eq 8;", Spaces);
14361 }
14362 
14363 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
14364   verifyFormat("class Foo : public Bar {};");
14365   verifyFormat("Foo::Foo() : foo(1) {}");
14366   verifyFormat("for (auto a : b) {\n}");
14367   verifyFormat("int x = a ? b : c;");
14368   verifyFormat("{\n"
14369                "label0:\n"
14370                "  int x = 0;\n"
14371                "}");
14372   verifyFormat("switch (x) {\n"
14373                "case 1:\n"
14374                "default:\n"
14375                "}");
14376   verifyFormat("switch (allBraces) {\n"
14377                "case 1: {\n"
14378                "  break;\n"
14379                "}\n"
14380                "case 2: {\n"
14381                "  [[fallthrough]];\n"
14382                "}\n"
14383                "default: {\n"
14384                "  break;\n"
14385                "}\n"
14386                "}");
14387 
14388   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
14389   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
14390   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
14391   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
14392   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
14393   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
14394   verifyFormat("{\n"
14395                "label1:\n"
14396                "  int x = 0;\n"
14397                "}",
14398                CtorInitializerStyle);
14399   verifyFormat("switch (x) {\n"
14400                "case 1:\n"
14401                "default:\n"
14402                "}",
14403                CtorInitializerStyle);
14404   verifyFormat("switch (allBraces) {\n"
14405                "case 1: {\n"
14406                "  break;\n"
14407                "}\n"
14408                "case 2: {\n"
14409                "  [[fallthrough]];\n"
14410                "}\n"
14411                "default: {\n"
14412                "  break;\n"
14413                "}\n"
14414                "}",
14415                CtorInitializerStyle);
14416   CtorInitializerStyle.BreakConstructorInitializers =
14417       FormatStyle::BCIS_AfterColon;
14418   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
14419                "    aaaaaaaaaaaaaaaa(1),\n"
14420                "    bbbbbbbbbbbbbbbb(2) {}",
14421                CtorInitializerStyle);
14422   CtorInitializerStyle.BreakConstructorInitializers =
14423       FormatStyle::BCIS_BeforeComma;
14424   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14425                "    : aaaaaaaaaaaaaaaa(1)\n"
14426                "    , bbbbbbbbbbbbbbbb(2) {}",
14427                CtorInitializerStyle);
14428   CtorInitializerStyle.BreakConstructorInitializers =
14429       FormatStyle::BCIS_BeforeColon;
14430   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14431                "    : aaaaaaaaaaaaaaaa(1),\n"
14432                "      bbbbbbbbbbbbbbbb(2) {}",
14433                CtorInitializerStyle);
14434   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
14435   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14436                ": aaaaaaaaaaaaaaaa(1),\n"
14437                "  bbbbbbbbbbbbbbbb(2) {}",
14438                CtorInitializerStyle);
14439 
14440   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
14441   InheritanceStyle.SpaceBeforeInheritanceColon = false;
14442   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
14443   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
14444   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
14445   verifyFormat("int x = a ? b : c;", InheritanceStyle);
14446   verifyFormat("{\n"
14447                "label2:\n"
14448                "  int x = 0;\n"
14449                "}",
14450                InheritanceStyle);
14451   verifyFormat("switch (x) {\n"
14452                "case 1:\n"
14453                "default:\n"
14454                "}",
14455                InheritanceStyle);
14456   verifyFormat("switch (allBraces) {\n"
14457                "case 1: {\n"
14458                "  break;\n"
14459                "}\n"
14460                "case 2: {\n"
14461                "  [[fallthrough]];\n"
14462                "}\n"
14463                "default: {\n"
14464                "  break;\n"
14465                "}\n"
14466                "}",
14467                InheritanceStyle);
14468   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
14469   verifyFormat("class Foooooooooooooooooooooo\n"
14470                "    : public aaaaaaaaaaaaaaaaaa,\n"
14471                "      public bbbbbbbbbbbbbbbbbb {\n"
14472                "}",
14473                InheritanceStyle);
14474   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
14475   verifyFormat("class Foooooooooooooooooooooo:\n"
14476                "    public aaaaaaaaaaaaaaaaaa,\n"
14477                "    public bbbbbbbbbbbbbbbbbb {\n"
14478                "}",
14479                InheritanceStyle);
14480   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
14481   verifyFormat("class Foooooooooooooooooooooo\n"
14482                "    : public aaaaaaaaaaaaaaaaaa\n"
14483                "    , public bbbbbbbbbbbbbbbbbb {\n"
14484                "}",
14485                InheritanceStyle);
14486   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
14487   verifyFormat("class Foooooooooooooooooooooo\n"
14488                "    : public aaaaaaaaaaaaaaaaaa,\n"
14489                "      public bbbbbbbbbbbbbbbbbb {\n"
14490                "}",
14491                InheritanceStyle);
14492   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
14493   verifyFormat("class Foooooooooooooooooooooo\n"
14494                ": public aaaaaaaaaaaaaaaaaa,\n"
14495                "  public bbbbbbbbbbbbbbbbbb {}",
14496                InheritanceStyle);
14497 
14498   FormatStyle ForLoopStyle = getLLVMStyle();
14499   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
14500   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
14501   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
14502   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
14503   verifyFormat("int x = a ? b : c;", ForLoopStyle);
14504   verifyFormat("{\n"
14505                "label2:\n"
14506                "  int x = 0;\n"
14507                "}",
14508                ForLoopStyle);
14509   verifyFormat("switch (x) {\n"
14510                "case 1:\n"
14511                "default:\n"
14512                "}",
14513                ForLoopStyle);
14514   verifyFormat("switch (allBraces) {\n"
14515                "case 1: {\n"
14516                "  break;\n"
14517                "}\n"
14518                "case 2: {\n"
14519                "  [[fallthrough]];\n"
14520                "}\n"
14521                "default: {\n"
14522                "  break;\n"
14523                "}\n"
14524                "}",
14525                ForLoopStyle);
14526 
14527   FormatStyle CaseStyle = getLLVMStyle();
14528   CaseStyle.SpaceBeforeCaseColon = true;
14529   verifyFormat("class Foo : public Bar {};", CaseStyle);
14530   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
14531   verifyFormat("for (auto a : b) {\n}", CaseStyle);
14532   verifyFormat("int x = a ? b : c;", CaseStyle);
14533   verifyFormat("switch (x) {\n"
14534                "case 1 :\n"
14535                "default :\n"
14536                "}",
14537                CaseStyle);
14538   verifyFormat("switch (allBraces) {\n"
14539                "case 1 : {\n"
14540                "  break;\n"
14541                "}\n"
14542                "case 2 : {\n"
14543                "  [[fallthrough]];\n"
14544                "}\n"
14545                "default : {\n"
14546                "  break;\n"
14547                "}\n"
14548                "}",
14549                CaseStyle);
14550 
14551   FormatStyle NoSpaceStyle = getLLVMStyle();
14552   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
14553   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
14554   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
14555   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
14556   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
14557   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
14558   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
14559   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
14560   verifyFormat("{\n"
14561                "label3:\n"
14562                "  int x = 0;\n"
14563                "}",
14564                NoSpaceStyle);
14565   verifyFormat("switch (x) {\n"
14566                "case 1:\n"
14567                "default:\n"
14568                "}",
14569                NoSpaceStyle);
14570   verifyFormat("switch (allBraces) {\n"
14571                "case 1: {\n"
14572                "  break;\n"
14573                "}\n"
14574                "case 2: {\n"
14575                "  [[fallthrough]];\n"
14576                "}\n"
14577                "default: {\n"
14578                "  break;\n"
14579                "}\n"
14580                "}",
14581                NoSpaceStyle);
14582 
14583   FormatStyle InvertedSpaceStyle = getLLVMStyle();
14584   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
14585   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
14586   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
14587   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
14588   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
14589   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
14590   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
14591   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
14592   verifyFormat("{\n"
14593                "label3:\n"
14594                "  int x = 0;\n"
14595                "}",
14596                InvertedSpaceStyle);
14597   verifyFormat("switch (x) {\n"
14598                "case 1 :\n"
14599                "case 2 : {\n"
14600                "  break;\n"
14601                "}\n"
14602                "default :\n"
14603                "  break;\n"
14604                "}",
14605                InvertedSpaceStyle);
14606   verifyFormat("switch (allBraces) {\n"
14607                "case 1 : {\n"
14608                "  break;\n"
14609                "}\n"
14610                "case 2 : {\n"
14611                "  [[fallthrough]];\n"
14612                "}\n"
14613                "default : {\n"
14614                "  break;\n"
14615                "}\n"
14616                "}",
14617                InvertedSpaceStyle);
14618 }
14619 
14620 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
14621   FormatStyle Style = getLLVMStyle();
14622 
14623   Style.PointerAlignment = FormatStyle::PAS_Left;
14624   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
14625   verifyFormat("void* const* x = NULL;", Style);
14626 
14627 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
14628   do {                                                                         \
14629     Style.PointerAlignment = FormatStyle::Pointers;                            \
14630     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
14631     verifyFormat(Code, Style);                                                 \
14632   } while (false)
14633 
14634   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
14635   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
14636   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
14637 
14638   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
14639   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
14640   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
14641 
14642   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
14643   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
14644   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
14645 
14646   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
14647   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
14648   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
14649 
14650   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
14651   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
14652                         SAPQ_Default);
14653   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
14654                         SAPQ_Default);
14655 
14656   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
14657   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
14658                         SAPQ_Before);
14659   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
14660                         SAPQ_Before);
14661 
14662   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
14663   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
14664   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
14665                         SAPQ_After);
14666 
14667   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
14668   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
14669   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
14670 
14671 #undef verifyQualifierSpaces
14672 
14673   FormatStyle Spaces = getLLVMStyle();
14674   Spaces.AttributeMacros.push_back("qualified");
14675   Spaces.PointerAlignment = FormatStyle::PAS_Right;
14676   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
14677   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
14678   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
14679   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
14680   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
14681   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14682   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
14683   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
14684   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
14685   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
14686   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
14687   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14688 
14689   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
14690   Spaces.PointerAlignment = FormatStyle::PAS_Left;
14691   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
14692   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
14693   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
14694   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
14695   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
14696   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14697   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
14698   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
14699   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
14700   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
14701   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
14702   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
14703   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14704 
14705   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
14706   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
14707   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
14708   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
14709   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
14710   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
14711   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
14712   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14713 }
14714 
14715 TEST_F(FormatTest, AlignConsecutiveMacros) {
14716   FormatStyle Style = getLLVMStyle();
14717   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14718   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14719   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
14720 
14721   verifyFormat("#define a 3\n"
14722                "#define bbbb 4\n"
14723                "#define ccc (5)",
14724                Style);
14725 
14726   verifyFormat("#define f(x) (x * x)\n"
14727                "#define fff(x, y, z) (x * y + z)\n"
14728                "#define ffff(x, y) (x - y)",
14729                Style);
14730 
14731   verifyFormat("#define foo(x, y) (x + y)\n"
14732                "#define bar (5, 6)(2 + 2)",
14733                Style);
14734 
14735   verifyFormat("#define a 3\n"
14736                "#define bbbb 4\n"
14737                "#define ccc (5)\n"
14738                "#define f(x) (x * x)\n"
14739                "#define fff(x, y, z) (x * y + z)\n"
14740                "#define ffff(x, y) (x - y)",
14741                Style);
14742 
14743   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14744   verifyFormat("#define a    3\n"
14745                "#define bbbb 4\n"
14746                "#define ccc  (5)",
14747                Style);
14748 
14749   verifyFormat("#define f(x)         (x * x)\n"
14750                "#define fff(x, y, z) (x * y + z)\n"
14751                "#define ffff(x, y)   (x - y)",
14752                Style);
14753 
14754   verifyFormat("#define foo(x, y) (x + y)\n"
14755                "#define bar       (5, 6)(2 + 2)",
14756                Style);
14757 
14758   verifyFormat("#define a            3\n"
14759                "#define bbbb         4\n"
14760                "#define ccc          (5)\n"
14761                "#define f(x)         (x * x)\n"
14762                "#define fff(x, y, z) (x * y + z)\n"
14763                "#define ffff(x, y)   (x - y)",
14764                Style);
14765 
14766   verifyFormat("#define a         5\n"
14767                "#define foo(x, y) (x + y)\n"
14768                "#define CCC       (6)\n"
14769                "auto lambda = []() {\n"
14770                "  auto  ii = 0;\n"
14771                "  float j  = 0;\n"
14772                "  return 0;\n"
14773                "};\n"
14774                "int   i  = 0;\n"
14775                "float i2 = 0;\n"
14776                "auto  v  = type{\n"
14777                "    i = 1,   //\n"
14778                "    (i = 2), //\n"
14779                "    i = 3    //\n"
14780                "};",
14781                Style);
14782 
14783   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
14784   Style.ColumnLimit = 20;
14785 
14786   verifyFormat("#define a          \\\n"
14787                "  \"aabbbbbbbbbbbb\"\n"
14788                "#define D          \\\n"
14789                "  \"aabbbbbbbbbbbb\" \\\n"
14790                "  \"ccddeeeeeeeee\"\n"
14791                "#define B          \\\n"
14792                "  \"QQQQQQQQQQQQQ\"  \\\n"
14793                "  \"FFFFFFFFFFFFF\"  \\\n"
14794                "  \"LLLLLLLL\"\n",
14795                Style);
14796 
14797   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14798   verifyFormat("#define a          \\\n"
14799                "  \"aabbbbbbbbbbbb\"\n"
14800                "#define D          \\\n"
14801                "  \"aabbbbbbbbbbbb\" \\\n"
14802                "  \"ccddeeeeeeeee\"\n"
14803                "#define B          \\\n"
14804                "  \"QQQQQQQQQQQQQ\"  \\\n"
14805                "  \"FFFFFFFFFFFFF\"  \\\n"
14806                "  \"LLLLLLLL\"\n",
14807                Style);
14808 
14809   // Test across comments
14810   Style.MaxEmptyLinesToKeep = 10;
14811   Style.ReflowComments = false;
14812   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
14813   EXPECT_EQ("#define a    3\n"
14814             "// line comment\n"
14815             "#define bbbb 4\n"
14816             "#define ccc  (5)",
14817             format("#define a 3\n"
14818                    "// line comment\n"
14819                    "#define bbbb 4\n"
14820                    "#define ccc (5)",
14821                    Style));
14822 
14823   EXPECT_EQ("#define a    3\n"
14824             "/* block comment */\n"
14825             "#define bbbb 4\n"
14826             "#define ccc  (5)",
14827             format("#define a  3\n"
14828                    "/* block comment */\n"
14829                    "#define bbbb 4\n"
14830                    "#define ccc (5)",
14831                    Style));
14832 
14833   EXPECT_EQ("#define a    3\n"
14834             "/* multi-line *\n"
14835             " * block comment */\n"
14836             "#define bbbb 4\n"
14837             "#define ccc  (5)",
14838             format("#define a 3\n"
14839                    "/* multi-line *\n"
14840                    " * block comment */\n"
14841                    "#define bbbb 4\n"
14842                    "#define ccc (5)",
14843                    Style));
14844 
14845   EXPECT_EQ("#define a    3\n"
14846             "// multi-line line comment\n"
14847             "//\n"
14848             "#define bbbb 4\n"
14849             "#define ccc  (5)",
14850             format("#define a  3\n"
14851                    "// multi-line line comment\n"
14852                    "//\n"
14853                    "#define bbbb 4\n"
14854                    "#define ccc (5)",
14855                    Style));
14856 
14857   EXPECT_EQ("#define a 3\n"
14858             "// empty lines still break.\n"
14859             "\n"
14860             "#define bbbb 4\n"
14861             "#define ccc  (5)",
14862             format("#define a     3\n"
14863                    "// empty lines still break.\n"
14864                    "\n"
14865                    "#define bbbb     4\n"
14866                    "#define ccc  (5)",
14867                    Style));
14868 
14869   // Test across empty lines
14870   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
14871   EXPECT_EQ("#define a    3\n"
14872             "\n"
14873             "#define bbbb 4\n"
14874             "#define ccc  (5)",
14875             format("#define a 3\n"
14876                    "\n"
14877                    "#define bbbb 4\n"
14878                    "#define ccc (5)",
14879                    Style));
14880 
14881   EXPECT_EQ("#define a    3\n"
14882             "\n"
14883             "\n"
14884             "\n"
14885             "#define bbbb 4\n"
14886             "#define ccc  (5)",
14887             format("#define a        3\n"
14888                    "\n"
14889                    "\n"
14890                    "\n"
14891                    "#define bbbb 4\n"
14892                    "#define ccc (5)",
14893                    Style));
14894 
14895   EXPECT_EQ("#define a 3\n"
14896             "// comments should break alignment\n"
14897             "//\n"
14898             "#define bbbb 4\n"
14899             "#define ccc  (5)",
14900             format("#define a        3\n"
14901                    "// comments should break alignment\n"
14902                    "//\n"
14903                    "#define bbbb 4\n"
14904                    "#define ccc (5)",
14905                    Style));
14906 
14907   // Test across empty lines and comments
14908   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
14909   verifyFormat("#define a    3\n"
14910                "\n"
14911                "// line comment\n"
14912                "#define bbbb 4\n"
14913                "#define ccc  (5)",
14914                Style);
14915 
14916   EXPECT_EQ("#define a    3\n"
14917             "\n"
14918             "\n"
14919             "/* multi-line *\n"
14920             " * block comment */\n"
14921             "\n"
14922             "\n"
14923             "#define bbbb 4\n"
14924             "#define ccc  (5)",
14925             format("#define a 3\n"
14926                    "\n"
14927                    "\n"
14928                    "/* multi-line *\n"
14929                    " * block comment */\n"
14930                    "\n"
14931                    "\n"
14932                    "#define bbbb 4\n"
14933                    "#define ccc (5)",
14934                    Style));
14935 
14936   EXPECT_EQ("#define a    3\n"
14937             "\n"
14938             "\n"
14939             "/* multi-line *\n"
14940             " * block comment */\n"
14941             "\n"
14942             "\n"
14943             "#define bbbb 4\n"
14944             "#define ccc  (5)",
14945             format("#define a 3\n"
14946                    "\n"
14947                    "\n"
14948                    "/* multi-line *\n"
14949                    " * block comment */\n"
14950                    "\n"
14951                    "\n"
14952                    "#define bbbb 4\n"
14953                    "#define ccc       (5)",
14954                    Style));
14955 }
14956 
14957 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
14958   FormatStyle Alignment = getLLVMStyle();
14959   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14960   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
14961 
14962   Alignment.MaxEmptyLinesToKeep = 10;
14963   /* Test alignment across empty lines */
14964   EXPECT_EQ("int a           = 5;\n"
14965             "\n"
14966             "int oneTwoThree = 123;",
14967             format("int a       = 5;\n"
14968                    "\n"
14969                    "int oneTwoThree= 123;",
14970                    Alignment));
14971   EXPECT_EQ("int a           = 5;\n"
14972             "int one         = 1;\n"
14973             "\n"
14974             "int oneTwoThree = 123;",
14975             format("int a = 5;\n"
14976                    "int one = 1;\n"
14977                    "\n"
14978                    "int oneTwoThree = 123;",
14979                    Alignment));
14980   EXPECT_EQ("int a           = 5;\n"
14981             "int one         = 1;\n"
14982             "\n"
14983             "int oneTwoThree = 123;\n"
14984             "int oneTwo      = 12;",
14985             format("int a = 5;\n"
14986                    "int one = 1;\n"
14987                    "\n"
14988                    "int oneTwoThree = 123;\n"
14989                    "int oneTwo = 12;",
14990                    Alignment));
14991 
14992   /* Test across comments */
14993   EXPECT_EQ("int a = 5;\n"
14994             "/* block comment */\n"
14995             "int oneTwoThree = 123;",
14996             format("int a = 5;\n"
14997                    "/* block comment */\n"
14998                    "int oneTwoThree=123;",
14999                    Alignment));
15000 
15001   EXPECT_EQ("int a = 5;\n"
15002             "// line comment\n"
15003             "int oneTwoThree = 123;",
15004             format("int a = 5;\n"
15005                    "// line comment\n"
15006                    "int oneTwoThree=123;",
15007                    Alignment));
15008 
15009   /* Test across comments and newlines */
15010   EXPECT_EQ("int a = 5;\n"
15011             "\n"
15012             "/* block comment */\n"
15013             "int oneTwoThree = 123;",
15014             format("int a = 5;\n"
15015                    "\n"
15016                    "/* block comment */\n"
15017                    "int oneTwoThree=123;",
15018                    Alignment));
15019 
15020   EXPECT_EQ("int a = 5;\n"
15021             "\n"
15022             "// line comment\n"
15023             "int oneTwoThree = 123;",
15024             format("int a = 5;\n"
15025                    "\n"
15026                    "// line comment\n"
15027                    "int oneTwoThree=123;",
15028                    Alignment));
15029 }
15030 
15031 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
15032   FormatStyle Alignment = getLLVMStyle();
15033   Alignment.AlignConsecutiveDeclarations =
15034       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15035   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15036 
15037   Alignment.MaxEmptyLinesToKeep = 10;
15038   /* Test alignment across empty lines */
15039   EXPECT_EQ("int         a = 5;\n"
15040             "\n"
15041             "float const oneTwoThree = 123;",
15042             format("int a = 5;\n"
15043                    "\n"
15044                    "float const oneTwoThree = 123;",
15045                    Alignment));
15046   EXPECT_EQ("int         a = 5;\n"
15047             "float const one = 1;\n"
15048             "\n"
15049             "int         oneTwoThree = 123;",
15050             format("int a = 5;\n"
15051                    "float const one = 1;\n"
15052                    "\n"
15053                    "int oneTwoThree = 123;",
15054                    Alignment));
15055 
15056   /* Test across comments */
15057   EXPECT_EQ("float const a = 5;\n"
15058             "/* block comment */\n"
15059             "int         oneTwoThree = 123;",
15060             format("float const a = 5;\n"
15061                    "/* block comment */\n"
15062                    "int oneTwoThree=123;",
15063                    Alignment));
15064 
15065   EXPECT_EQ("float const a = 5;\n"
15066             "// line comment\n"
15067             "int         oneTwoThree = 123;",
15068             format("float const a = 5;\n"
15069                    "// line comment\n"
15070                    "int oneTwoThree=123;",
15071                    Alignment));
15072 
15073   /* Test across comments and newlines */
15074   EXPECT_EQ("float const a = 5;\n"
15075             "\n"
15076             "/* block comment */\n"
15077             "int         oneTwoThree = 123;",
15078             format("float const a = 5;\n"
15079                    "\n"
15080                    "/* block comment */\n"
15081                    "int         oneTwoThree=123;",
15082                    Alignment));
15083 
15084   EXPECT_EQ("float const a = 5;\n"
15085             "\n"
15086             "// line comment\n"
15087             "int         oneTwoThree = 123;",
15088             format("float const a = 5;\n"
15089                    "\n"
15090                    "// line comment\n"
15091                    "int oneTwoThree=123;",
15092                    Alignment));
15093 }
15094 
15095 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
15096   FormatStyle Alignment = getLLVMStyle();
15097   Alignment.AlignConsecutiveBitFields =
15098       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15099 
15100   Alignment.MaxEmptyLinesToKeep = 10;
15101   /* Test alignment across empty lines */
15102   EXPECT_EQ("int a            : 5;\n"
15103             "\n"
15104             "int longbitfield : 6;",
15105             format("int a : 5;\n"
15106                    "\n"
15107                    "int longbitfield : 6;",
15108                    Alignment));
15109   EXPECT_EQ("int a            : 5;\n"
15110             "int one          : 1;\n"
15111             "\n"
15112             "int longbitfield : 6;",
15113             format("int a : 5;\n"
15114                    "int one : 1;\n"
15115                    "\n"
15116                    "int longbitfield : 6;",
15117                    Alignment));
15118 
15119   /* Test across comments */
15120   EXPECT_EQ("int a            : 5;\n"
15121             "/* block comment */\n"
15122             "int longbitfield : 6;",
15123             format("int a : 5;\n"
15124                    "/* block comment */\n"
15125                    "int longbitfield : 6;",
15126                    Alignment));
15127   EXPECT_EQ("int a            : 5;\n"
15128             "int one          : 1;\n"
15129             "// line comment\n"
15130             "int longbitfield : 6;",
15131             format("int a : 5;\n"
15132                    "int one : 1;\n"
15133                    "// line comment\n"
15134                    "int longbitfield : 6;",
15135                    Alignment));
15136 
15137   /* Test across comments and newlines */
15138   EXPECT_EQ("int a            : 5;\n"
15139             "/* block comment */\n"
15140             "\n"
15141             "int longbitfield : 6;",
15142             format("int a : 5;\n"
15143                    "/* block comment */\n"
15144                    "\n"
15145                    "int longbitfield : 6;",
15146                    Alignment));
15147   EXPECT_EQ("int a            : 5;\n"
15148             "int one          : 1;\n"
15149             "\n"
15150             "// line comment\n"
15151             "\n"
15152             "int longbitfield : 6;",
15153             format("int a : 5;\n"
15154                    "int one : 1;\n"
15155                    "\n"
15156                    "// line comment \n"
15157                    "\n"
15158                    "int longbitfield : 6;",
15159                    Alignment));
15160 }
15161 
15162 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
15163   FormatStyle Alignment = getLLVMStyle();
15164   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15165   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
15166 
15167   Alignment.MaxEmptyLinesToKeep = 10;
15168   /* Test alignment across empty lines */
15169   EXPECT_EQ("int a = 5;\n"
15170             "\n"
15171             "int oneTwoThree = 123;",
15172             format("int a       = 5;\n"
15173                    "\n"
15174                    "int oneTwoThree= 123;",
15175                    Alignment));
15176   EXPECT_EQ("int a   = 5;\n"
15177             "int one = 1;\n"
15178             "\n"
15179             "int oneTwoThree = 123;",
15180             format("int a = 5;\n"
15181                    "int one = 1;\n"
15182                    "\n"
15183                    "int oneTwoThree = 123;",
15184                    Alignment));
15185 
15186   /* Test across comments */
15187   EXPECT_EQ("int a           = 5;\n"
15188             "/* block comment */\n"
15189             "int oneTwoThree = 123;",
15190             format("int a = 5;\n"
15191                    "/* block comment */\n"
15192                    "int oneTwoThree=123;",
15193                    Alignment));
15194 
15195   EXPECT_EQ("int a           = 5;\n"
15196             "// line comment\n"
15197             "int oneTwoThree = 123;",
15198             format("int a = 5;\n"
15199                    "// line comment\n"
15200                    "int oneTwoThree=123;",
15201                    Alignment));
15202 
15203   EXPECT_EQ("int a           = 5;\n"
15204             "/*\n"
15205             " * multi-line block comment\n"
15206             " */\n"
15207             "int oneTwoThree = 123;",
15208             format("int a = 5;\n"
15209                    "/*\n"
15210                    " * multi-line block comment\n"
15211                    " */\n"
15212                    "int oneTwoThree=123;",
15213                    Alignment));
15214 
15215   EXPECT_EQ("int a           = 5;\n"
15216             "//\n"
15217             "// multi-line line comment\n"
15218             "//\n"
15219             "int oneTwoThree = 123;",
15220             format("int a = 5;\n"
15221                    "//\n"
15222                    "// multi-line line comment\n"
15223                    "//\n"
15224                    "int oneTwoThree=123;",
15225                    Alignment));
15226 
15227   /* Test across comments and newlines */
15228   EXPECT_EQ("int a = 5;\n"
15229             "\n"
15230             "/* block comment */\n"
15231             "int oneTwoThree = 123;",
15232             format("int a = 5;\n"
15233                    "\n"
15234                    "/* block comment */\n"
15235                    "int oneTwoThree=123;",
15236                    Alignment));
15237 
15238   EXPECT_EQ("int a = 5;\n"
15239             "\n"
15240             "// line comment\n"
15241             "int oneTwoThree = 123;",
15242             format("int a = 5;\n"
15243                    "\n"
15244                    "// line comment\n"
15245                    "int oneTwoThree=123;",
15246                    Alignment));
15247 }
15248 
15249 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
15250   FormatStyle Alignment = getLLVMStyle();
15251   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15252   Alignment.AlignConsecutiveAssignments =
15253       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15254   verifyFormat("int a           = 5;\n"
15255                "int oneTwoThree = 123;",
15256                Alignment);
15257   verifyFormat("int a           = method();\n"
15258                "int oneTwoThree = 133;",
15259                Alignment);
15260   verifyFormat("a &= 5;\n"
15261                "bcd *= 5;\n"
15262                "ghtyf += 5;\n"
15263                "dvfvdb -= 5;\n"
15264                "a /= 5;\n"
15265                "vdsvsv %= 5;\n"
15266                "sfdbddfbdfbb ^= 5;\n"
15267                "dvsdsv |= 5;\n"
15268                "int dsvvdvsdvvv = 123;",
15269                Alignment);
15270   verifyFormat("int i = 1, j = 10;\n"
15271                "something = 2000;",
15272                Alignment);
15273   verifyFormat("something = 2000;\n"
15274                "int i = 1, j = 10;\n",
15275                Alignment);
15276   verifyFormat("something = 2000;\n"
15277                "another   = 911;\n"
15278                "int i = 1, j = 10;\n"
15279                "oneMore = 1;\n"
15280                "i       = 2;",
15281                Alignment);
15282   verifyFormat("int a   = 5;\n"
15283                "int one = 1;\n"
15284                "method();\n"
15285                "int oneTwoThree = 123;\n"
15286                "int oneTwo      = 12;",
15287                Alignment);
15288   verifyFormat("int oneTwoThree = 123;\n"
15289                "int oneTwo      = 12;\n"
15290                "method();\n",
15291                Alignment);
15292   verifyFormat("int oneTwoThree = 123; // comment\n"
15293                "int oneTwo      = 12;  // comment",
15294                Alignment);
15295 
15296   // Bug 25167
15297   /* Uncomment when fixed
15298     verifyFormat("#if A\n"
15299                  "#else\n"
15300                  "int aaaaaaaa = 12;\n"
15301                  "#endif\n"
15302                  "#if B\n"
15303                  "#else\n"
15304                  "int a = 12;\n"
15305                  "#endif\n",
15306                  Alignment);
15307     verifyFormat("enum foo {\n"
15308                  "#if A\n"
15309                  "#else\n"
15310                  "  aaaaaaaa = 12;\n"
15311                  "#endif\n"
15312                  "#if B\n"
15313                  "#else\n"
15314                  "  a = 12;\n"
15315                  "#endif\n"
15316                  "};\n",
15317                  Alignment);
15318   */
15319 
15320   Alignment.MaxEmptyLinesToKeep = 10;
15321   /* Test alignment across empty lines */
15322   EXPECT_EQ("int a           = 5;\n"
15323             "\n"
15324             "int oneTwoThree = 123;",
15325             format("int a       = 5;\n"
15326                    "\n"
15327                    "int oneTwoThree= 123;",
15328                    Alignment));
15329   EXPECT_EQ("int a           = 5;\n"
15330             "int one         = 1;\n"
15331             "\n"
15332             "int oneTwoThree = 123;",
15333             format("int a = 5;\n"
15334                    "int one = 1;\n"
15335                    "\n"
15336                    "int oneTwoThree = 123;",
15337                    Alignment));
15338   EXPECT_EQ("int a           = 5;\n"
15339             "int one         = 1;\n"
15340             "\n"
15341             "int oneTwoThree = 123;\n"
15342             "int oneTwo      = 12;",
15343             format("int a = 5;\n"
15344                    "int one = 1;\n"
15345                    "\n"
15346                    "int oneTwoThree = 123;\n"
15347                    "int oneTwo = 12;",
15348                    Alignment));
15349 
15350   /* Test across comments */
15351   EXPECT_EQ("int a           = 5;\n"
15352             "/* block comment */\n"
15353             "int oneTwoThree = 123;",
15354             format("int a = 5;\n"
15355                    "/* block comment */\n"
15356                    "int oneTwoThree=123;",
15357                    Alignment));
15358 
15359   EXPECT_EQ("int a           = 5;\n"
15360             "// line comment\n"
15361             "int oneTwoThree = 123;",
15362             format("int a = 5;\n"
15363                    "// line comment\n"
15364                    "int oneTwoThree=123;",
15365                    Alignment));
15366 
15367   /* Test across comments and newlines */
15368   EXPECT_EQ("int a           = 5;\n"
15369             "\n"
15370             "/* block comment */\n"
15371             "int oneTwoThree = 123;",
15372             format("int a = 5;\n"
15373                    "\n"
15374                    "/* block comment */\n"
15375                    "int oneTwoThree=123;",
15376                    Alignment));
15377 
15378   EXPECT_EQ("int a           = 5;\n"
15379             "\n"
15380             "// line comment\n"
15381             "int oneTwoThree = 123;",
15382             format("int a = 5;\n"
15383                    "\n"
15384                    "// line comment\n"
15385                    "int oneTwoThree=123;",
15386                    Alignment));
15387 
15388   EXPECT_EQ("int a           = 5;\n"
15389             "//\n"
15390             "// multi-line line comment\n"
15391             "//\n"
15392             "int oneTwoThree = 123;",
15393             format("int a = 5;\n"
15394                    "//\n"
15395                    "// multi-line line comment\n"
15396                    "//\n"
15397                    "int oneTwoThree=123;",
15398                    Alignment));
15399 
15400   EXPECT_EQ("int a           = 5;\n"
15401             "/*\n"
15402             " *  multi-line block comment\n"
15403             " */\n"
15404             "int oneTwoThree = 123;",
15405             format("int a = 5;\n"
15406                    "/*\n"
15407                    " *  multi-line block comment\n"
15408                    " */\n"
15409                    "int oneTwoThree=123;",
15410                    Alignment));
15411 
15412   EXPECT_EQ("int a           = 5;\n"
15413             "\n"
15414             "/* block comment */\n"
15415             "\n"
15416             "\n"
15417             "\n"
15418             "int oneTwoThree = 123;",
15419             format("int a = 5;\n"
15420                    "\n"
15421                    "/* block comment */\n"
15422                    "\n"
15423                    "\n"
15424                    "\n"
15425                    "int oneTwoThree=123;",
15426                    Alignment));
15427 
15428   EXPECT_EQ("int a           = 5;\n"
15429             "\n"
15430             "// line comment\n"
15431             "\n"
15432             "\n"
15433             "\n"
15434             "int oneTwoThree = 123;",
15435             format("int a = 5;\n"
15436                    "\n"
15437                    "// line comment\n"
15438                    "\n"
15439                    "\n"
15440                    "\n"
15441                    "int oneTwoThree=123;",
15442                    Alignment));
15443 
15444   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
15445   verifyFormat("#define A \\\n"
15446                "  int aaaa       = 12; \\\n"
15447                "  int b          = 23; \\\n"
15448                "  int ccc        = 234; \\\n"
15449                "  int dddddddddd = 2345;",
15450                Alignment);
15451   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
15452   verifyFormat("#define A               \\\n"
15453                "  int aaaa       = 12;  \\\n"
15454                "  int b          = 23;  \\\n"
15455                "  int ccc        = 234; \\\n"
15456                "  int dddddddddd = 2345;",
15457                Alignment);
15458   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
15459   verifyFormat("#define A                                                      "
15460                "                \\\n"
15461                "  int aaaa       = 12;                                         "
15462                "                \\\n"
15463                "  int b          = 23;                                         "
15464                "                \\\n"
15465                "  int ccc        = 234;                                        "
15466                "                \\\n"
15467                "  int dddddddddd = 2345;",
15468                Alignment);
15469   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
15470                "k = 4, int l = 5,\n"
15471                "                  int m = 6) {\n"
15472                "  int j      = 10;\n"
15473                "  otherThing = 1;\n"
15474                "}",
15475                Alignment);
15476   verifyFormat("void SomeFunction(int parameter = 0) {\n"
15477                "  int i   = 1;\n"
15478                "  int j   = 2;\n"
15479                "  int big = 10000;\n"
15480                "}",
15481                Alignment);
15482   verifyFormat("class C {\n"
15483                "public:\n"
15484                "  int i            = 1;\n"
15485                "  virtual void f() = 0;\n"
15486                "};",
15487                Alignment);
15488   verifyFormat("int i = 1;\n"
15489                "if (SomeType t = getSomething()) {\n"
15490                "}\n"
15491                "int j   = 2;\n"
15492                "int big = 10000;",
15493                Alignment);
15494   verifyFormat("int j = 7;\n"
15495                "for (int k = 0; k < N; ++k) {\n"
15496                "}\n"
15497                "int j   = 2;\n"
15498                "int big = 10000;\n"
15499                "}",
15500                Alignment);
15501   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15502   verifyFormat("int i = 1;\n"
15503                "LooooooooooongType loooooooooooooooooooooongVariable\n"
15504                "    = someLooooooooooooooooongFunction();\n"
15505                "int j = 2;",
15506                Alignment);
15507   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
15508   verifyFormat("int i = 1;\n"
15509                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
15510                "    someLooooooooooooooooongFunction();\n"
15511                "int j = 2;",
15512                Alignment);
15513 
15514   verifyFormat("auto lambda = []() {\n"
15515                "  auto i = 0;\n"
15516                "  return 0;\n"
15517                "};\n"
15518                "int i  = 0;\n"
15519                "auto v = type{\n"
15520                "    i = 1,   //\n"
15521                "    (i = 2), //\n"
15522                "    i = 3    //\n"
15523                "};",
15524                Alignment);
15525 
15526   verifyFormat(
15527       "int i      = 1;\n"
15528       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
15529       "                          loooooooooooooooooooooongParameterB);\n"
15530       "int j      = 2;",
15531       Alignment);
15532 
15533   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
15534                "          typename B   = very_long_type_name_1,\n"
15535                "          typename T_2 = very_long_type_name_2>\n"
15536                "auto foo() {}\n",
15537                Alignment);
15538   verifyFormat("int a, b = 1;\n"
15539                "int c  = 2;\n"
15540                "int dd = 3;\n",
15541                Alignment);
15542   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
15543                "float b[1][] = {{3.f}};\n",
15544                Alignment);
15545   verifyFormat("for (int i = 0; i < 1; i++)\n"
15546                "  int x = 1;\n",
15547                Alignment);
15548   verifyFormat("for (i = 0; i < 1; i++)\n"
15549                "  x = 1;\n"
15550                "y = 1;\n",
15551                Alignment);
15552 
15553   Alignment.ReflowComments = true;
15554   Alignment.ColumnLimit = 50;
15555   EXPECT_EQ("int x   = 0;\n"
15556             "int yy  = 1; /// specificlennospace\n"
15557             "int zzz = 2;\n",
15558             format("int x   = 0;\n"
15559                    "int yy  = 1; ///specificlennospace\n"
15560                    "int zzz = 2;\n",
15561                    Alignment));
15562 }
15563 
15564 TEST_F(FormatTest, AlignConsecutiveAssignments) {
15565   FormatStyle Alignment = getLLVMStyle();
15566   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15567   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15568   verifyFormat("int a = 5;\n"
15569                "int oneTwoThree = 123;",
15570                Alignment);
15571   verifyFormat("int a = 5;\n"
15572                "int oneTwoThree = 123;",
15573                Alignment);
15574 
15575   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15576   verifyFormat("int a           = 5;\n"
15577                "int oneTwoThree = 123;",
15578                Alignment);
15579   verifyFormat("int a           = method();\n"
15580                "int oneTwoThree = 133;",
15581                Alignment);
15582   verifyFormat("a &= 5;\n"
15583                "bcd *= 5;\n"
15584                "ghtyf += 5;\n"
15585                "dvfvdb -= 5;\n"
15586                "a /= 5;\n"
15587                "vdsvsv %= 5;\n"
15588                "sfdbddfbdfbb ^= 5;\n"
15589                "dvsdsv |= 5;\n"
15590                "int dsvvdvsdvvv = 123;",
15591                Alignment);
15592   verifyFormat("int i = 1, j = 10;\n"
15593                "something = 2000;",
15594                Alignment);
15595   verifyFormat("something = 2000;\n"
15596                "int i = 1, j = 10;\n",
15597                Alignment);
15598   verifyFormat("something = 2000;\n"
15599                "another   = 911;\n"
15600                "int i = 1, j = 10;\n"
15601                "oneMore = 1;\n"
15602                "i       = 2;",
15603                Alignment);
15604   verifyFormat("int a   = 5;\n"
15605                "int one = 1;\n"
15606                "method();\n"
15607                "int oneTwoThree = 123;\n"
15608                "int oneTwo      = 12;",
15609                Alignment);
15610   verifyFormat("int oneTwoThree = 123;\n"
15611                "int oneTwo      = 12;\n"
15612                "method();\n",
15613                Alignment);
15614   verifyFormat("int oneTwoThree = 123; // comment\n"
15615                "int oneTwo      = 12;  // comment",
15616                Alignment);
15617 
15618   // Bug 25167
15619   /* Uncomment when fixed
15620     verifyFormat("#if A\n"
15621                  "#else\n"
15622                  "int aaaaaaaa = 12;\n"
15623                  "#endif\n"
15624                  "#if B\n"
15625                  "#else\n"
15626                  "int a = 12;\n"
15627                  "#endif\n",
15628                  Alignment);
15629     verifyFormat("enum foo {\n"
15630                  "#if A\n"
15631                  "#else\n"
15632                  "  aaaaaaaa = 12;\n"
15633                  "#endif\n"
15634                  "#if B\n"
15635                  "#else\n"
15636                  "  a = 12;\n"
15637                  "#endif\n"
15638                  "};\n",
15639                  Alignment);
15640   */
15641 
15642   EXPECT_EQ("int a = 5;\n"
15643             "\n"
15644             "int oneTwoThree = 123;",
15645             format("int a       = 5;\n"
15646                    "\n"
15647                    "int oneTwoThree= 123;",
15648                    Alignment));
15649   EXPECT_EQ("int a   = 5;\n"
15650             "int one = 1;\n"
15651             "\n"
15652             "int oneTwoThree = 123;",
15653             format("int a = 5;\n"
15654                    "int one = 1;\n"
15655                    "\n"
15656                    "int oneTwoThree = 123;",
15657                    Alignment));
15658   EXPECT_EQ("int a   = 5;\n"
15659             "int one = 1;\n"
15660             "\n"
15661             "int oneTwoThree = 123;\n"
15662             "int oneTwo      = 12;",
15663             format("int a = 5;\n"
15664                    "int one = 1;\n"
15665                    "\n"
15666                    "int oneTwoThree = 123;\n"
15667                    "int oneTwo = 12;",
15668                    Alignment));
15669   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
15670   verifyFormat("#define A \\\n"
15671                "  int aaaa       = 12; \\\n"
15672                "  int b          = 23; \\\n"
15673                "  int ccc        = 234; \\\n"
15674                "  int dddddddddd = 2345;",
15675                Alignment);
15676   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
15677   verifyFormat("#define A               \\\n"
15678                "  int aaaa       = 12;  \\\n"
15679                "  int b          = 23;  \\\n"
15680                "  int ccc        = 234; \\\n"
15681                "  int dddddddddd = 2345;",
15682                Alignment);
15683   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
15684   verifyFormat("#define A                                                      "
15685                "                \\\n"
15686                "  int aaaa       = 12;                                         "
15687                "                \\\n"
15688                "  int b          = 23;                                         "
15689                "                \\\n"
15690                "  int ccc        = 234;                                        "
15691                "                \\\n"
15692                "  int dddddddddd = 2345;",
15693                Alignment);
15694   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
15695                "k = 4, int l = 5,\n"
15696                "                  int m = 6) {\n"
15697                "  int j      = 10;\n"
15698                "  otherThing = 1;\n"
15699                "}",
15700                Alignment);
15701   verifyFormat("void SomeFunction(int parameter = 0) {\n"
15702                "  int i   = 1;\n"
15703                "  int j   = 2;\n"
15704                "  int big = 10000;\n"
15705                "}",
15706                Alignment);
15707   verifyFormat("class C {\n"
15708                "public:\n"
15709                "  int i            = 1;\n"
15710                "  virtual void f() = 0;\n"
15711                "};",
15712                Alignment);
15713   verifyFormat("int i = 1;\n"
15714                "if (SomeType t = getSomething()) {\n"
15715                "}\n"
15716                "int j   = 2;\n"
15717                "int big = 10000;",
15718                Alignment);
15719   verifyFormat("int j = 7;\n"
15720                "for (int k = 0; k < N; ++k) {\n"
15721                "}\n"
15722                "int j   = 2;\n"
15723                "int big = 10000;\n"
15724                "}",
15725                Alignment);
15726   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15727   verifyFormat("int i = 1;\n"
15728                "LooooooooooongType loooooooooooooooooooooongVariable\n"
15729                "    = someLooooooooooooooooongFunction();\n"
15730                "int j = 2;",
15731                Alignment);
15732   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
15733   verifyFormat("int i = 1;\n"
15734                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
15735                "    someLooooooooooooooooongFunction();\n"
15736                "int j = 2;",
15737                Alignment);
15738 
15739   verifyFormat("auto lambda = []() {\n"
15740                "  auto i = 0;\n"
15741                "  return 0;\n"
15742                "};\n"
15743                "int i  = 0;\n"
15744                "auto v = type{\n"
15745                "    i = 1,   //\n"
15746                "    (i = 2), //\n"
15747                "    i = 3    //\n"
15748                "};",
15749                Alignment);
15750 
15751   verifyFormat(
15752       "int i      = 1;\n"
15753       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
15754       "                          loooooooooooooooooooooongParameterB);\n"
15755       "int j      = 2;",
15756       Alignment);
15757 
15758   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
15759                "          typename B   = very_long_type_name_1,\n"
15760                "          typename T_2 = very_long_type_name_2>\n"
15761                "auto foo() {}\n",
15762                Alignment);
15763   verifyFormat("int a, b = 1;\n"
15764                "int c  = 2;\n"
15765                "int dd = 3;\n",
15766                Alignment);
15767   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
15768                "float b[1][] = {{3.f}};\n",
15769                Alignment);
15770   verifyFormat("for (int i = 0; i < 1; i++)\n"
15771                "  int x = 1;\n",
15772                Alignment);
15773   verifyFormat("for (i = 0; i < 1; i++)\n"
15774                "  x = 1;\n"
15775                "y = 1;\n",
15776                Alignment);
15777 
15778   Alignment.ReflowComments = true;
15779   Alignment.ColumnLimit = 50;
15780   EXPECT_EQ("int x   = 0;\n"
15781             "int yy  = 1; /// specificlennospace\n"
15782             "int zzz = 2;\n",
15783             format("int x   = 0;\n"
15784                    "int yy  = 1; ///specificlennospace\n"
15785                    "int zzz = 2;\n",
15786                    Alignment));
15787 }
15788 
15789 TEST_F(FormatTest, AlignConsecutiveBitFields) {
15790   FormatStyle Alignment = getLLVMStyle();
15791   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
15792   verifyFormat("int const a     : 5;\n"
15793                "int oneTwoThree : 23;",
15794                Alignment);
15795 
15796   // Initializers are allowed starting with c++2a
15797   verifyFormat("int const a     : 5 = 1;\n"
15798                "int oneTwoThree : 23 = 0;",
15799                Alignment);
15800 
15801   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15802   verifyFormat("int const a           : 5;\n"
15803                "int       oneTwoThree : 23;",
15804                Alignment);
15805 
15806   verifyFormat("int const a           : 5;  // comment\n"
15807                "int       oneTwoThree : 23; // comment",
15808                Alignment);
15809 
15810   verifyFormat("int const a           : 5 = 1;\n"
15811                "int       oneTwoThree : 23 = 0;",
15812                Alignment);
15813 
15814   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15815   verifyFormat("int const a           : 5  = 1;\n"
15816                "int       oneTwoThree : 23 = 0;",
15817                Alignment);
15818   verifyFormat("int const a           : 5  = {1};\n"
15819                "int       oneTwoThree : 23 = 0;",
15820                Alignment);
15821 
15822   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
15823   verifyFormat("int const a          :5;\n"
15824                "int       oneTwoThree:23;",
15825                Alignment);
15826 
15827   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
15828   verifyFormat("int const a           :5;\n"
15829                "int       oneTwoThree :23;",
15830                Alignment);
15831 
15832   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
15833   verifyFormat("int const a          : 5;\n"
15834                "int       oneTwoThree: 23;",
15835                Alignment);
15836 
15837   // Known limitations: ':' is only recognized as a bitfield colon when
15838   // followed by a number.
15839   /*
15840   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
15841                "int a           : 5;",
15842                Alignment);
15843   */
15844 }
15845 
15846 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
15847   FormatStyle Alignment = getLLVMStyle();
15848   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15849   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
15850   Alignment.PointerAlignment = FormatStyle::PAS_Right;
15851   verifyFormat("float const a = 5;\n"
15852                "int oneTwoThree = 123;",
15853                Alignment);
15854   verifyFormat("int a = 5;\n"
15855                "float const oneTwoThree = 123;",
15856                Alignment);
15857 
15858   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15859   verifyFormat("float const a = 5;\n"
15860                "int         oneTwoThree = 123;",
15861                Alignment);
15862   verifyFormat("int         a = method();\n"
15863                "float const oneTwoThree = 133;",
15864                Alignment);
15865   verifyFormat("int i = 1, j = 10;\n"
15866                "something = 2000;",
15867                Alignment);
15868   verifyFormat("something = 2000;\n"
15869                "int i = 1, j = 10;\n",
15870                Alignment);
15871   verifyFormat("float      something = 2000;\n"
15872                "double     another = 911;\n"
15873                "int        i = 1, j = 10;\n"
15874                "const int *oneMore = 1;\n"
15875                "unsigned   i = 2;",
15876                Alignment);
15877   verifyFormat("float a = 5;\n"
15878                "int   one = 1;\n"
15879                "method();\n"
15880                "const double       oneTwoThree = 123;\n"
15881                "const unsigned int oneTwo = 12;",
15882                Alignment);
15883   verifyFormat("int      oneTwoThree{0}; // comment\n"
15884                "unsigned oneTwo;         // comment",
15885                Alignment);
15886   verifyFormat("unsigned int       *a;\n"
15887                "int                *b;\n"
15888                "unsigned int Const *c;\n"
15889                "unsigned int const *d;\n"
15890                "unsigned int Const &e;\n"
15891                "unsigned int const &f;",
15892                Alignment);
15893   verifyFormat("Const unsigned int *c;\n"
15894                "const unsigned int *d;\n"
15895                "Const unsigned int &e;\n"
15896                "const unsigned int &f;\n"
15897                "const unsigned      g;\n"
15898                "Const unsigned      h;",
15899                Alignment);
15900   EXPECT_EQ("float const a = 5;\n"
15901             "\n"
15902             "int oneTwoThree = 123;",
15903             format("float const   a = 5;\n"
15904                    "\n"
15905                    "int           oneTwoThree= 123;",
15906                    Alignment));
15907   EXPECT_EQ("float a = 5;\n"
15908             "int   one = 1;\n"
15909             "\n"
15910             "unsigned oneTwoThree = 123;",
15911             format("float    a = 5;\n"
15912                    "int      one = 1;\n"
15913                    "\n"
15914                    "unsigned oneTwoThree = 123;",
15915                    Alignment));
15916   EXPECT_EQ("float a = 5;\n"
15917             "int   one = 1;\n"
15918             "\n"
15919             "unsigned oneTwoThree = 123;\n"
15920             "int      oneTwo = 12;",
15921             format("float    a = 5;\n"
15922                    "int one = 1;\n"
15923                    "\n"
15924                    "unsigned oneTwoThree = 123;\n"
15925                    "int oneTwo = 12;",
15926                    Alignment));
15927   // Function prototype alignment
15928   verifyFormat("int    a();\n"
15929                "double b();",
15930                Alignment);
15931   verifyFormat("int    a(int x);\n"
15932                "double b();",
15933                Alignment);
15934   unsigned OldColumnLimit = Alignment.ColumnLimit;
15935   // We need to set ColumnLimit to zero, in order to stress nested alignments,
15936   // otherwise the function parameters will be re-flowed onto a single line.
15937   Alignment.ColumnLimit = 0;
15938   EXPECT_EQ("int    a(int   x,\n"
15939             "         float y);\n"
15940             "double b(int    x,\n"
15941             "         double y);",
15942             format("int a(int x,\n"
15943                    " float y);\n"
15944                    "double b(int x,\n"
15945                    " double y);",
15946                    Alignment));
15947   // This ensures that function parameters of function declarations are
15948   // correctly indented when their owning functions are indented.
15949   // The failure case here is for 'double y' to not be indented enough.
15950   EXPECT_EQ("double a(int x);\n"
15951             "int    b(int    y,\n"
15952             "         double z);",
15953             format("double a(int x);\n"
15954                    "int b(int y,\n"
15955                    " double z);",
15956                    Alignment));
15957   // Set ColumnLimit low so that we induce wrapping immediately after
15958   // the function name and opening paren.
15959   Alignment.ColumnLimit = 13;
15960   verifyFormat("int function(\n"
15961                "    int  x,\n"
15962                "    bool y);",
15963                Alignment);
15964   Alignment.ColumnLimit = OldColumnLimit;
15965   // Ensure function pointers don't screw up recursive alignment
15966   verifyFormat("int    a(int x, void (*fp)(int y));\n"
15967                "double b();",
15968                Alignment);
15969   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15970   // Ensure recursive alignment is broken by function braces, so that the
15971   // "a = 1" does not align with subsequent assignments inside the function
15972   // body.
15973   verifyFormat("int func(int a = 1) {\n"
15974                "  int b  = 2;\n"
15975                "  int cc = 3;\n"
15976                "}",
15977                Alignment);
15978   verifyFormat("float      something = 2000;\n"
15979                "double     another   = 911;\n"
15980                "int        i = 1, j = 10;\n"
15981                "const int *oneMore = 1;\n"
15982                "unsigned   i       = 2;",
15983                Alignment);
15984   verifyFormat("int      oneTwoThree = {0}; // comment\n"
15985                "unsigned oneTwo      = 0;   // comment",
15986                Alignment);
15987   // Make sure that scope is correctly tracked, in the absence of braces
15988   verifyFormat("for (int i = 0; i < n; i++)\n"
15989                "  j = i;\n"
15990                "double x = 1;\n",
15991                Alignment);
15992   verifyFormat("if (int i = 0)\n"
15993                "  j = i;\n"
15994                "double x = 1;\n",
15995                Alignment);
15996   // Ensure operator[] and operator() are comprehended
15997   verifyFormat("struct test {\n"
15998                "  long long int foo();\n"
15999                "  int           operator[](int a);\n"
16000                "  double        bar();\n"
16001                "};\n",
16002                Alignment);
16003   verifyFormat("struct test {\n"
16004                "  long long int foo();\n"
16005                "  int           operator()(int a);\n"
16006                "  double        bar();\n"
16007                "};\n",
16008                Alignment);
16009 
16010   // PAS_Right
16011   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16012             "  int const i   = 1;\n"
16013             "  int      *j   = 2;\n"
16014             "  int       big = 10000;\n"
16015             "\n"
16016             "  unsigned oneTwoThree = 123;\n"
16017             "  int      oneTwo      = 12;\n"
16018             "  method();\n"
16019             "  float k  = 2;\n"
16020             "  int   ll = 10000;\n"
16021             "}",
16022             format("void SomeFunction(int parameter= 0) {\n"
16023                    " int const  i= 1;\n"
16024                    "  int *j=2;\n"
16025                    " int big  =  10000;\n"
16026                    "\n"
16027                    "unsigned oneTwoThree  =123;\n"
16028                    "int oneTwo = 12;\n"
16029                    "  method();\n"
16030                    "float k= 2;\n"
16031                    "int ll=10000;\n"
16032                    "}",
16033                    Alignment));
16034   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16035             "  int const i   = 1;\n"
16036             "  int     **j   = 2, ***k;\n"
16037             "  int      &k   = i;\n"
16038             "  int     &&l   = i + j;\n"
16039             "  int       big = 10000;\n"
16040             "\n"
16041             "  unsigned oneTwoThree = 123;\n"
16042             "  int      oneTwo      = 12;\n"
16043             "  method();\n"
16044             "  float k  = 2;\n"
16045             "  int   ll = 10000;\n"
16046             "}",
16047             format("void SomeFunction(int parameter= 0) {\n"
16048                    " int const  i= 1;\n"
16049                    "  int **j=2,***k;\n"
16050                    "int &k=i;\n"
16051                    "int &&l=i+j;\n"
16052                    " int big  =  10000;\n"
16053                    "\n"
16054                    "unsigned oneTwoThree  =123;\n"
16055                    "int oneTwo = 12;\n"
16056                    "  method();\n"
16057                    "float k= 2;\n"
16058                    "int ll=10000;\n"
16059                    "}",
16060                    Alignment));
16061   // variables are aligned at their name, pointers are at the right most
16062   // position
16063   verifyFormat("int   *a;\n"
16064                "int  **b;\n"
16065                "int ***c;\n"
16066                "int    foobar;\n",
16067                Alignment);
16068 
16069   // PAS_Left
16070   FormatStyle AlignmentLeft = Alignment;
16071   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
16072   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16073             "  int const i   = 1;\n"
16074             "  int*      j   = 2;\n"
16075             "  int       big = 10000;\n"
16076             "\n"
16077             "  unsigned oneTwoThree = 123;\n"
16078             "  int      oneTwo      = 12;\n"
16079             "  method();\n"
16080             "  float k  = 2;\n"
16081             "  int   ll = 10000;\n"
16082             "}",
16083             format("void SomeFunction(int parameter= 0) {\n"
16084                    " int const  i= 1;\n"
16085                    "  int *j=2;\n"
16086                    " int big  =  10000;\n"
16087                    "\n"
16088                    "unsigned oneTwoThree  =123;\n"
16089                    "int oneTwo = 12;\n"
16090                    "  method();\n"
16091                    "float k= 2;\n"
16092                    "int ll=10000;\n"
16093                    "}",
16094                    AlignmentLeft));
16095   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16096             "  int const i   = 1;\n"
16097             "  int**     j   = 2;\n"
16098             "  int&      k   = i;\n"
16099             "  int&&     l   = i + j;\n"
16100             "  int       big = 10000;\n"
16101             "\n"
16102             "  unsigned oneTwoThree = 123;\n"
16103             "  int      oneTwo      = 12;\n"
16104             "  method();\n"
16105             "  float k  = 2;\n"
16106             "  int   ll = 10000;\n"
16107             "}",
16108             format("void SomeFunction(int parameter= 0) {\n"
16109                    " int const  i= 1;\n"
16110                    "  int **j=2;\n"
16111                    "int &k=i;\n"
16112                    "int &&l=i+j;\n"
16113                    " int big  =  10000;\n"
16114                    "\n"
16115                    "unsigned oneTwoThree  =123;\n"
16116                    "int oneTwo = 12;\n"
16117                    "  method();\n"
16118                    "float k= 2;\n"
16119                    "int ll=10000;\n"
16120                    "}",
16121                    AlignmentLeft));
16122   // variables are aligned at their name, pointers are at the left most position
16123   verifyFormat("int*   a;\n"
16124                "int**  b;\n"
16125                "int*** c;\n"
16126                "int    foobar;\n",
16127                AlignmentLeft);
16128 
16129   // PAS_Middle
16130   FormatStyle AlignmentMiddle = Alignment;
16131   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
16132   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16133             "  int const i   = 1;\n"
16134             "  int *     j   = 2;\n"
16135             "  int       big = 10000;\n"
16136             "\n"
16137             "  unsigned oneTwoThree = 123;\n"
16138             "  int      oneTwo      = 12;\n"
16139             "  method();\n"
16140             "  float k  = 2;\n"
16141             "  int   ll = 10000;\n"
16142             "}",
16143             format("void SomeFunction(int parameter= 0) {\n"
16144                    " int const  i= 1;\n"
16145                    "  int *j=2;\n"
16146                    " int big  =  10000;\n"
16147                    "\n"
16148                    "unsigned oneTwoThree  =123;\n"
16149                    "int oneTwo = 12;\n"
16150                    "  method();\n"
16151                    "float k= 2;\n"
16152                    "int ll=10000;\n"
16153                    "}",
16154                    AlignmentMiddle));
16155   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16156             "  int const i   = 1;\n"
16157             "  int **    j   = 2, ***k;\n"
16158             "  int &     k   = i;\n"
16159             "  int &&    l   = i + j;\n"
16160             "  int       big = 10000;\n"
16161             "\n"
16162             "  unsigned oneTwoThree = 123;\n"
16163             "  int      oneTwo      = 12;\n"
16164             "  method();\n"
16165             "  float k  = 2;\n"
16166             "  int   ll = 10000;\n"
16167             "}",
16168             format("void SomeFunction(int parameter= 0) {\n"
16169                    " int const  i= 1;\n"
16170                    "  int **j=2,***k;\n"
16171                    "int &k=i;\n"
16172                    "int &&l=i+j;\n"
16173                    " int big  =  10000;\n"
16174                    "\n"
16175                    "unsigned oneTwoThree  =123;\n"
16176                    "int oneTwo = 12;\n"
16177                    "  method();\n"
16178                    "float k= 2;\n"
16179                    "int ll=10000;\n"
16180                    "}",
16181                    AlignmentMiddle));
16182   // variables are aligned at their name, pointers are in the middle
16183   verifyFormat("int *   a;\n"
16184                "int *   b;\n"
16185                "int *** c;\n"
16186                "int     foobar;\n",
16187                AlignmentMiddle);
16188 
16189   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16190   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16191   verifyFormat("#define A \\\n"
16192                "  int       aaaa = 12; \\\n"
16193                "  float     b = 23; \\\n"
16194                "  const int ccc = 234; \\\n"
16195                "  unsigned  dddddddddd = 2345;",
16196                Alignment);
16197   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16198   verifyFormat("#define A              \\\n"
16199                "  int       aaaa = 12; \\\n"
16200                "  float     b = 23;    \\\n"
16201                "  const int ccc = 234; \\\n"
16202                "  unsigned  dddddddddd = 2345;",
16203                Alignment);
16204   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16205   Alignment.ColumnLimit = 30;
16206   verifyFormat("#define A                    \\\n"
16207                "  int       aaaa = 12;       \\\n"
16208                "  float     b = 23;          \\\n"
16209                "  const int ccc = 234;       \\\n"
16210                "  int       dddddddddd = 2345;",
16211                Alignment);
16212   Alignment.ColumnLimit = 80;
16213   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16214                "k = 4, int l = 5,\n"
16215                "                  int m = 6) {\n"
16216                "  const int j = 10;\n"
16217                "  otherThing = 1;\n"
16218                "}",
16219                Alignment);
16220   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16221                "  int const i = 1;\n"
16222                "  int      *j = 2;\n"
16223                "  int       big = 10000;\n"
16224                "}",
16225                Alignment);
16226   verifyFormat("class C {\n"
16227                "public:\n"
16228                "  int          i = 1;\n"
16229                "  virtual void f() = 0;\n"
16230                "};",
16231                Alignment);
16232   verifyFormat("float i = 1;\n"
16233                "if (SomeType t = getSomething()) {\n"
16234                "}\n"
16235                "const unsigned j = 2;\n"
16236                "int            big = 10000;",
16237                Alignment);
16238   verifyFormat("float j = 7;\n"
16239                "for (int k = 0; k < N; ++k) {\n"
16240                "}\n"
16241                "unsigned j = 2;\n"
16242                "int      big = 10000;\n"
16243                "}",
16244                Alignment);
16245   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16246   verifyFormat("float              i = 1;\n"
16247                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16248                "    = someLooooooooooooooooongFunction();\n"
16249                "int j = 2;",
16250                Alignment);
16251   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16252   verifyFormat("int                i = 1;\n"
16253                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16254                "    someLooooooooooooooooongFunction();\n"
16255                "int j = 2;",
16256                Alignment);
16257 
16258   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16259   verifyFormat("auto lambda = []() {\n"
16260                "  auto  ii = 0;\n"
16261                "  float j  = 0;\n"
16262                "  return 0;\n"
16263                "};\n"
16264                "int   i  = 0;\n"
16265                "float i2 = 0;\n"
16266                "auto  v  = type{\n"
16267                "    i = 1,   //\n"
16268                "    (i = 2), //\n"
16269                "    i = 3    //\n"
16270                "};",
16271                Alignment);
16272   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16273 
16274   verifyFormat(
16275       "int      i = 1;\n"
16276       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16277       "                          loooooooooooooooooooooongParameterB);\n"
16278       "int      j = 2;",
16279       Alignment);
16280 
16281   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
16282   // We expect declarations and assignments to align, as long as it doesn't
16283   // exceed the column limit, starting a new alignment sequence whenever it
16284   // happens.
16285   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16286   Alignment.ColumnLimit = 30;
16287   verifyFormat("float    ii              = 1;\n"
16288                "unsigned j               = 2;\n"
16289                "int someVerylongVariable = 1;\n"
16290                "AnotherLongType  ll = 123456;\n"
16291                "VeryVeryLongType k  = 2;\n"
16292                "int              myvar = 1;",
16293                Alignment);
16294   Alignment.ColumnLimit = 80;
16295   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16296 
16297   verifyFormat(
16298       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
16299       "          typename LongType, typename B>\n"
16300       "auto foo() {}\n",
16301       Alignment);
16302   verifyFormat("float a, b = 1;\n"
16303                "int   c = 2;\n"
16304                "int   dd = 3;\n",
16305                Alignment);
16306   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
16307                "float b[1][] = {{3.f}};\n",
16308                Alignment);
16309   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16310   verifyFormat("float a, b = 1;\n"
16311                "int   c  = 2;\n"
16312                "int   dd = 3;\n",
16313                Alignment);
16314   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
16315                "float b[1][] = {{3.f}};\n",
16316                Alignment);
16317   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16318 
16319   Alignment.ColumnLimit = 30;
16320   Alignment.BinPackParameters = false;
16321   verifyFormat("void foo(float     a,\n"
16322                "         float     b,\n"
16323                "         int       c,\n"
16324                "         uint32_t *d) {\n"
16325                "  int   *e = 0;\n"
16326                "  float  f = 0;\n"
16327                "  double g = 0;\n"
16328                "}\n"
16329                "void bar(ino_t     a,\n"
16330                "         int       b,\n"
16331                "         uint32_t *c,\n"
16332                "         bool      d) {}\n",
16333                Alignment);
16334   Alignment.BinPackParameters = true;
16335   Alignment.ColumnLimit = 80;
16336 
16337   // Bug 33507
16338   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16339   verifyFormat(
16340       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
16341       "  static const Version verVs2017;\n"
16342       "  return true;\n"
16343       "});\n",
16344       Alignment);
16345   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16346 
16347   // See llvm.org/PR35641
16348   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16349   verifyFormat("int func() { //\n"
16350                "  int      b;\n"
16351                "  unsigned c;\n"
16352                "}",
16353                Alignment);
16354 
16355   // See PR37175
16356   FormatStyle Style = getMozillaStyle();
16357   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16358   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
16359             "foo(int a);",
16360             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
16361 
16362   Alignment.PointerAlignment = FormatStyle::PAS_Left;
16363   verifyFormat("unsigned int*       a;\n"
16364                "int*                b;\n"
16365                "unsigned int Const* c;\n"
16366                "unsigned int const* d;\n"
16367                "unsigned int Const& e;\n"
16368                "unsigned int const& f;",
16369                Alignment);
16370   verifyFormat("Const unsigned int* c;\n"
16371                "const unsigned int* d;\n"
16372                "Const unsigned int& e;\n"
16373                "const unsigned int& f;\n"
16374                "const unsigned      g;\n"
16375                "Const unsigned      h;",
16376                Alignment);
16377 
16378   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16379   verifyFormat("unsigned int *       a;\n"
16380                "int *                b;\n"
16381                "unsigned int Const * c;\n"
16382                "unsigned int const * d;\n"
16383                "unsigned int Const & e;\n"
16384                "unsigned int const & f;",
16385                Alignment);
16386   verifyFormat("Const unsigned int * c;\n"
16387                "const unsigned int * d;\n"
16388                "Const unsigned int & e;\n"
16389                "const unsigned int & f;\n"
16390                "const unsigned       g;\n"
16391                "Const unsigned       h;",
16392                Alignment);
16393 }
16394 
16395 TEST_F(FormatTest, AlignWithLineBreaks) {
16396   auto Style = getLLVMStyleWithColumns(120);
16397 
16398   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
16399   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16400   verifyFormat("void foo() {\n"
16401                "  int myVar = 5;\n"
16402                "  double x = 3.14;\n"
16403                "  auto str = \"Hello \"\n"
16404                "             \"World\";\n"
16405                "  auto s = \"Hello \"\n"
16406                "           \"Again\";\n"
16407                "}",
16408                Style);
16409 
16410   // clang-format off
16411   verifyFormat("void foo() {\n"
16412                "  const int capacityBefore = Entries.capacity();\n"
16413                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16414                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16415                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16416                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16417                "}",
16418                Style);
16419   // clang-format on
16420 
16421   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16422   verifyFormat("void foo() {\n"
16423                "  int myVar = 5;\n"
16424                "  double x  = 3.14;\n"
16425                "  auto str  = \"Hello \"\n"
16426                "              \"World\";\n"
16427                "  auto s    = \"Hello \"\n"
16428                "              \"Again\";\n"
16429                "}",
16430                Style);
16431 
16432   // clang-format off
16433   verifyFormat("void foo() {\n"
16434                "  const int capacityBefore = Entries.capacity();\n"
16435                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16436                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16437                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16438                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16439                "}",
16440                Style);
16441   // clang-format on
16442 
16443   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16444   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16445   verifyFormat("void foo() {\n"
16446                "  int    myVar = 5;\n"
16447                "  double x = 3.14;\n"
16448                "  auto   str = \"Hello \"\n"
16449                "               \"World\";\n"
16450                "  auto   s = \"Hello \"\n"
16451                "             \"Again\";\n"
16452                "}",
16453                Style);
16454 
16455   // clang-format off
16456   verifyFormat("void foo() {\n"
16457                "  const int  capacityBefore = Entries.capacity();\n"
16458                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16459                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16460                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16461                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16462                "}",
16463                Style);
16464   // clang-format on
16465 
16466   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16467   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16468 
16469   verifyFormat("void foo() {\n"
16470                "  int    myVar = 5;\n"
16471                "  double x     = 3.14;\n"
16472                "  auto   str   = \"Hello \"\n"
16473                "                 \"World\";\n"
16474                "  auto   s     = \"Hello \"\n"
16475                "                 \"Again\";\n"
16476                "}",
16477                Style);
16478 
16479   // clang-format off
16480   verifyFormat("void foo() {\n"
16481                "  const int  capacityBefore = Entries.capacity();\n"
16482                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16483                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16484                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16485                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16486                "}",
16487                Style);
16488   // clang-format on
16489 
16490   Style = getLLVMStyleWithColumns(120);
16491   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16492   Style.ContinuationIndentWidth = 4;
16493   Style.IndentWidth = 4;
16494 
16495   // clang-format off
16496   verifyFormat("void SomeFunc() {\n"
16497                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16498                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16499                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16500                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16501                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16502                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16503                "}",
16504                Style);
16505   // clang-format on
16506 
16507   Style.BinPackArguments = false;
16508 
16509   // clang-format off
16510   verifyFormat("void SomeFunc() {\n"
16511                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
16512                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16513                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
16514                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16515                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
16516                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16517                "}",
16518                Style);
16519   // clang-format on
16520 }
16521 
16522 TEST_F(FormatTest, AlignWithInitializerPeriods) {
16523   auto Style = getLLVMStyleWithColumns(60);
16524 
16525   verifyFormat("void foo1(void) {\n"
16526                "  BYTE p[1] = 1;\n"
16527                "  A B = {.one_foooooooooooooooo = 2,\n"
16528                "         .two_fooooooooooooo = 3,\n"
16529                "         .three_fooooooooooooo = 4};\n"
16530                "  BYTE payload = 2;\n"
16531                "}",
16532                Style);
16533 
16534   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16535   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16536   verifyFormat("void foo2(void) {\n"
16537                "  BYTE p[1]    = 1;\n"
16538                "  A B          = {.one_foooooooooooooooo = 2,\n"
16539                "                  .two_fooooooooooooo    = 3,\n"
16540                "                  .three_fooooooooooooo  = 4};\n"
16541                "  BYTE payload = 2;\n"
16542                "}",
16543                Style);
16544 
16545   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16546   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16547   verifyFormat("void foo3(void) {\n"
16548                "  BYTE p[1] = 1;\n"
16549                "  A    B = {.one_foooooooooooooooo = 2,\n"
16550                "            .two_fooooooooooooo = 3,\n"
16551                "            .three_fooooooooooooo = 4};\n"
16552                "  BYTE payload = 2;\n"
16553                "}",
16554                Style);
16555 
16556   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16557   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16558   verifyFormat("void foo4(void) {\n"
16559                "  BYTE p[1]    = 1;\n"
16560                "  A    B       = {.one_foooooooooooooooo = 2,\n"
16561                "                  .two_fooooooooooooo    = 3,\n"
16562                "                  .three_fooooooooooooo  = 4};\n"
16563                "  BYTE payload = 2;\n"
16564                "}",
16565                Style);
16566 }
16567 
16568 TEST_F(FormatTest, LinuxBraceBreaking) {
16569   FormatStyle LinuxBraceStyle = getLLVMStyle();
16570   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
16571   verifyFormat("namespace a\n"
16572                "{\n"
16573                "class A\n"
16574                "{\n"
16575                "  void f()\n"
16576                "  {\n"
16577                "    if (true) {\n"
16578                "      a();\n"
16579                "      b();\n"
16580                "    } else {\n"
16581                "      a();\n"
16582                "    }\n"
16583                "  }\n"
16584                "  void g() { return; }\n"
16585                "};\n"
16586                "struct B {\n"
16587                "  int x;\n"
16588                "};\n"
16589                "} // namespace a\n",
16590                LinuxBraceStyle);
16591   verifyFormat("enum X {\n"
16592                "  Y = 0,\n"
16593                "}\n",
16594                LinuxBraceStyle);
16595   verifyFormat("struct S {\n"
16596                "  int Type;\n"
16597                "  union {\n"
16598                "    int x;\n"
16599                "    double y;\n"
16600                "  } Value;\n"
16601                "  class C\n"
16602                "  {\n"
16603                "    MyFavoriteType Value;\n"
16604                "  } Class;\n"
16605                "}\n",
16606                LinuxBraceStyle);
16607 }
16608 
16609 TEST_F(FormatTest, MozillaBraceBreaking) {
16610   FormatStyle MozillaBraceStyle = getLLVMStyle();
16611   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
16612   MozillaBraceStyle.FixNamespaceComments = false;
16613   verifyFormat("namespace a {\n"
16614                "class A\n"
16615                "{\n"
16616                "  void f()\n"
16617                "  {\n"
16618                "    if (true) {\n"
16619                "      a();\n"
16620                "      b();\n"
16621                "    }\n"
16622                "  }\n"
16623                "  void g() { return; }\n"
16624                "};\n"
16625                "enum E\n"
16626                "{\n"
16627                "  A,\n"
16628                "  // foo\n"
16629                "  B,\n"
16630                "  C\n"
16631                "};\n"
16632                "struct B\n"
16633                "{\n"
16634                "  int x;\n"
16635                "};\n"
16636                "}\n",
16637                MozillaBraceStyle);
16638   verifyFormat("struct S\n"
16639                "{\n"
16640                "  int Type;\n"
16641                "  union\n"
16642                "  {\n"
16643                "    int x;\n"
16644                "    double y;\n"
16645                "  } Value;\n"
16646                "  class C\n"
16647                "  {\n"
16648                "    MyFavoriteType Value;\n"
16649                "  } Class;\n"
16650                "}\n",
16651                MozillaBraceStyle);
16652 }
16653 
16654 TEST_F(FormatTest, StroustrupBraceBreaking) {
16655   FormatStyle StroustrupBraceStyle = getLLVMStyle();
16656   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
16657   verifyFormat("namespace a {\n"
16658                "class A {\n"
16659                "  void f()\n"
16660                "  {\n"
16661                "    if (true) {\n"
16662                "      a();\n"
16663                "      b();\n"
16664                "    }\n"
16665                "  }\n"
16666                "  void g() { return; }\n"
16667                "};\n"
16668                "struct B {\n"
16669                "  int x;\n"
16670                "};\n"
16671                "} // namespace a\n",
16672                StroustrupBraceStyle);
16673 
16674   verifyFormat("void foo()\n"
16675                "{\n"
16676                "  if (a) {\n"
16677                "    a();\n"
16678                "  }\n"
16679                "  else {\n"
16680                "    b();\n"
16681                "  }\n"
16682                "}\n",
16683                StroustrupBraceStyle);
16684 
16685   verifyFormat("#ifdef _DEBUG\n"
16686                "int foo(int i = 0)\n"
16687                "#else\n"
16688                "int foo(int i = 5)\n"
16689                "#endif\n"
16690                "{\n"
16691                "  return i;\n"
16692                "}",
16693                StroustrupBraceStyle);
16694 
16695   verifyFormat("void foo() {}\n"
16696                "void bar()\n"
16697                "#ifdef _DEBUG\n"
16698                "{\n"
16699                "  foo();\n"
16700                "}\n"
16701                "#else\n"
16702                "{\n"
16703                "}\n"
16704                "#endif",
16705                StroustrupBraceStyle);
16706 
16707   verifyFormat("void foobar() { int i = 5; }\n"
16708                "#ifdef _DEBUG\n"
16709                "void bar() {}\n"
16710                "#else\n"
16711                "void bar() { foobar(); }\n"
16712                "#endif",
16713                StroustrupBraceStyle);
16714 }
16715 
16716 TEST_F(FormatTest, AllmanBraceBreaking) {
16717   FormatStyle AllmanBraceStyle = getLLVMStyle();
16718   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
16719 
16720   EXPECT_EQ("namespace a\n"
16721             "{\n"
16722             "void f();\n"
16723             "void g();\n"
16724             "} // namespace a\n",
16725             format("namespace a\n"
16726                    "{\n"
16727                    "void f();\n"
16728                    "void g();\n"
16729                    "}\n",
16730                    AllmanBraceStyle));
16731 
16732   verifyFormat("namespace a\n"
16733                "{\n"
16734                "class A\n"
16735                "{\n"
16736                "  void f()\n"
16737                "  {\n"
16738                "    if (true)\n"
16739                "    {\n"
16740                "      a();\n"
16741                "      b();\n"
16742                "    }\n"
16743                "  }\n"
16744                "  void g() { return; }\n"
16745                "};\n"
16746                "struct B\n"
16747                "{\n"
16748                "  int x;\n"
16749                "};\n"
16750                "union C\n"
16751                "{\n"
16752                "};\n"
16753                "} // namespace a",
16754                AllmanBraceStyle);
16755 
16756   verifyFormat("void f()\n"
16757                "{\n"
16758                "  if (true)\n"
16759                "  {\n"
16760                "    a();\n"
16761                "  }\n"
16762                "  else if (false)\n"
16763                "  {\n"
16764                "    b();\n"
16765                "  }\n"
16766                "  else\n"
16767                "  {\n"
16768                "    c();\n"
16769                "  }\n"
16770                "}\n",
16771                AllmanBraceStyle);
16772 
16773   verifyFormat("void f()\n"
16774                "{\n"
16775                "  for (int i = 0; i < 10; ++i)\n"
16776                "  {\n"
16777                "    a();\n"
16778                "  }\n"
16779                "  while (false)\n"
16780                "  {\n"
16781                "    b();\n"
16782                "  }\n"
16783                "  do\n"
16784                "  {\n"
16785                "    c();\n"
16786                "  } while (false)\n"
16787                "}\n",
16788                AllmanBraceStyle);
16789 
16790   verifyFormat("void f(int a)\n"
16791                "{\n"
16792                "  switch (a)\n"
16793                "  {\n"
16794                "  case 0:\n"
16795                "    break;\n"
16796                "  case 1:\n"
16797                "  {\n"
16798                "    break;\n"
16799                "  }\n"
16800                "  case 2:\n"
16801                "  {\n"
16802                "  }\n"
16803                "  break;\n"
16804                "  default:\n"
16805                "    break;\n"
16806                "  }\n"
16807                "}\n",
16808                AllmanBraceStyle);
16809 
16810   verifyFormat("enum X\n"
16811                "{\n"
16812                "  Y = 0,\n"
16813                "}\n",
16814                AllmanBraceStyle);
16815   verifyFormat("enum X\n"
16816                "{\n"
16817                "  Y = 0\n"
16818                "}\n",
16819                AllmanBraceStyle);
16820 
16821   verifyFormat("@interface BSApplicationController ()\n"
16822                "{\n"
16823                "@private\n"
16824                "  id _extraIvar;\n"
16825                "}\n"
16826                "@end\n",
16827                AllmanBraceStyle);
16828 
16829   verifyFormat("#ifdef _DEBUG\n"
16830                "int foo(int i = 0)\n"
16831                "#else\n"
16832                "int foo(int i = 5)\n"
16833                "#endif\n"
16834                "{\n"
16835                "  return i;\n"
16836                "}",
16837                AllmanBraceStyle);
16838 
16839   verifyFormat("void foo() {}\n"
16840                "void bar()\n"
16841                "#ifdef _DEBUG\n"
16842                "{\n"
16843                "  foo();\n"
16844                "}\n"
16845                "#else\n"
16846                "{\n"
16847                "}\n"
16848                "#endif",
16849                AllmanBraceStyle);
16850 
16851   verifyFormat("void foobar() { int i = 5; }\n"
16852                "#ifdef _DEBUG\n"
16853                "void bar() {}\n"
16854                "#else\n"
16855                "void bar() { foobar(); }\n"
16856                "#endif",
16857                AllmanBraceStyle);
16858 
16859   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
16860             FormatStyle::SLS_All);
16861 
16862   verifyFormat("[](int i) { return i + 2; };\n"
16863                "[](int i, int j)\n"
16864                "{\n"
16865                "  auto x = i + j;\n"
16866                "  auto y = i * j;\n"
16867                "  return x ^ y;\n"
16868                "};\n"
16869                "void foo()\n"
16870                "{\n"
16871                "  auto shortLambda = [](int i) { return i + 2; };\n"
16872                "  auto longLambda = [](int i, int j)\n"
16873                "  {\n"
16874                "    auto x = i + j;\n"
16875                "    auto y = i * j;\n"
16876                "    return x ^ y;\n"
16877                "  };\n"
16878                "}",
16879                AllmanBraceStyle);
16880 
16881   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
16882 
16883   verifyFormat("[](int i)\n"
16884                "{\n"
16885                "  return i + 2;\n"
16886                "};\n"
16887                "[](int i, int j)\n"
16888                "{\n"
16889                "  auto x = i + j;\n"
16890                "  auto y = i * j;\n"
16891                "  return x ^ y;\n"
16892                "};\n"
16893                "void foo()\n"
16894                "{\n"
16895                "  auto shortLambda = [](int i)\n"
16896                "  {\n"
16897                "    return i + 2;\n"
16898                "  };\n"
16899                "  auto longLambda = [](int i, int j)\n"
16900                "  {\n"
16901                "    auto x = i + j;\n"
16902                "    auto y = i * j;\n"
16903                "    return x ^ y;\n"
16904                "  };\n"
16905                "}",
16906                AllmanBraceStyle);
16907 
16908   // Reset
16909   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
16910 
16911   // This shouldn't affect ObjC blocks..
16912   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
16913                "  // ...\n"
16914                "  int i;\n"
16915                "}];",
16916                AllmanBraceStyle);
16917   verifyFormat("void (^block)(void) = ^{\n"
16918                "  // ...\n"
16919                "  int i;\n"
16920                "};",
16921                AllmanBraceStyle);
16922   // .. or dict literals.
16923   verifyFormat("void f()\n"
16924                "{\n"
16925                "  // ...\n"
16926                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
16927                "}",
16928                AllmanBraceStyle);
16929   verifyFormat("void f()\n"
16930                "{\n"
16931                "  // ...\n"
16932                "  [object someMethod:@{a : @\"b\"}];\n"
16933                "}",
16934                AllmanBraceStyle);
16935   verifyFormat("int f()\n"
16936                "{ // comment\n"
16937                "  return 42;\n"
16938                "}",
16939                AllmanBraceStyle);
16940 
16941   AllmanBraceStyle.ColumnLimit = 19;
16942   verifyFormat("void f() { int i; }", AllmanBraceStyle);
16943   AllmanBraceStyle.ColumnLimit = 18;
16944   verifyFormat("void f()\n"
16945                "{\n"
16946                "  int i;\n"
16947                "}",
16948                AllmanBraceStyle);
16949   AllmanBraceStyle.ColumnLimit = 80;
16950 
16951   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
16952   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
16953       FormatStyle::SIS_WithoutElse;
16954   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
16955   verifyFormat("void f(bool b)\n"
16956                "{\n"
16957                "  if (b)\n"
16958                "  {\n"
16959                "    return;\n"
16960                "  }\n"
16961                "}\n",
16962                BreakBeforeBraceShortIfs);
16963   verifyFormat("void f(bool b)\n"
16964                "{\n"
16965                "  if constexpr (b)\n"
16966                "  {\n"
16967                "    return;\n"
16968                "  }\n"
16969                "}\n",
16970                BreakBeforeBraceShortIfs);
16971   verifyFormat("void f(bool b)\n"
16972                "{\n"
16973                "  if CONSTEXPR (b)\n"
16974                "  {\n"
16975                "    return;\n"
16976                "  }\n"
16977                "}\n",
16978                BreakBeforeBraceShortIfs);
16979   verifyFormat("void f(bool b)\n"
16980                "{\n"
16981                "  if (b) return;\n"
16982                "}\n",
16983                BreakBeforeBraceShortIfs);
16984   verifyFormat("void f(bool b)\n"
16985                "{\n"
16986                "  if constexpr (b) return;\n"
16987                "}\n",
16988                BreakBeforeBraceShortIfs);
16989   verifyFormat("void f(bool b)\n"
16990                "{\n"
16991                "  if CONSTEXPR (b) return;\n"
16992                "}\n",
16993                BreakBeforeBraceShortIfs);
16994   verifyFormat("void f(bool b)\n"
16995                "{\n"
16996                "  while (b)\n"
16997                "  {\n"
16998                "    return;\n"
16999                "  }\n"
17000                "}\n",
17001                BreakBeforeBraceShortIfs);
17002 }
17003 
17004 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
17005   FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
17006   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
17007 
17008   // Make a few changes to the style for testing purposes
17009   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
17010       FormatStyle::SFS_Empty;
17011   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17012   WhitesmithsBraceStyle.ColumnLimit = 0;
17013 
17014   // FIXME: this test case can't decide whether there should be a blank line
17015   // after the ~D() line or not. It adds one if one doesn't exist in the test
17016   // and it removes the line if one exists.
17017   /*
17018   verifyFormat("class A;\n"
17019                "namespace B\n"
17020                "  {\n"
17021                "class C;\n"
17022                "// Comment\n"
17023                "class D\n"
17024                "  {\n"
17025                "public:\n"
17026                "  D();\n"
17027                "  ~D() {}\n"
17028                "private:\n"
17029                "  enum E\n"
17030                "    {\n"
17031                "    F\n"
17032                "    }\n"
17033                "  };\n"
17034                "  } // namespace B\n",
17035                WhitesmithsBraceStyle);
17036   */
17037 
17038   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
17039   verifyFormat("namespace a\n"
17040                "  {\n"
17041                "class A\n"
17042                "  {\n"
17043                "  void f()\n"
17044                "    {\n"
17045                "    if (true)\n"
17046                "      {\n"
17047                "      a();\n"
17048                "      b();\n"
17049                "      }\n"
17050                "    }\n"
17051                "  void g()\n"
17052                "    {\n"
17053                "    return;\n"
17054                "    }\n"
17055                "  };\n"
17056                "struct B\n"
17057                "  {\n"
17058                "  int x;\n"
17059                "  };\n"
17060                "  } // namespace a",
17061                WhitesmithsBraceStyle);
17062 
17063   verifyFormat("namespace a\n"
17064                "  {\n"
17065                "namespace b\n"
17066                "  {\n"
17067                "class A\n"
17068                "  {\n"
17069                "  void f()\n"
17070                "    {\n"
17071                "    if (true)\n"
17072                "      {\n"
17073                "      a();\n"
17074                "      b();\n"
17075                "      }\n"
17076                "    }\n"
17077                "  void g()\n"
17078                "    {\n"
17079                "    return;\n"
17080                "    }\n"
17081                "  };\n"
17082                "struct B\n"
17083                "  {\n"
17084                "  int x;\n"
17085                "  };\n"
17086                "  } // namespace b\n"
17087                "  } // namespace a",
17088                WhitesmithsBraceStyle);
17089 
17090   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
17091   verifyFormat("namespace a\n"
17092                "  {\n"
17093                "namespace b\n"
17094                "  {\n"
17095                "  class A\n"
17096                "    {\n"
17097                "    void f()\n"
17098                "      {\n"
17099                "      if (true)\n"
17100                "        {\n"
17101                "        a();\n"
17102                "        b();\n"
17103                "        }\n"
17104                "      }\n"
17105                "    void g()\n"
17106                "      {\n"
17107                "      return;\n"
17108                "      }\n"
17109                "    };\n"
17110                "  struct B\n"
17111                "    {\n"
17112                "    int x;\n"
17113                "    };\n"
17114                "  } // namespace b\n"
17115                "  } // namespace a",
17116                WhitesmithsBraceStyle);
17117 
17118   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
17119   verifyFormat("namespace a\n"
17120                "  {\n"
17121                "  namespace b\n"
17122                "    {\n"
17123                "    class A\n"
17124                "      {\n"
17125                "      void f()\n"
17126                "        {\n"
17127                "        if (true)\n"
17128                "          {\n"
17129                "          a();\n"
17130                "          b();\n"
17131                "          }\n"
17132                "        }\n"
17133                "      void g()\n"
17134                "        {\n"
17135                "        return;\n"
17136                "        }\n"
17137                "      };\n"
17138                "    struct B\n"
17139                "      {\n"
17140                "      int x;\n"
17141                "      };\n"
17142                "    } // namespace b\n"
17143                "  }   // namespace a",
17144                WhitesmithsBraceStyle);
17145 
17146   verifyFormat("void f()\n"
17147                "  {\n"
17148                "  if (true)\n"
17149                "    {\n"
17150                "    a();\n"
17151                "    }\n"
17152                "  else if (false)\n"
17153                "    {\n"
17154                "    b();\n"
17155                "    }\n"
17156                "  else\n"
17157                "    {\n"
17158                "    c();\n"
17159                "    }\n"
17160                "  }\n",
17161                WhitesmithsBraceStyle);
17162 
17163   verifyFormat("void f()\n"
17164                "  {\n"
17165                "  for (int i = 0; i < 10; ++i)\n"
17166                "    {\n"
17167                "    a();\n"
17168                "    }\n"
17169                "  while (false)\n"
17170                "    {\n"
17171                "    b();\n"
17172                "    }\n"
17173                "  do\n"
17174                "    {\n"
17175                "    c();\n"
17176                "    } while (false)\n"
17177                "  }\n",
17178                WhitesmithsBraceStyle);
17179 
17180   WhitesmithsBraceStyle.IndentCaseLabels = true;
17181   verifyFormat("void switchTest1(int a)\n"
17182                "  {\n"
17183                "  switch (a)\n"
17184                "    {\n"
17185                "    case 2:\n"
17186                "      {\n"
17187                "      }\n"
17188                "      break;\n"
17189                "    }\n"
17190                "  }\n",
17191                WhitesmithsBraceStyle);
17192 
17193   verifyFormat("void switchTest2(int a)\n"
17194                "  {\n"
17195                "  switch (a)\n"
17196                "    {\n"
17197                "    case 0:\n"
17198                "      break;\n"
17199                "    case 1:\n"
17200                "      {\n"
17201                "      break;\n"
17202                "      }\n"
17203                "    case 2:\n"
17204                "      {\n"
17205                "      }\n"
17206                "      break;\n"
17207                "    default:\n"
17208                "      break;\n"
17209                "    }\n"
17210                "  }\n",
17211                WhitesmithsBraceStyle);
17212 
17213   verifyFormat("void switchTest3(int a)\n"
17214                "  {\n"
17215                "  switch (a)\n"
17216                "    {\n"
17217                "    case 0:\n"
17218                "      {\n"
17219                "      foo(x);\n"
17220                "      }\n"
17221                "      break;\n"
17222                "    default:\n"
17223                "      {\n"
17224                "      foo(1);\n"
17225                "      }\n"
17226                "      break;\n"
17227                "    }\n"
17228                "  }\n",
17229                WhitesmithsBraceStyle);
17230 
17231   WhitesmithsBraceStyle.IndentCaseLabels = false;
17232 
17233   verifyFormat("void switchTest4(int a)\n"
17234                "  {\n"
17235                "  switch (a)\n"
17236                "    {\n"
17237                "  case 2:\n"
17238                "    {\n"
17239                "    }\n"
17240                "    break;\n"
17241                "    }\n"
17242                "  }\n",
17243                WhitesmithsBraceStyle);
17244 
17245   verifyFormat("void switchTest5(int a)\n"
17246                "  {\n"
17247                "  switch (a)\n"
17248                "    {\n"
17249                "  case 0:\n"
17250                "    break;\n"
17251                "  case 1:\n"
17252                "    {\n"
17253                "    foo();\n"
17254                "    break;\n"
17255                "    }\n"
17256                "  case 2:\n"
17257                "    {\n"
17258                "    }\n"
17259                "    break;\n"
17260                "  default:\n"
17261                "    break;\n"
17262                "    }\n"
17263                "  }\n",
17264                WhitesmithsBraceStyle);
17265 
17266   verifyFormat("void switchTest6(int a)\n"
17267                "  {\n"
17268                "  switch (a)\n"
17269                "    {\n"
17270                "  case 0:\n"
17271                "    {\n"
17272                "    foo(x);\n"
17273                "    }\n"
17274                "    break;\n"
17275                "  default:\n"
17276                "    {\n"
17277                "    foo(1);\n"
17278                "    }\n"
17279                "    break;\n"
17280                "    }\n"
17281                "  }\n",
17282                WhitesmithsBraceStyle);
17283 
17284   verifyFormat("enum X\n"
17285                "  {\n"
17286                "  Y = 0, // testing\n"
17287                "  }\n",
17288                WhitesmithsBraceStyle);
17289 
17290   verifyFormat("enum X\n"
17291                "  {\n"
17292                "  Y = 0\n"
17293                "  }\n",
17294                WhitesmithsBraceStyle);
17295   verifyFormat("enum X\n"
17296                "  {\n"
17297                "  Y = 0,\n"
17298                "  Z = 1\n"
17299                "  };\n",
17300                WhitesmithsBraceStyle);
17301 
17302   verifyFormat("@interface BSApplicationController ()\n"
17303                "  {\n"
17304                "@private\n"
17305                "  id _extraIvar;\n"
17306                "  }\n"
17307                "@end\n",
17308                WhitesmithsBraceStyle);
17309 
17310   verifyFormat("#ifdef _DEBUG\n"
17311                "int foo(int i = 0)\n"
17312                "#else\n"
17313                "int foo(int i = 5)\n"
17314                "#endif\n"
17315                "  {\n"
17316                "  return i;\n"
17317                "  }",
17318                WhitesmithsBraceStyle);
17319 
17320   verifyFormat("void foo() {}\n"
17321                "void bar()\n"
17322                "#ifdef _DEBUG\n"
17323                "  {\n"
17324                "  foo();\n"
17325                "  }\n"
17326                "#else\n"
17327                "  {\n"
17328                "  }\n"
17329                "#endif",
17330                WhitesmithsBraceStyle);
17331 
17332   verifyFormat("void foobar()\n"
17333                "  {\n"
17334                "  int i = 5;\n"
17335                "  }\n"
17336                "#ifdef _DEBUG\n"
17337                "void bar()\n"
17338                "  {\n"
17339                "  }\n"
17340                "#else\n"
17341                "void bar()\n"
17342                "  {\n"
17343                "  foobar();\n"
17344                "  }\n"
17345                "#endif",
17346                WhitesmithsBraceStyle);
17347 
17348   // This shouldn't affect ObjC blocks..
17349   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17350                "  // ...\n"
17351                "  int i;\n"
17352                "}];",
17353                WhitesmithsBraceStyle);
17354   verifyFormat("void (^block)(void) = ^{\n"
17355                "  // ...\n"
17356                "  int i;\n"
17357                "};",
17358                WhitesmithsBraceStyle);
17359   // .. or dict literals.
17360   verifyFormat("void f()\n"
17361                "  {\n"
17362                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
17363                "  }",
17364                WhitesmithsBraceStyle);
17365 
17366   verifyFormat("int f()\n"
17367                "  { // comment\n"
17368                "  return 42;\n"
17369                "  }",
17370                WhitesmithsBraceStyle);
17371 
17372   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
17373   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17374       FormatStyle::SIS_OnlyFirstIf;
17375   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17376   verifyFormat("void f(bool b)\n"
17377                "  {\n"
17378                "  if (b)\n"
17379                "    {\n"
17380                "    return;\n"
17381                "    }\n"
17382                "  }\n",
17383                BreakBeforeBraceShortIfs);
17384   verifyFormat("void f(bool b)\n"
17385                "  {\n"
17386                "  if (b) return;\n"
17387                "  }\n",
17388                BreakBeforeBraceShortIfs);
17389   verifyFormat("void f(bool b)\n"
17390                "  {\n"
17391                "  while (b)\n"
17392                "    {\n"
17393                "    return;\n"
17394                "    }\n"
17395                "  }\n",
17396                BreakBeforeBraceShortIfs);
17397 }
17398 
17399 TEST_F(FormatTest, GNUBraceBreaking) {
17400   FormatStyle GNUBraceStyle = getLLVMStyle();
17401   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
17402   verifyFormat("namespace a\n"
17403                "{\n"
17404                "class A\n"
17405                "{\n"
17406                "  void f()\n"
17407                "  {\n"
17408                "    int a;\n"
17409                "    {\n"
17410                "      int b;\n"
17411                "    }\n"
17412                "    if (true)\n"
17413                "      {\n"
17414                "        a();\n"
17415                "        b();\n"
17416                "      }\n"
17417                "  }\n"
17418                "  void g() { return; }\n"
17419                "}\n"
17420                "} // namespace a",
17421                GNUBraceStyle);
17422 
17423   verifyFormat("void f()\n"
17424                "{\n"
17425                "  if (true)\n"
17426                "    {\n"
17427                "      a();\n"
17428                "    }\n"
17429                "  else if (false)\n"
17430                "    {\n"
17431                "      b();\n"
17432                "    }\n"
17433                "  else\n"
17434                "    {\n"
17435                "      c();\n"
17436                "    }\n"
17437                "}\n",
17438                GNUBraceStyle);
17439 
17440   verifyFormat("void f()\n"
17441                "{\n"
17442                "  for (int i = 0; i < 10; ++i)\n"
17443                "    {\n"
17444                "      a();\n"
17445                "    }\n"
17446                "  while (false)\n"
17447                "    {\n"
17448                "      b();\n"
17449                "    }\n"
17450                "  do\n"
17451                "    {\n"
17452                "      c();\n"
17453                "    }\n"
17454                "  while (false);\n"
17455                "}\n",
17456                GNUBraceStyle);
17457 
17458   verifyFormat("void f(int a)\n"
17459                "{\n"
17460                "  switch (a)\n"
17461                "    {\n"
17462                "    case 0:\n"
17463                "      break;\n"
17464                "    case 1:\n"
17465                "      {\n"
17466                "        break;\n"
17467                "      }\n"
17468                "    case 2:\n"
17469                "      {\n"
17470                "      }\n"
17471                "      break;\n"
17472                "    default:\n"
17473                "      break;\n"
17474                "    }\n"
17475                "}\n",
17476                GNUBraceStyle);
17477 
17478   verifyFormat("enum X\n"
17479                "{\n"
17480                "  Y = 0,\n"
17481                "}\n",
17482                GNUBraceStyle);
17483 
17484   verifyFormat("@interface BSApplicationController ()\n"
17485                "{\n"
17486                "@private\n"
17487                "  id _extraIvar;\n"
17488                "}\n"
17489                "@end\n",
17490                GNUBraceStyle);
17491 
17492   verifyFormat("#ifdef _DEBUG\n"
17493                "int foo(int i = 0)\n"
17494                "#else\n"
17495                "int foo(int i = 5)\n"
17496                "#endif\n"
17497                "{\n"
17498                "  return i;\n"
17499                "}",
17500                GNUBraceStyle);
17501 
17502   verifyFormat("void foo() {}\n"
17503                "void bar()\n"
17504                "#ifdef _DEBUG\n"
17505                "{\n"
17506                "  foo();\n"
17507                "}\n"
17508                "#else\n"
17509                "{\n"
17510                "}\n"
17511                "#endif",
17512                GNUBraceStyle);
17513 
17514   verifyFormat("void foobar() { int i = 5; }\n"
17515                "#ifdef _DEBUG\n"
17516                "void bar() {}\n"
17517                "#else\n"
17518                "void bar() { foobar(); }\n"
17519                "#endif",
17520                GNUBraceStyle);
17521 }
17522 
17523 TEST_F(FormatTest, WebKitBraceBreaking) {
17524   FormatStyle WebKitBraceStyle = getLLVMStyle();
17525   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
17526   WebKitBraceStyle.FixNamespaceComments = false;
17527   verifyFormat("namespace a {\n"
17528                "class A {\n"
17529                "  void f()\n"
17530                "  {\n"
17531                "    if (true) {\n"
17532                "      a();\n"
17533                "      b();\n"
17534                "    }\n"
17535                "  }\n"
17536                "  void g() { return; }\n"
17537                "};\n"
17538                "enum E {\n"
17539                "  A,\n"
17540                "  // foo\n"
17541                "  B,\n"
17542                "  C\n"
17543                "};\n"
17544                "struct B {\n"
17545                "  int x;\n"
17546                "};\n"
17547                "}\n",
17548                WebKitBraceStyle);
17549   verifyFormat("struct S {\n"
17550                "  int Type;\n"
17551                "  union {\n"
17552                "    int x;\n"
17553                "    double y;\n"
17554                "  } Value;\n"
17555                "  class C {\n"
17556                "    MyFavoriteType Value;\n"
17557                "  } Class;\n"
17558                "};\n",
17559                WebKitBraceStyle);
17560 }
17561 
17562 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
17563   verifyFormat("void f() {\n"
17564                "  try {\n"
17565                "  } catch (const Exception &e) {\n"
17566                "  }\n"
17567                "}\n",
17568                getLLVMStyle());
17569 }
17570 
17571 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
17572   auto Style = getLLVMStyle();
17573   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
17574   Style.AlignConsecutiveAssignments =
17575       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17576   Style.AlignConsecutiveDeclarations =
17577       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17578   verifyFormat("struct test demo[] = {\n"
17579                "    {56,    23, \"hello\"},\n"
17580                "    {-1, 93463, \"world\"},\n"
17581                "    { 7,     5,    \"!!\"}\n"
17582                "};\n",
17583                Style);
17584 
17585   verifyFormat("struct test demo[] = {\n"
17586                "    {56,    23, \"hello\"}, // first line\n"
17587                "    {-1, 93463, \"world\"}, // second line\n"
17588                "    { 7,     5,    \"!!\"}  // third line\n"
17589                "};\n",
17590                Style);
17591 
17592   verifyFormat("struct test demo[4] = {\n"
17593                "    { 56,    23, 21,       \"oh\"}, // first line\n"
17594                "    { -1, 93463, 22,       \"my\"}, // second line\n"
17595                "    {  7,     5,  1, \"goodness\"}  // third line\n"
17596                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
17597                "};\n",
17598                Style);
17599 
17600   verifyFormat("struct test demo[3] = {\n"
17601                "    {56,    23, \"hello\"},\n"
17602                "    {-1, 93463, \"world\"},\n"
17603                "    { 7,     5,    \"!!\"}\n"
17604                "};\n",
17605                Style);
17606 
17607   verifyFormat("struct test demo[3] = {\n"
17608                "    {int{56},    23, \"hello\"},\n"
17609                "    {int{-1}, 93463, \"world\"},\n"
17610                "    { int{7},     5,    \"!!\"}\n"
17611                "};\n",
17612                Style);
17613 
17614   verifyFormat("struct test demo[] = {\n"
17615                "    {56,    23, \"hello\"},\n"
17616                "    {-1, 93463, \"world\"},\n"
17617                "    { 7,     5,    \"!!\"},\n"
17618                "};\n",
17619                Style);
17620 
17621   verifyFormat("test demo[] = {\n"
17622                "    {56,    23, \"hello\"},\n"
17623                "    {-1, 93463, \"world\"},\n"
17624                "    { 7,     5,    \"!!\"},\n"
17625                "};\n",
17626                Style);
17627 
17628   verifyFormat("demo = std::array<struct test, 3>{\n"
17629                "    test{56,    23, \"hello\"},\n"
17630                "    test{-1, 93463, \"world\"},\n"
17631                "    test{ 7,     5,    \"!!\"},\n"
17632                "};\n",
17633                Style);
17634 
17635   verifyFormat("test demo[] = {\n"
17636                "    {56,    23, \"hello\"},\n"
17637                "#if X\n"
17638                "    {-1, 93463, \"world\"},\n"
17639                "#endif\n"
17640                "    { 7,     5,    \"!!\"}\n"
17641                "};\n",
17642                Style);
17643 
17644   verifyFormat(
17645       "test demo[] = {\n"
17646       "    { 7,    23,\n"
17647       "     \"hello world i am a very long line that really, in any\"\n"
17648       "     \"just world, ought to be split over multiple lines\"},\n"
17649       "    {-1, 93463,                                  \"world\"},\n"
17650       "    {56,     5,                                     \"!!\"}\n"
17651       "};\n",
17652       Style);
17653 
17654   verifyFormat("return GradForUnaryCwise(g, {\n"
17655                "                                {{\"sign\"}, \"Sign\",  "
17656                "  {\"x\", \"dy\"}},\n"
17657                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
17658                ", \"sign\"}},\n"
17659                "});\n",
17660                Style);
17661 
17662   Style.ColumnLimit = 0;
17663   EXPECT_EQ(
17664       "test demo[] = {\n"
17665       "    {56,    23, \"hello world i am a very long line that really, "
17666       "in any just world, ought to be split over multiple lines\"},\n"
17667       "    {-1, 93463,                                                  "
17668       "                                                 \"world\"},\n"
17669       "    { 7,     5,                                                  "
17670       "                                                    \"!!\"},\n"
17671       "};",
17672       format("test demo[] = {{56, 23, \"hello world i am a very long line "
17673              "that really, in any just world, ought to be split over multiple "
17674              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17675              Style));
17676 
17677   Style.ColumnLimit = 80;
17678   verifyFormat("test demo[] = {\n"
17679                "    {56,    23, /* a comment */ \"hello\"},\n"
17680                "    {-1, 93463,                 \"world\"},\n"
17681                "    { 7,     5,                    \"!!\"}\n"
17682                "};\n",
17683                Style);
17684 
17685   verifyFormat("test demo[] = {\n"
17686                "    {56,    23,                    \"hello\"},\n"
17687                "    {-1, 93463, \"world\" /* comment here */},\n"
17688                "    { 7,     5,                       \"!!\"}\n"
17689                "};\n",
17690                Style);
17691 
17692   verifyFormat("test demo[] = {\n"
17693                "    {56, /* a comment */ 23, \"hello\"},\n"
17694                "    {-1,              93463, \"world\"},\n"
17695                "    { 7,                  5,    \"!!\"}\n"
17696                "};\n",
17697                Style);
17698 
17699   Style.ColumnLimit = 20;
17700   EXPECT_EQ(
17701       "demo = std::array<\n"
17702       "    struct test, 3>{\n"
17703       "    test{\n"
17704       "         56,    23,\n"
17705       "         \"hello \"\n"
17706       "         \"world i \"\n"
17707       "         \"am a very \"\n"
17708       "         \"long line \"\n"
17709       "         \"that \"\n"
17710       "         \"really, \"\n"
17711       "         \"in any \"\n"
17712       "         \"just \"\n"
17713       "         \"world, \"\n"
17714       "         \"ought to \"\n"
17715       "         \"be split \"\n"
17716       "         \"over \"\n"
17717       "         \"multiple \"\n"
17718       "         \"lines\"},\n"
17719       "    test{-1, 93463,\n"
17720       "         \"world\"},\n"
17721       "    test{ 7,     5,\n"
17722       "         \"!!\"   },\n"
17723       "};",
17724       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
17725              "i am a very long line that really, in any just world, ought "
17726              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
17727              "test{7, 5, \"!!\"},};",
17728              Style));
17729   // This caused a core dump by enabling Alignment in the LLVMStyle globally
17730   Style = getLLVMStyleWithColumns(50);
17731   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
17732   verifyFormat("static A x = {\n"
17733                "    {{init1, init2, init3, init4},\n"
17734                "     {init1, init2, init3, init4}}\n"
17735                "};",
17736                Style);
17737   Style.ColumnLimit = 100;
17738   EXPECT_EQ(
17739       "test demo[] = {\n"
17740       "    {56,    23,\n"
17741       "     \"hello world i am a very long line that really, in any just world"
17742       ", ought to be split over \"\n"
17743       "     \"multiple lines\"  },\n"
17744       "    {-1, 93463, \"world\"},\n"
17745       "    { 7,     5,    \"!!\"},\n"
17746       "};",
17747       format("test demo[] = {{56, 23, \"hello world i am a very long line "
17748              "that really, in any just world, ought to be split over multiple "
17749              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17750              Style));
17751 
17752   Style = getLLVMStyleWithColumns(50);
17753   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
17754   Style.AlignConsecutiveAssignments =
17755       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17756   Style.AlignConsecutiveDeclarations =
17757       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17758   verifyFormat("struct test demo[] = {\n"
17759                "    {56,    23, \"hello\"},\n"
17760                "    {-1, 93463, \"world\"},\n"
17761                "    { 7,     5,    \"!!\"}\n"
17762                "};\n"
17763                "static A x = {\n"
17764                "    {{init1, init2, init3, init4},\n"
17765                "     {init1, init2, init3, init4}}\n"
17766                "};",
17767                Style);
17768   Style.ColumnLimit = 100;
17769   Style.AlignConsecutiveAssignments =
17770       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
17771   Style.AlignConsecutiveDeclarations =
17772       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
17773   verifyFormat("struct test demo[] = {\n"
17774                "    {56,    23, \"hello\"},\n"
17775                "    {-1, 93463, \"world\"},\n"
17776                "    { 7,     5,    \"!!\"}\n"
17777                "};\n"
17778                "struct test demo[4] = {\n"
17779                "    { 56,    23, 21,       \"oh\"}, // first line\n"
17780                "    { -1, 93463, 22,       \"my\"}, // second line\n"
17781                "    {  7,     5,  1, \"goodness\"}  // third line\n"
17782                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
17783                "};\n",
17784                Style);
17785   EXPECT_EQ(
17786       "test demo[] = {\n"
17787       "    {56,\n"
17788       "     \"hello world i am a very long line that really, in any just world"
17789       ", ought to be split over \"\n"
17790       "     \"multiple lines\",    23},\n"
17791       "    {-1,      \"world\", 93463},\n"
17792       "    { 7,         \"!!\",     5},\n"
17793       "};",
17794       format("test demo[] = {{56, \"hello world i am a very long line "
17795              "that really, in any just world, ought to be split over multiple "
17796              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
17797              Style));
17798 }
17799 
17800 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
17801   auto Style = getLLVMStyle();
17802   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
17803   verifyFormat("struct test demo[] = {\n"
17804                "    {56, 23,    \"hello\"},\n"
17805                "    {-1, 93463, \"world\"},\n"
17806                "    {7,  5,     \"!!\"   }\n"
17807                "};\n",
17808                Style);
17809 
17810   verifyFormat("struct test demo[] = {\n"
17811                "    {56, 23,    \"hello\"}, // first line\n"
17812                "    {-1, 93463, \"world\"}, // second line\n"
17813                "    {7,  5,     \"!!\"   }  // third line\n"
17814                "};\n",
17815                Style);
17816   verifyFormat("struct test demo[4] = {\n"
17817                "    {56,  23,    21, \"oh\"      }, // first line\n"
17818                "    {-1,  93463, 22, \"my\"      }, // second line\n"
17819                "    {7,   5,     1,  \"goodness\"}  // third line\n"
17820                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
17821                "};\n",
17822                Style);
17823   verifyFormat("struct test demo[3] = {\n"
17824                "    {56, 23,    \"hello\"},\n"
17825                "    {-1, 93463, \"world\"},\n"
17826                "    {7,  5,     \"!!\"   }\n"
17827                "};\n",
17828                Style);
17829 
17830   verifyFormat("struct test demo[3] = {\n"
17831                "    {int{56}, 23,    \"hello\"},\n"
17832                "    {int{-1}, 93463, \"world\"},\n"
17833                "    {int{7},  5,     \"!!\"   }\n"
17834                "};\n",
17835                Style);
17836   verifyFormat("struct test demo[] = {\n"
17837                "    {56, 23,    \"hello\"},\n"
17838                "    {-1, 93463, \"world\"},\n"
17839                "    {7,  5,     \"!!\"   },\n"
17840                "};\n",
17841                Style);
17842   verifyFormat("test demo[] = {\n"
17843                "    {56, 23,    \"hello\"},\n"
17844                "    {-1, 93463, \"world\"},\n"
17845                "    {7,  5,     \"!!\"   },\n"
17846                "};\n",
17847                Style);
17848   verifyFormat("demo = std::array<struct test, 3>{\n"
17849                "    test{56, 23,    \"hello\"},\n"
17850                "    test{-1, 93463, \"world\"},\n"
17851                "    test{7,  5,     \"!!\"   },\n"
17852                "};\n",
17853                Style);
17854   verifyFormat("test demo[] = {\n"
17855                "    {56, 23,    \"hello\"},\n"
17856                "#if X\n"
17857                "    {-1, 93463, \"world\"},\n"
17858                "#endif\n"
17859                "    {7,  5,     \"!!\"   }\n"
17860                "};\n",
17861                Style);
17862   verifyFormat(
17863       "test demo[] = {\n"
17864       "    {7,  23,\n"
17865       "     \"hello world i am a very long line that really, in any\"\n"
17866       "     \"just world, ought to be split over multiple lines\"},\n"
17867       "    {-1, 93463, \"world\"                                 },\n"
17868       "    {56, 5,     \"!!\"                                    }\n"
17869       "};\n",
17870       Style);
17871 
17872   verifyFormat("return GradForUnaryCwise(g, {\n"
17873                "                                {{\"sign\"}, \"Sign\", {\"x\", "
17874                "\"dy\"}   },\n"
17875                "                                {{\"dx\"},   \"Mul\",  "
17876                "{\"dy\", \"sign\"}},\n"
17877                "});\n",
17878                Style);
17879 
17880   Style.ColumnLimit = 0;
17881   EXPECT_EQ(
17882       "test demo[] = {\n"
17883       "    {56, 23,    \"hello world i am a very long line that really, in any "
17884       "just world, ought to be split over multiple lines\"},\n"
17885       "    {-1, 93463, \"world\"                                               "
17886       "                                                   },\n"
17887       "    {7,  5,     \"!!\"                                                  "
17888       "                                                   },\n"
17889       "};",
17890       format("test demo[] = {{56, 23, \"hello world i am a very long line "
17891              "that really, in any just world, ought to be split over multiple "
17892              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17893              Style));
17894 
17895   Style.ColumnLimit = 80;
17896   verifyFormat("test demo[] = {\n"
17897                "    {56, 23,    /* a comment */ \"hello\"},\n"
17898                "    {-1, 93463, \"world\"                },\n"
17899                "    {7,  5,     \"!!\"                   }\n"
17900                "};\n",
17901                Style);
17902 
17903   verifyFormat("test demo[] = {\n"
17904                "    {56, 23,    \"hello\"                   },\n"
17905                "    {-1, 93463, \"world\" /* comment here */},\n"
17906                "    {7,  5,     \"!!\"                      }\n"
17907                "};\n",
17908                Style);
17909 
17910   verifyFormat("test demo[] = {\n"
17911                "    {56, /* a comment */ 23, \"hello\"},\n"
17912                "    {-1, 93463,              \"world\"},\n"
17913                "    {7,  5,                  \"!!\"   }\n"
17914                "};\n",
17915                Style);
17916 
17917   Style.ColumnLimit = 20;
17918   EXPECT_EQ(
17919       "demo = std::array<\n"
17920       "    struct test, 3>{\n"
17921       "    test{\n"
17922       "         56, 23,\n"
17923       "         \"hello \"\n"
17924       "         \"world i \"\n"
17925       "         \"am a very \"\n"
17926       "         \"long line \"\n"
17927       "         \"that \"\n"
17928       "         \"really, \"\n"
17929       "         \"in any \"\n"
17930       "         \"just \"\n"
17931       "         \"world, \"\n"
17932       "         \"ought to \"\n"
17933       "         \"be split \"\n"
17934       "         \"over \"\n"
17935       "         \"multiple \"\n"
17936       "         \"lines\"},\n"
17937       "    test{-1, 93463,\n"
17938       "         \"world\"},\n"
17939       "    test{7,  5,\n"
17940       "         \"!!\"   },\n"
17941       "};",
17942       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
17943              "i am a very long line that really, in any just world, ought "
17944              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
17945              "test{7, 5, \"!!\"},};",
17946              Style));
17947 
17948   // This caused a core dump by enabling Alignment in the LLVMStyle globally
17949   Style = getLLVMStyleWithColumns(50);
17950   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
17951   verifyFormat("static A x = {\n"
17952                "    {{init1, init2, init3, init4},\n"
17953                "     {init1, init2, init3, init4}}\n"
17954                "};",
17955                Style);
17956   Style.ColumnLimit = 100;
17957   EXPECT_EQ(
17958       "test demo[] = {\n"
17959       "    {56, 23,\n"
17960       "     \"hello world i am a very long line that really, in any just world"
17961       ", ought to be split over \"\n"
17962       "     \"multiple lines\"  },\n"
17963       "    {-1, 93463, \"world\"},\n"
17964       "    {7,  5,     \"!!\"   },\n"
17965       "};",
17966       format("test demo[] = {{56, 23, \"hello world i am a very long line "
17967              "that really, in any just world, ought to be split over multiple "
17968              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17969              Style));
17970 }
17971 
17972 TEST_F(FormatTest, UnderstandsPragmas) {
17973   verifyFormat("#pragma omp reduction(| : var)");
17974   verifyFormat("#pragma omp reduction(+ : var)");
17975 
17976   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
17977             "(including parentheses).",
17978             format("#pragma    mark   Any non-hyphenated or hyphenated string "
17979                    "(including parentheses)."));
17980 }
17981 
17982 TEST_F(FormatTest, UnderstandPragmaOption) {
17983   verifyFormat("#pragma option -C -A");
17984 
17985   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
17986 }
17987 
17988 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
17989   FormatStyle Style = getLLVMStyle();
17990   Style.ColumnLimit = 20;
17991 
17992   // See PR41213
17993   EXPECT_EQ("/*\n"
17994             " *\t9012345\n"
17995             " * /8901\n"
17996             " */",
17997             format("/*\n"
17998                    " *\t9012345 /8901\n"
17999                    " */",
18000                    Style));
18001   EXPECT_EQ("/*\n"
18002             " *345678\n"
18003             " *\t/8901\n"
18004             " */",
18005             format("/*\n"
18006                    " *345678\t/8901\n"
18007                    " */",
18008                    Style));
18009 
18010   verifyFormat("int a; // the\n"
18011                "       // comment",
18012                Style);
18013   EXPECT_EQ("int a; /* first line\n"
18014             "        * second\n"
18015             "        * line third\n"
18016             "        * line\n"
18017             "        */",
18018             format("int a; /* first line\n"
18019                    "        * second\n"
18020                    "        * line third\n"
18021                    "        * line\n"
18022                    "        */",
18023                    Style));
18024   EXPECT_EQ("int a; // first line\n"
18025             "       // second\n"
18026             "       // line third\n"
18027             "       // line",
18028             format("int a; // first line\n"
18029                    "       // second line\n"
18030                    "       // third line",
18031                    Style));
18032 
18033   Style.PenaltyExcessCharacter = 90;
18034   verifyFormat("int a; // the comment", Style);
18035   EXPECT_EQ("int a; // the comment\n"
18036             "       // aaa",
18037             format("int a; // the comment aaa", Style));
18038   EXPECT_EQ("int a; /* first line\n"
18039             "        * second line\n"
18040             "        * third line\n"
18041             "        */",
18042             format("int a; /* first line\n"
18043                    "        * second line\n"
18044                    "        * third line\n"
18045                    "        */",
18046                    Style));
18047   EXPECT_EQ("int a; // first line\n"
18048             "       // second line\n"
18049             "       // third line",
18050             format("int a; // first line\n"
18051                    "       // second line\n"
18052                    "       // third line",
18053                    Style));
18054   // FIXME: Investigate why this is not getting the same layout as the test
18055   // above.
18056   EXPECT_EQ("int a; /* first line\n"
18057             "        * second line\n"
18058             "        * third line\n"
18059             "        */",
18060             format("int a; /* first line second line third line"
18061                    "\n*/",
18062                    Style));
18063 
18064   EXPECT_EQ("// foo bar baz bazfoo\n"
18065             "// foo bar foo bar\n",
18066             format("// foo bar baz bazfoo\n"
18067                    "// foo bar foo           bar\n",
18068                    Style));
18069   EXPECT_EQ("// foo bar baz bazfoo\n"
18070             "// foo bar foo bar\n",
18071             format("// foo bar baz      bazfoo\n"
18072                    "// foo            bar foo bar\n",
18073                    Style));
18074 
18075   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
18076   // next one.
18077   EXPECT_EQ("// foo bar baz bazfoo\n"
18078             "// bar foo bar\n",
18079             format("// foo bar baz      bazfoo bar\n"
18080                    "// foo            bar\n",
18081                    Style));
18082 
18083   EXPECT_EQ("// foo bar baz bazfoo\n"
18084             "// foo bar baz bazfoo\n"
18085             "// bar foo bar\n",
18086             format("// foo bar baz      bazfoo\n"
18087                    "// foo bar baz      bazfoo bar\n"
18088                    "// foo bar\n",
18089                    Style));
18090 
18091   EXPECT_EQ("// foo bar baz bazfoo\n"
18092             "// foo bar baz bazfoo\n"
18093             "// bar foo bar\n",
18094             format("// foo bar baz      bazfoo\n"
18095                    "// foo bar baz      bazfoo bar\n"
18096                    "// foo           bar\n",
18097                    Style));
18098 
18099   // Make sure we do not keep protruding characters if strict mode reflow is
18100   // cheaper than keeping protruding characters.
18101   Style.ColumnLimit = 21;
18102   EXPECT_EQ(
18103       "// foo foo foo foo\n"
18104       "// foo foo foo foo\n"
18105       "// foo foo foo foo\n",
18106       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
18107 
18108   EXPECT_EQ("int a = /* long block\n"
18109             "           comment */\n"
18110             "    42;",
18111             format("int a = /* long block comment */ 42;", Style));
18112 }
18113 
18114 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
18115   for (size_t i = 1; i < Styles.size(); ++i)                                   \
18116   EXPECT_EQ(Styles[0], Styles[i])                                              \
18117       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
18118 
18119 TEST_F(FormatTest, GetsPredefinedStyleByName) {
18120   SmallVector<FormatStyle, 3> Styles;
18121   Styles.resize(3);
18122 
18123   Styles[0] = getLLVMStyle();
18124   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
18125   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
18126   EXPECT_ALL_STYLES_EQUAL(Styles);
18127 
18128   Styles[0] = getGoogleStyle();
18129   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
18130   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
18131   EXPECT_ALL_STYLES_EQUAL(Styles);
18132 
18133   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18134   EXPECT_TRUE(
18135       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
18136   EXPECT_TRUE(
18137       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
18138   EXPECT_ALL_STYLES_EQUAL(Styles);
18139 
18140   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
18141   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
18142   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
18143   EXPECT_ALL_STYLES_EQUAL(Styles);
18144 
18145   Styles[0] = getMozillaStyle();
18146   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
18147   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
18148   EXPECT_ALL_STYLES_EQUAL(Styles);
18149 
18150   Styles[0] = getWebKitStyle();
18151   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
18152   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
18153   EXPECT_ALL_STYLES_EQUAL(Styles);
18154 
18155   Styles[0] = getGNUStyle();
18156   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
18157   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
18158   EXPECT_ALL_STYLES_EQUAL(Styles);
18159 
18160   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
18161 }
18162 
18163 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
18164   SmallVector<FormatStyle, 8> Styles;
18165   Styles.resize(2);
18166 
18167   Styles[0] = getGoogleStyle();
18168   Styles[1] = getLLVMStyle();
18169   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18170   EXPECT_ALL_STYLES_EQUAL(Styles);
18171 
18172   Styles.resize(5);
18173   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18174   Styles[1] = getLLVMStyle();
18175   Styles[1].Language = FormatStyle::LK_JavaScript;
18176   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18177 
18178   Styles[2] = getLLVMStyle();
18179   Styles[2].Language = FormatStyle::LK_JavaScript;
18180   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
18181                                   "BasedOnStyle: Google",
18182                                   &Styles[2])
18183                    .value());
18184 
18185   Styles[3] = getLLVMStyle();
18186   Styles[3].Language = FormatStyle::LK_JavaScript;
18187   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
18188                                   "Language: JavaScript",
18189                                   &Styles[3])
18190                    .value());
18191 
18192   Styles[4] = getLLVMStyle();
18193   Styles[4].Language = FormatStyle::LK_JavaScript;
18194   EXPECT_EQ(0, parseConfiguration("---\n"
18195                                   "BasedOnStyle: LLVM\n"
18196                                   "IndentWidth: 123\n"
18197                                   "---\n"
18198                                   "BasedOnStyle: Google\n"
18199                                   "Language: JavaScript",
18200                                   &Styles[4])
18201                    .value());
18202   EXPECT_ALL_STYLES_EQUAL(Styles);
18203 }
18204 
18205 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
18206   Style.FIELD = false;                                                         \
18207   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
18208   EXPECT_TRUE(Style.FIELD);                                                    \
18209   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
18210   EXPECT_FALSE(Style.FIELD);
18211 
18212 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
18213 
18214 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
18215   Style.STRUCT.FIELD = false;                                                  \
18216   EXPECT_EQ(0,                                                                 \
18217             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
18218                 .value());                                                     \
18219   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
18220   EXPECT_EQ(0,                                                                 \
18221             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
18222                 .value());                                                     \
18223   EXPECT_FALSE(Style.STRUCT.FIELD);
18224 
18225 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
18226   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
18227 
18228 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
18229   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
18230   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
18231   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
18232 
18233 TEST_F(FormatTest, ParsesConfigurationBools) {
18234   FormatStyle Style = {};
18235   Style.Language = FormatStyle::LK_Cpp;
18236   CHECK_PARSE_BOOL(AlignTrailingComments);
18237   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
18238   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
18239   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
18240   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
18241   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
18242   CHECK_PARSE_BOOL(BinPackArguments);
18243   CHECK_PARSE_BOOL(BinPackParameters);
18244   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
18245   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
18246   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
18247   CHECK_PARSE_BOOL(BreakStringLiterals);
18248   CHECK_PARSE_BOOL(CompactNamespaces);
18249   CHECK_PARSE_BOOL(DeriveLineEnding);
18250   CHECK_PARSE_BOOL(DerivePointerAlignment);
18251   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
18252   CHECK_PARSE_BOOL(DisableFormat);
18253   CHECK_PARSE_BOOL(IndentAccessModifiers);
18254   CHECK_PARSE_BOOL(IndentCaseLabels);
18255   CHECK_PARSE_BOOL(IndentCaseBlocks);
18256   CHECK_PARSE_BOOL(IndentGotoLabels);
18257   CHECK_PARSE_BOOL(IndentRequires);
18258   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
18259   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
18260   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
18261   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
18262   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
18263   CHECK_PARSE_BOOL(ReflowComments);
18264   CHECK_PARSE_BOOL(SortUsingDeclarations);
18265   CHECK_PARSE_BOOL(SpacesInParentheses);
18266   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
18267   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
18268   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
18269   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
18270   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
18271   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
18272   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
18273   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
18274   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
18275   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
18276   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
18277   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
18278   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
18279   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
18280   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
18281   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
18282   CHECK_PARSE_BOOL(UseCRLF);
18283 
18284   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
18285   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
18286   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
18287   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
18288   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
18289   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
18290   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
18291   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
18292   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
18293   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
18294   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
18295   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
18296   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
18297   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
18298   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
18299   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
18300   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
18301 }
18302 
18303 #undef CHECK_PARSE_BOOL
18304 
18305 TEST_F(FormatTest, ParsesConfiguration) {
18306   FormatStyle Style = {};
18307   Style.Language = FormatStyle::LK_Cpp;
18308   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
18309   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
18310               ConstructorInitializerIndentWidth, 1234u);
18311   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
18312   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
18313   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
18314   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
18315   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
18316               PenaltyBreakBeforeFirstCallParameter, 1234u);
18317   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
18318               PenaltyBreakTemplateDeclaration, 1234u);
18319   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
18320   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
18321               PenaltyReturnTypeOnItsOwnLine, 1234u);
18322   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
18323               SpacesBeforeTrailingComments, 1234u);
18324   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
18325   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
18326   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
18327 
18328   Style.QualifierAlignment = FormatStyle::QAS_Right;
18329   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
18330               FormatStyle::QAS_Leave);
18331   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
18332               FormatStyle::QAS_Right);
18333   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
18334               FormatStyle::QAS_Left);
18335   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
18336               FormatStyle::QAS_Custom);
18337 
18338   Style.QualifierOrder.clear();
18339   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
18340               std::vector<std::string>({"const", "volatile", "type"}));
18341   Style.QualifierOrder.clear();
18342   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
18343               std::vector<std::string>({"const", "type"}));
18344   Style.QualifierOrder.clear();
18345   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
18346               std::vector<std::string>({"volatile", "type"}));
18347 
18348   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
18349   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
18350               FormatStyle::ACS_None);
18351   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
18352               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
18353   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
18354               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
18355   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
18356               AlignConsecutiveAssignments,
18357               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18358   // For backwards compability, false / true should still parse
18359   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
18360               FormatStyle::ACS_None);
18361   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
18362               FormatStyle::ACS_Consecutive);
18363 
18364   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
18365   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
18366               FormatStyle::ACS_None);
18367   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
18368               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
18369   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
18370               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
18371   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
18372               AlignConsecutiveBitFields,
18373               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18374   // For backwards compability, false / true should still parse
18375   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
18376               FormatStyle::ACS_None);
18377   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
18378               FormatStyle::ACS_Consecutive);
18379 
18380   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
18381   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
18382               FormatStyle::ACS_None);
18383   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
18384               FormatStyle::ACS_Consecutive);
18385   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
18386               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
18387   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
18388               AlignConsecutiveMacros,
18389               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18390   // For backwards compability, false / true should still parse
18391   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
18392               FormatStyle::ACS_None);
18393   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
18394               FormatStyle::ACS_Consecutive);
18395 
18396   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
18397   CHECK_PARSE("AlignConsecutiveDeclarations: None",
18398               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
18399   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
18400               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
18401   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
18402               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
18403   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
18404               AlignConsecutiveDeclarations,
18405               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18406   // For backwards compability, false / true should still parse
18407   CHECK_PARSE("AlignConsecutiveDeclarations: false",
18408               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
18409   CHECK_PARSE("AlignConsecutiveDeclarations: true",
18410               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
18411 
18412   Style.PointerAlignment = FormatStyle::PAS_Middle;
18413   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
18414               FormatStyle::PAS_Left);
18415   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
18416               FormatStyle::PAS_Right);
18417   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
18418               FormatStyle::PAS_Middle);
18419   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
18420   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
18421               FormatStyle::RAS_Pointer);
18422   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
18423               FormatStyle::RAS_Left);
18424   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
18425               FormatStyle::RAS_Right);
18426   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
18427               FormatStyle::RAS_Middle);
18428   // For backward compatibility:
18429   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
18430               FormatStyle::PAS_Left);
18431   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
18432               FormatStyle::PAS_Right);
18433   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
18434               FormatStyle::PAS_Middle);
18435 
18436   Style.Standard = FormatStyle::LS_Auto;
18437   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
18438   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
18439   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
18440   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
18441   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
18442   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
18443   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
18444   // Legacy aliases:
18445   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
18446   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
18447   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
18448   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
18449 
18450   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
18451   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
18452               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
18453   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
18454               FormatStyle::BOS_None);
18455   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
18456               FormatStyle::BOS_All);
18457   // For backward compatibility:
18458   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
18459               FormatStyle::BOS_None);
18460   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
18461               FormatStyle::BOS_All);
18462 
18463   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
18464   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
18465               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
18466   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
18467               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
18468   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
18469               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
18470   // For backward compatibility:
18471   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
18472               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
18473 
18474   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
18475   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
18476               FormatStyle::BILS_AfterComma);
18477   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
18478               FormatStyle::BILS_BeforeComma);
18479   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
18480               FormatStyle::BILS_AfterColon);
18481   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
18482               FormatStyle::BILS_BeforeColon);
18483   // For backward compatibility:
18484   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
18485               FormatStyle::BILS_BeforeComma);
18486 
18487   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
18488   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
18489               FormatStyle::PCIS_Never);
18490   CHECK_PARSE("PackConstructorInitializers: BinPack",
18491               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
18492   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
18493               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
18494   CHECK_PARSE("PackConstructorInitializers: NextLine",
18495               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
18496   // For backward compatibility:
18497   CHECK_PARSE("BasedOnStyle: Google\n"
18498               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
18499               "AllowAllConstructorInitializersOnNextLine: false",
18500               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
18501   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
18502   CHECK_PARSE("BasedOnStyle: Google\n"
18503               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
18504               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
18505   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
18506               "AllowAllConstructorInitializersOnNextLine: true",
18507               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
18508   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
18509   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
18510               "AllowAllConstructorInitializersOnNextLine: false",
18511               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
18512 
18513   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
18514   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
18515               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
18516   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
18517               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
18518   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
18519               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
18520   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
18521               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
18522 
18523   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
18524   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
18525               FormatStyle::BAS_Align);
18526   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
18527               FormatStyle::BAS_DontAlign);
18528   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
18529               FormatStyle::BAS_AlwaysBreak);
18530   // For backward compatibility:
18531   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
18532               FormatStyle::BAS_DontAlign);
18533   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
18534               FormatStyle::BAS_Align);
18535 
18536   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
18537   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
18538               FormatStyle::ENAS_DontAlign);
18539   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
18540               FormatStyle::ENAS_Left);
18541   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
18542               FormatStyle::ENAS_Right);
18543   // For backward compatibility:
18544   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
18545               FormatStyle::ENAS_Left);
18546   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
18547               FormatStyle::ENAS_Right);
18548 
18549   Style.AlignOperands = FormatStyle::OAS_Align;
18550   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
18551               FormatStyle::OAS_DontAlign);
18552   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
18553   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
18554               FormatStyle::OAS_AlignAfterOperator);
18555   // For backward compatibility:
18556   CHECK_PARSE("AlignOperands: false", AlignOperands,
18557               FormatStyle::OAS_DontAlign);
18558   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
18559 
18560   Style.UseTab = FormatStyle::UT_ForIndentation;
18561   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
18562   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
18563   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
18564   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
18565               FormatStyle::UT_ForContinuationAndIndentation);
18566   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
18567               FormatStyle::UT_AlignWithSpaces);
18568   // For backward compatibility:
18569   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
18570   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
18571 
18572   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
18573   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
18574               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
18575   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
18576               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
18577   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
18578               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
18579   // For backward compatibility:
18580   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
18581               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
18582   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
18583               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
18584 
18585   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
18586   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
18587               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
18588   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
18589               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
18590   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
18591               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
18592   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
18593               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
18594   // For backward compatibility:
18595   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
18596               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
18597   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
18598               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
18599 
18600   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
18601   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
18602               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
18603   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
18604               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
18605   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
18606               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
18607   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
18608               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
18609 
18610   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
18611   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
18612               FormatStyle::SBPO_Never);
18613   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
18614               FormatStyle::SBPO_Always);
18615   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
18616               FormatStyle::SBPO_ControlStatements);
18617   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
18618               SpaceBeforeParens,
18619               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
18620   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
18621               FormatStyle::SBPO_NonEmptyParentheses);
18622   // For backward compatibility:
18623   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
18624               FormatStyle::SBPO_Never);
18625   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
18626               FormatStyle::SBPO_ControlStatements);
18627   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
18628               SpaceBeforeParens,
18629               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
18630 
18631   Style.ColumnLimit = 123;
18632   FormatStyle BaseStyle = getLLVMStyle();
18633   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
18634   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
18635 
18636   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18637   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
18638               FormatStyle::BS_Attach);
18639   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
18640               FormatStyle::BS_Linux);
18641   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
18642               FormatStyle::BS_Mozilla);
18643   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
18644               FormatStyle::BS_Stroustrup);
18645   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
18646               FormatStyle::BS_Allman);
18647   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
18648               FormatStyle::BS_Whitesmiths);
18649   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
18650   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
18651               FormatStyle::BS_WebKit);
18652   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
18653               FormatStyle::BS_Custom);
18654 
18655   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
18656   CHECK_PARSE("BraceWrapping:\n"
18657               "  AfterControlStatement: MultiLine",
18658               BraceWrapping.AfterControlStatement,
18659               FormatStyle::BWACS_MultiLine);
18660   CHECK_PARSE("BraceWrapping:\n"
18661               "  AfterControlStatement: Always",
18662               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
18663   CHECK_PARSE("BraceWrapping:\n"
18664               "  AfterControlStatement: Never",
18665               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
18666   // For backward compatibility:
18667   CHECK_PARSE("BraceWrapping:\n"
18668               "  AfterControlStatement: true",
18669               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
18670   CHECK_PARSE("BraceWrapping:\n"
18671               "  AfterControlStatement: false",
18672               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
18673 
18674   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
18675   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
18676               FormatStyle::RTBS_None);
18677   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
18678               FormatStyle::RTBS_All);
18679   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
18680               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
18681   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
18682               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
18683   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
18684               AlwaysBreakAfterReturnType,
18685               FormatStyle::RTBS_TopLevelDefinitions);
18686 
18687   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
18688   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
18689               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
18690   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
18691               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
18692   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
18693               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
18694   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
18695               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
18696   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
18697               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
18698 
18699   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
18700   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
18701               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
18702   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
18703               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
18704   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
18705               AlwaysBreakAfterDefinitionReturnType,
18706               FormatStyle::DRTBS_TopLevel);
18707 
18708   Style.NamespaceIndentation = FormatStyle::NI_All;
18709   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
18710               FormatStyle::NI_None);
18711   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
18712               FormatStyle::NI_Inner);
18713   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
18714               FormatStyle::NI_All);
18715 
18716   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
18717   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
18718               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
18719   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
18720               AllowShortIfStatementsOnASingleLine,
18721               FormatStyle::SIS_WithoutElse);
18722   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
18723               AllowShortIfStatementsOnASingleLine,
18724               FormatStyle::SIS_OnlyFirstIf);
18725   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
18726               AllowShortIfStatementsOnASingleLine,
18727               FormatStyle::SIS_AllIfsAndElse);
18728   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
18729               AllowShortIfStatementsOnASingleLine,
18730               FormatStyle::SIS_OnlyFirstIf);
18731   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
18732               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
18733   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
18734               AllowShortIfStatementsOnASingleLine,
18735               FormatStyle::SIS_WithoutElse);
18736 
18737   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
18738   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
18739               FormatStyle::IEBS_AfterExternBlock);
18740   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
18741               FormatStyle::IEBS_Indent);
18742   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
18743               FormatStyle::IEBS_NoIndent);
18744   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
18745               FormatStyle::IEBS_Indent);
18746   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
18747               FormatStyle::IEBS_NoIndent);
18748 
18749   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
18750   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
18751               FormatStyle::BFCS_Both);
18752   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
18753               FormatStyle::BFCS_None);
18754   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
18755               FormatStyle::BFCS_Before);
18756   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
18757               FormatStyle::BFCS_After);
18758 
18759   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
18760   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
18761               FormatStyle::SJSIO_After);
18762   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
18763               FormatStyle::SJSIO_Before);
18764 
18765   // FIXME: This is required because parsing a configuration simply overwrites
18766   // the first N elements of the list instead of resetting it.
18767   Style.ForEachMacros.clear();
18768   std::vector<std::string> BoostForeach;
18769   BoostForeach.push_back("BOOST_FOREACH");
18770   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
18771   std::vector<std::string> BoostAndQForeach;
18772   BoostAndQForeach.push_back("BOOST_FOREACH");
18773   BoostAndQForeach.push_back("Q_FOREACH");
18774   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
18775               BoostAndQForeach);
18776 
18777   Style.IfMacros.clear();
18778   std::vector<std::string> CustomIfs;
18779   CustomIfs.push_back("MYIF");
18780   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
18781 
18782   Style.AttributeMacros.clear();
18783   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
18784               std::vector<std::string>{"__capability"});
18785   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
18786               std::vector<std::string>({"attr1", "attr2"}));
18787 
18788   Style.StatementAttributeLikeMacros.clear();
18789   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
18790               StatementAttributeLikeMacros,
18791               std::vector<std::string>({"emit", "Q_EMIT"}));
18792 
18793   Style.StatementMacros.clear();
18794   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
18795               std::vector<std::string>{"QUNUSED"});
18796   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
18797               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
18798 
18799   Style.NamespaceMacros.clear();
18800   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
18801               std::vector<std::string>{"TESTSUITE"});
18802   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
18803               std::vector<std::string>({"TESTSUITE", "SUITE"}));
18804 
18805   Style.WhitespaceSensitiveMacros.clear();
18806   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
18807               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
18808   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
18809               WhitespaceSensitiveMacros,
18810               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
18811   Style.WhitespaceSensitiveMacros.clear();
18812   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
18813               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
18814   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
18815               WhitespaceSensitiveMacros,
18816               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
18817 
18818   Style.IncludeStyle.IncludeCategories.clear();
18819   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
18820       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
18821   CHECK_PARSE("IncludeCategories:\n"
18822               "  - Regex: abc/.*\n"
18823               "    Priority: 2\n"
18824               "  - Regex: .*\n"
18825               "    Priority: 1\n"
18826               "    CaseSensitive: true\n",
18827               IncludeStyle.IncludeCategories, ExpectedCategories);
18828   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
18829               "abc$");
18830   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
18831               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
18832 
18833   Style.SortIncludes = FormatStyle::SI_Never;
18834   CHECK_PARSE("SortIncludes: true", SortIncludes,
18835               FormatStyle::SI_CaseSensitive);
18836   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
18837   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
18838               FormatStyle::SI_CaseInsensitive);
18839   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
18840               FormatStyle::SI_CaseSensitive);
18841   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
18842 
18843   Style.RawStringFormats.clear();
18844   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
18845       {
18846           FormatStyle::LK_TextProto,
18847           {"pb", "proto"},
18848           {"PARSE_TEXT_PROTO"},
18849           /*CanonicalDelimiter=*/"",
18850           "llvm",
18851       },
18852       {
18853           FormatStyle::LK_Cpp,
18854           {"cc", "cpp"},
18855           {"C_CODEBLOCK", "CPPEVAL"},
18856           /*CanonicalDelimiter=*/"cc",
18857           /*BasedOnStyle=*/"",
18858       },
18859   };
18860 
18861   CHECK_PARSE("RawStringFormats:\n"
18862               "  - Language: TextProto\n"
18863               "    Delimiters:\n"
18864               "      - 'pb'\n"
18865               "      - 'proto'\n"
18866               "    EnclosingFunctions:\n"
18867               "      - 'PARSE_TEXT_PROTO'\n"
18868               "    BasedOnStyle: llvm\n"
18869               "  - Language: Cpp\n"
18870               "    Delimiters:\n"
18871               "      - 'cc'\n"
18872               "      - 'cpp'\n"
18873               "    EnclosingFunctions:\n"
18874               "      - 'C_CODEBLOCK'\n"
18875               "      - 'CPPEVAL'\n"
18876               "    CanonicalDelimiter: 'cc'",
18877               RawStringFormats, ExpectedRawStringFormats);
18878 
18879   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18880               "  Minimum: 0\n"
18881               "  Maximum: 0",
18882               SpacesInLineCommentPrefix.Minimum, 0u);
18883   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
18884   Style.SpacesInLineCommentPrefix.Minimum = 1;
18885   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18886               "  Minimum: 2",
18887               SpacesInLineCommentPrefix.Minimum, 0u);
18888   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18889               "  Maximum: -1",
18890               SpacesInLineCommentPrefix.Maximum, -1u);
18891   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18892               "  Minimum: 2",
18893               SpacesInLineCommentPrefix.Minimum, 2u);
18894   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18895               "  Maximum: 1",
18896               SpacesInLineCommentPrefix.Maximum, 1u);
18897   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
18898 
18899   Style.SpacesInAngles = FormatStyle::SIAS_Always;
18900   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
18901   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
18902               FormatStyle::SIAS_Always);
18903   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
18904   // For backward compatibility:
18905   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
18906   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
18907 }
18908 
18909 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
18910   FormatStyle Style = {};
18911   Style.Language = FormatStyle::LK_Cpp;
18912   CHECK_PARSE("Language: Cpp\n"
18913               "IndentWidth: 12",
18914               IndentWidth, 12u);
18915   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
18916                                "IndentWidth: 34",
18917                                &Style),
18918             ParseError::Unsuitable);
18919   FormatStyle BinPackedTCS = {};
18920   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
18921   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
18922                                "InsertTrailingCommas: Wrapped",
18923                                &BinPackedTCS),
18924             ParseError::BinPackTrailingCommaConflict);
18925   EXPECT_EQ(12u, Style.IndentWidth);
18926   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
18927   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
18928 
18929   Style.Language = FormatStyle::LK_JavaScript;
18930   CHECK_PARSE("Language: JavaScript\n"
18931               "IndentWidth: 12",
18932               IndentWidth, 12u);
18933   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
18934   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
18935                                "IndentWidth: 34",
18936                                &Style),
18937             ParseError::Unsuitable);
18938   EXPECT_EQ(23u, Style.IndentWidth);
18939   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
18940   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
18941 
18942   CHECK_PARSE("BasedOnStyle: LLVM\n"
18943               "IndentWidth: 67",
18944               IndentWidth, 67u);
18945 
18946   CHECK_PARSE("---\n"
18947               "Language: JavaScript\n"
18948               "IndentWidth: 12\n"
18949               "---\n"
18950               "Language: Cpp\n"
18951               "IndentWidth: 34\n"
18952               "...\n",
18953               IndentWidth, 12u);
18954 
18955   Style.Language = FormatStyle::LK_Cpp;
18956   CHECK_PARSE("---\n"
18957               "Language: JavaScript\n"
18958               "IndentWidth: 12\n"
18959               "---\n"
18960               "Language: Cpp\n"
18961               "IndentWidth: 34\n"
18962               "...\n",
18963               IndentWidth, 34u);
18964   CHECK_PARSE("---\n"
18965               "IndentWidth: 78\n"
18966               "---\n"
18967               "Language: JavaScript\n"
18968               "IndentWidth: 56\n"
18969               "...\n",
18970               IndentWidth, 78u);
18971 
18972   Style.ColumnLimit = 123;
18973   Style.IndentWidth = 234;
18974   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
18975   Style.TabWidth = 345;
18976   EXPECT_FALSE(parseConfiguration("---\n"
18977                                   "IndentWidth: 456\n"
18978                                   "BreakBeforeBraces: Allman\n"
18979                                   "---\n"
18980                                   "Language: JavaScript\n"
18981                                   "IndentWidth: 111\n"
18982                                   "TabWidth: 111\n"
18983                                   "---\n"
18984                                   "Language: Cpp\n"
18985                                   "BreakBeforeBraces: Stroustrup\n"
18986                                   "TabWidth: 789\n"
18987                                   "...\n",
18988                                   &Style));
18989   EXPECT_EQ(123u, Style.ColumnLimit);
18990   EXPECT_EQ(456u, Style.IndentWidth);
18991   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
18992   EXPECT_EQ(789u, Style.TabWidth);
18993 
18994   EXPECT_EQ(parseConfiguration("---\n"
18995                                "Language: JavaScript\n"
18996                                "IndentWidth: 56\n"
18997                                "---\n"
18998                                "IndentWidth: 78\n"
18999                                "...\n",
19000                                &Style),
19001             ParseError::Error);
19002   EXPECT_EQ(parseConfiguration("---\n"
19003                                "Language: JavaScript\n"
19004                                "IndentWidth: 56\n"
19005                                "---\n"
19006                                "Language: JavaScript\n"
19007                                "IndentWidth: 78\n"
19008                                "...\n",
19009                                &Style),
19010             ParseError::Error);
19011 
19012   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19013 }
19014 
19015 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
19016   FormatStyle Style = {};
19017   Style.Language = FormatStyle::LK_JavaScript;
19018   Style.BreakBeforeTernaryOperators = true;
19019   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
19020   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19021 
19022   Style.BreakBeforeTernaryOperators = true;
19023   EXPECT_EQ(0, parseConfiguration("---\n"
19024                                   "BasedOnStyle: Google\n"
19025                                   "---\n"
19026                                   "Language: JavaScript\n"
19027                                   "IndentWidth: 76\n"
19028                                   "...\n",
19029                                   &Style)
19030                    .value());
19031   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19032   EXPECT_EQ(76u, Style.IndentWidth);
19033   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19034 }
19035 
19036 TEST_F(FormatTest, ConfigurationRoundTripTest) {
19037   FormatStyle Style = getLLVMStyle();
19038   std::string YAML = configurationAsText(Style);
19039   FormatStyle ParsedStyle = {};
19040   ParsedStyle.Language = FormatStyle::LK_Cpp;
19041   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
19042   EXPECT_EQ(Style, ParsedStyle);
19043 }
19044 
19045 TEST_F(FormatTest, WorksFor8bitEncodings) {
19046   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
19047             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
19048             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
19049             "\"\xef\xee\xf0\xf3...\"",
19050             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
19051                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
19052                    "\xef\xee\xf0\xf3...\"",
19053                    getLLVMStyleWithColumns(12)));
19054 }
19055 
19056 TEST_F(FormatTest, HandlesUTF8BOM) {
19057   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
19058   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
19059             format("\xef\xbb\xbf#include <iostream>"));
19060   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
19061             format("\xef\xbb\xbf\n#include <iostream>"));
19062 }
19063 
19064 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
19065 #if !defined(_MSC_VER)
19066 
19067 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
19068   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
19069                getLLVMStyleWithColumns(35));
19070   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
19071                getLLVMStyleWithColumns(31));
19072   verifyFormat("// Однажды в студёную зимнюю пору...",
19073                getLLVMStyleWithColumns(36));
19074   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
19075   verifyFormat("/* Однажды в студёную зимнюю пору... */",
19076                getLLVMStyleWithColumns(39));
19077   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
19078                getLLVMStyleWithColumns(35));
19079 }
19080 
19081 TEST_F(FormatTest, SplitsUTF8Strings) {
19082   // Non-printable characters' width is currently considered to be the length in
19083   // bytes in UTF8. The characters can be displayed in very different manner
19084   // (zero-width, single width with a substitution glyph, expanded to their code
19085   // (e.g. "<8d>"), so there's no single correct way to handle them.
19086   EXPECT_EQ("\"aaaaÄ\"\n"
19087             "\"\xc2\x8d\";",
19088             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19089   EXPECT_EQ("\"aaaaaaaÄ\"\n"
19090             "\"\xc2\x8d\";",
19091             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19092   EXPECT_EQ("\"Однажды, в \"\n"
19093             "\"студёную \"\n"
19094             "\"зимнюю \"\n"
19095             "\"пору,\"",
19096             format("\"Однажды, в студёную зимнюю пору,\"",
19097                    getLLVMStyleWithColumns(13)));
19098   EXPECT_EQ(
19099       "\"一 二 三 \"\n"
19100       "\"四 五六 \"\n"
19101       "\"七 八 九 \"\n"
19102       "\"十\"",
19103       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
19104   EXPECT_EQ("\"一\t\"\n"
19105             "\"二 \t\"\n"
19106             "\"三 四 \"\n"
19107             "\"五\t\"\n"
19108             "\"六 \t\"\n"
19109             "\"七 \"\n"
19110             "\"八九十\tqq\"",
19111             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
19112                    getLLVMStyleWithColumns(11)));
19113 
19114   // UTF8 character in an escape sequence.
19115   EXPECT_EQ("\"aaaaaa\"\n"
19116             "\"\\\xC2\x8D\"",
19117             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
19118 }
19119 
19120 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
19121   EXPECT_EQ("const char *sssss =\n"
19122             "    \"一二三四五六七八\\\n"
19123             " 九 十\";",
19124             format("const char *sssss = \"一二三四五六七八\\\n"
19125                    " 九 十\";",
19126                    getLLVMStyleWithColumns(30)));
19127 }
19128 
19129 TEST_F(FormatTest, SplitsUTF8LineComments) {
19130   EXPECT_EQ("// aaaaÄ\xc2\x8d",
19131             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
19132   EXPECT_EQ("// Я из лесу\n"
19133             "// вышел; был\n"
19134             "// сильный\n"
19135             "// мороз.",
19136             format("// Я из лесу вышел; был сильный мороз.",
19137                    getLLVMStyleWithColumns(13)));
19138   EXPECT_EQ("// 一二三\n"
19139             "// 四五六七\n"
19140             "// 八  九\n"
19141             "// 十",
19142             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
19143 }
19144 
19145 TEST_F(FormatTest, SplitsUTF8BlockComments) {
19146   EXPECT_EQ("/* Гляжу,\n"
19147             " * поднимается\n"
19148             " * медленно в\n"
19149             " * гору\n"
19150             " * Лошадка,\n"
19151             " * везущая\n"
19152             " * хворосту\n"
19153             " * воз. */",
19154             format("/* Гляжу, поднимается медленно в гору\n"
19155                    " * Лошадка, везущая хворосту воз. */",
19156                    getLLVMStyleWithColumns(13)));
19157   EXPECT_EQ(
19158       "/* 一二三\n"
19159       " * 四五六七\n"
19160       " * 八  九\n"
19161       " * 十  */",
19162       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
19163   EXPECT_EQ("/* �������� ��������\n"
19164             " * ��������\n"
19165             " * ������-�� */",
19166             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
19167 }
19168 
19169 #endif // _MSC_VER
19170 
19171 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
19172   FormatStyle Style = getLLVMStyle();
19173 
19174   Style.ConstructorInitializerIndentWidth = 4;
19175   verifyFormat(
19176       "SomeClass::Constructor()\n"
19177       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19178       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19179       Style);
19180 
19181   Style.ConstructorInitializerIndentWidth = 2;
19182   verifyFormat(
19183       "SomeClass::Constructor()\n"
19184       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19185       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19186       Style);
19187 
19188   Style.ConstructorInitializerIndentWidth = 0;
19189   verifyFormat(
19190       "SomeClass::Constructor()\n"
19191       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19192       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19193       Style);
19194   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19195   verifyFormat(
19196       "SomeLongTemplateVariableName<\n"
19197       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
19198       Style);
19199   verifyFormat("bool smaller = 1 < "
19200                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
19201                "                       "
19202                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
19203                Style);
19204 
19205   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
19206   verifyFormat("SomeClass::Constructor() :\n"
19207                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
19208                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
19209                Style);
19210 }
19211 
19212 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
19213   FormatStyle Style = getLLVMStyle();
19214   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19215   Style.ConstructorInitializerIndentWidth = 4;
19216   verifyFormat("SomeClass::Constructor()\n"
19217                "    : a(a)\n"
19218                "    , b(b)\n"
19219                "    , c(c) {}",
19220                Style);
19221   verifyFormat("SomeClass::Constructor()\n"
19222                "    : a(a) {}",
19223                Style);
19224 
19225   Style.ColumnLimit = 0;
19226   verifyFormat("SomeClass::Constructor()\n"
19227                "    : a(a) {}",
19228                Style);
19229   verifyFormat("SomeClass::Constructor() noexcept\n"
19230                "    : a(a) {}",
19231                Style);
19232   verifyFormat("SomeClass::Constructor()\n"
19233                "    : a(a)\n"
19234                "    , b(b)\n"
19235                "    , c(c) {}",
19236                Style);
19237   verifyFormat("SomeClass::Constructor()\n"
19238                "    : a(a) {\n"
19239                "  foo();\n"
19240                "  bar();\n"
19241                "}",
19242                Style);
19243 
19244   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
19245   verifyFormat("SomeClass::Constructor()\n"
19246                "    : a(a)\n"
19247                "    , b(b)\n"
19248                "    , c(c) {\n}",
19249                Style);
19250   verifyFormat("SomeClass::Constructor()\n"
19251                "    : a(a) {\n}",
19252                Style);
19253 
19254   Style.ColumnLimit = 80;
19255   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
19256   Style.ConstructorInitializerIndentWidth = 2;
19257   verifyFormat("SomeClass::Constructor()\n"
19258                "  : a(a)\n"
19259                "  , b(b)\n"
19260                "  , c(c) {}",
19261                Style);
19262 
19263   Style.ConstructorInitializerIndentWidth = 0;
19264   verifyFormat("SomeClass::Constructor()\n"
19265                ": a(a)\n"
19266                ", b(b)\n"
19267                ", c(c) {}",
19268                Style);
19269 
19270   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19271   Style.ConstructorInitializerIndentWidth = 4;
19272   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
19273   verifyFormat(
19274       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
19275       Style);
19276   verifyFormat(
19277       "SomeClass::Constructor()\n"
19278       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
19279       Style);
19280   Style.ConstructorInitializerIndentWidth = 4;
19281   Style.ColumnLimit = 60;
19282   verifyFormat("SomeClass::Constructor()\n"
19283                "    : aaaaaaaa(aaaaaaaa)\n"
19284                "    , aaaaaaaa(aaaaaaaa)\n"
19285                "    , aaaaaaaa(aaaaaaaa) {}",
19286                Style);
19287 }
19288 
19289 TEST_F(FormatTest, Destructors) {
19290   verifyFormat("void F(int &i) { i.~int(); }");
19291   verifyFormat("void F(int &i) { i->~int(); }");
19292 }
19293 
19294 TEST_F(FormatTest, FormatsWithWebKitStyle) {
19295   FormatStyle Style = getWebKitStyle();
19296 
19297   // Don't indent in outer namespaces.
19298   verifyFormat("namespace outer {\n"
19299                "int i;\n"
19300                "namespace inner {\n"
19301                "    int i;\n"
19302                "} // namespace inner\n"
19303                "} // namespace outer\n"
19304                "namespace other_outer {\n"
19305                "int i;\n"
19306                "}",
19307                Style);
19308 
19309   // Don't indent case labels.
19310   verifyFormat("switch (variable) {\n"
19311                "case 1:\n"
19312                "case 2:\n"
19313                "    doSomething();\n"
19314                "    break;\n"
19315                "default:\n"
19316                "    ++variable;\n"
19317                "}",
19318                Style);
19319 
19320   // Wrap before binary operators.
19321   EXPECT_EQ("void f()\n"
19322             "{\n"
19323             "    if (aaaaaaaaaaaaaaaa\n"
19324             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
19325             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
19326             "        return;\n"
19327             "}",
19328             format("void f() {\n"
19329                    "if (aaaaaaaaaaaaaaaa\n"
19330                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
19331                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
19332                    "return;\n"
19333                    "}",
19334                    Style));
19335 
19336   // Allow functions on a single line.
19337   verifyFormat("void f() { return; }", Style);
19338 
19339   // Allow empty blocks on a single line and insert a space in empty blocks.
19340   EXPECT_EQ("void f() { }", format("void f() {}", Style));
19341   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
19342   // However, don't merge non-empty short loops.
19343   EXPECT_EQ("while (true) {\n"
19344             "    continue;\n"
19345             "}",
19346             format("while (true) { continue; }", Style));
19347 
19348   // Constructor initializers are formatted one per line with the "," on the
19349   // new line.
19350   verifyFormat("Constructor()\n"
19351                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
19352                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
19353                "          aaaaaaaaaaaaaa)\n"
19354                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
19355                "{\n"
19356                "}",
19357                Style);
19358   verifyFormat("SomeClass::Constructor()\n"
19359                "    : a(a)\n"
19360                "{\n"
19361                "}",
19362                Style);
19363   EXPECT_EQ("SomeClass::Constructor()\n"
19364             "    : a(a)\n"
19365             "{\n"
19366             "}",
19367             format("SomeClass::Constructor():a(a){}", Style));
19368   verifyFormat("SomeClass::Constructor()\n"
19369                "    : a(a)\n"
19370                "    , b(b)\n"
19371                "    , c(c)\n"
19372                "{\n"
19373                "}",
19374                Style);
19375   verifyFormat("SomeClass::Constructor()\n"
19376                "    : a(a)\n"
19377                "{\n"
19378                "    foo();\n"
19379                "    bar();\n"
19380                "}",
19381                Style);
19382 
19383   // Access specifiers should be aligned left.
19384   verifyFormat("class C {\n"
19385                "public:\n"
19386                "    int i;\n"
19387                "};",
19388                Style);
19389 
19390   // Do not align comments.
19391   verifyFormat("int a; // Do not\n"
19392                "double b; // align comments.",
19393                Style);
19394 
19395   // Do not align operands.
19396   EXPECT_EQ("ASSERT(aaaa\n"
19397             "    || bbbb);",
19398             format("ASSERT ( aaaa\n||bbbb);", Style));
19399 
19400   // Accept input's line breaks.
19401   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
19402             "    || bbbbbbbbbbbbbbb) {\n"
19403             "    i++;\n"
19404             "}",
19405             format("if (aaaaaaaaaaaaaaa\n"
19406                    "|| bbbbbbbbbbbbbbb) { i++; }",
19407                    Style));
19408   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
19409             "    i++;\n"
19410             "}",
19411             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
19412 
19413   // Don't automatically break all macro definitions (llvm.org/PR17842).
19414   verifyFormat("#define aNumber 10", Style);
19415   // However, generally keep the line breaks that the user authored.
19416   EXPECT_EQ("#define aNumber \\\n"
19417             "    10",
19418             format("#define aNumber \\\n"
19419                    " 10",
19420                    Style));
19421 
19422   // Keep empty and one-element array literals on a single line.
19423   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
19424             "                                  copyItems:YES];",
19425             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
19426                    "copyItems:YES];",
19427                    Style));
19428   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
19429             "                                  copyItems:YES];",
19430             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
19431                    "             copyItems:YES];",
19432                    Style));
19433   // FIXME: This does not seem right, there should be more indentation before
19434   // the array literal's entries. Nested blocks have the same problem.
19435   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
19436             "    @\"a\",\n"
19437             "    @\"a\"\n"
19438             "]\n"
19439             "                                  copyItems:YES];",
19440             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
19441                    "     @\"a\",\n"
19442                    "     @\"a\"\n"
19443                    "     ]\n"
19444                    "       copyItems:YES];",
19445                    Style));
19446   EXPECT_EQ(
19447       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
19448       "                                  copyItems:YES];",
19449       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
19450              "   copyItems:YES];",
19451              Style));
19452 
19453   verifyFormat("[self.a b:c c:d];", Style);
19454   EXPECT_EQ("[self.a b:c\n"
19455             "        c:d];",
19456             format("[self.a b:c\n"
19457                    "c:d];",
19458                    Style));
19459 }
19460 
19461 TEST_F(FormatTest, FormatsLambdas) {
19462   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
19463   verifyFormat(
19464       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
19465   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
19466   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
19467   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
19468   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
19469   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
19470   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
19471   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
19472   verifyFormat("int x = f(*+[] {});");
19473   verifyFormat("void f() {\n"
19474                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
19475                "}\n");
19476   verifyFormat("void f() {\n"
19477                "  other(x.begin(), //\n"
19478                "        x.end(),   //\n"
19479                "        [&](int, int) { return 1; });\n"
19480                "}\n");
19481   verifyFormat("void f() {\n"
19482                "  other.other.other.other.other(\n"
19483                "      x.begin(), x.end(),\n"
19484                "      [something, rather](int, int, int, int, int, int, int) { "
19485                "return 1; });\n"
19486                "}\n");
19487   verifyFormat(
19488       "void f() {\n"
19489       "  other.other.other.other.other(\n"
19490       "      x.begin(), x.end(),\n"
19491       "      [something, rather](int, int, int, int, int, int, int) {\n"
19492       "        //\n"
19493       "      });\n"
19494       "}\n");
19495   verifyFormat("SomeFunction([]() { // A cool function...\n"
19496                "  return 43;\n"
19497                "});");
19498   EXPECT_EQ("SomeFunction([]() {\n"
19499             "#define A a\n"
19500             "  return 43;\n"
19501             "});",
19502             format("SomeFunction([](){\n"
19503                    "#define A a\n"
19504                    "return 43;\n"
19505                    "});"));
19506   verifyFormat("void f() {\n"
19507                "  SomeFunction([](decltype(x), A *a) {});\n"
19508                "  SomeFunction([](typeof(x), A *a) {});\n"
19509                "  SomeFunction([](_Atomic(x), A *a) {});\n"
19510                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
19511                "}");
19512   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19513                "    [](const aaaaaaaaaa &a) { return a; });");
19514   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
19515                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
19516                "});");
19517   verifyFormat("Constructor()\n"
19518                "    : Field([] { // comment\n"
19519                "        int i;\n"
19520                "      }) {}");
19521   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
19522                "  return some_parameter.size();\n"
19523                "};");
19524   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
19525                "    [](const string &s) { return s; };");
19526   verifyFormat("int i = aaaaaa ? 1 //\n"
19527                "               : [] {\n"
19528                "                   return 2; //\n"
19529                "                 }();");
19530   verifyFormat("llvm::errs() << \"number of twos is \"\n"
19531                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
19532                "                  return x == 2; // force break\n"
19533                "                });");
19534   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19535                "    [=](int iiiiiiiiiiii) {\n"
19536                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
19537                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
19538                "    });",
19539                getLLVMStyleWithColumns(60));
19540 
19541   verifyFormat("SomeFunction({[&] {\n"
19542                "                // comment\n"
19543                "              },\n"
19544                "              [&] {\n"
19545                "                // comment\n"
19546                "              }});");
19547   verifyFormat("SomeFunction({[&] {\n"
19548                "  // comment\n"
19549                "}});");
19550   verifyFormat(
19551       "virtual aaaaaaaaaaaaaaaa(\n"
19552       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
19553       "    aaaaa aaaaaaaaa);");
19554 
19555   // Lambdas with return types.
19556   verifyFormat("int c = []() -> int { return 2; }();\n");
19557   verifyFormat("int c = []() -> int * { return 2; }();\n");
19558   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
19559   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
19560   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
19561   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
19562   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
19563   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
19564   verifyFormat("[a, a]() -> a<1> {};");
19565   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
19566   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
19567   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
19568   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
19569   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
19570   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
19571   verifyFormat("[]() -> foo<!5> { return {}; };");
19572   verifyFormat("[]() -> foo<~5> { return {}; };");
19573   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
19574   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
19575   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
19576   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
19577   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
19578   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
19579   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
19580   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
19581   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
19582   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
19583   verifyFormat("namespace bar {\n"
19584                "// broken:\n"
19585                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
19586                "} // namespace bar");
19587   verifyFormat("namespace bar {\n"
19588                "// broken:\n"
19589                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
19590                "} // namespace bar");
19591   verifyFormat("namespace bar {\n"
19592                "// broken:\n"
19593                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
19594                "} // namespace bar");
19595   verifyFormat("namespace bar {\n"
19596                "// broken:\n"
19597                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
19598                "} // namespace bar");
19599   verifyFormat("namespace bar {\n"
19600                "// broken:\n"
19601                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
19602                "} // namespace bar");
19603   verifyFormat("namespace bar {\n"
19604                "// broken:\n"
19605                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
19606                "} // namespace bar");
19607   verifyFormat("namespace bar {\n"
19608                "// broken:\n"
19609                "auto foo{[]() -> foo<!5> { return {}; }};\n"
19610                "} // namespace bar");
19611   verifyFormat("namespace bar {\n"
19612                "// broken:\n"
19613                "auto foo{[]() -> foo<~5> { return {}; }};\n"
19614                "} // namespace bar");
19615   verifyFormat("namespace bar {\n"
19616                "// broken:\n"
19617                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
19618                "} // namespace bar");
19619   verifyFormat("namespace bar {\n"
19620                "// broken:\n"
19621                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
19622                "} // namespace bar");
19623   verifyFormat("namespace bar {\n"
19624                "// broken:\n"
19625                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
19626                "} // namespace bar");
19627   verifyFormat("namespace bar {\n"
19628                "// broken:\n"
19629                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
19630                "} // namespace bar");
19631   verifyFormat("namespace bar {\n"
19632                "// broken:\n"
19633                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
19634                "} // namespace bar");
19635   verifyFormat("namespace bar {\n"
19636                "// broken:\n"
19637                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
19638                "} // namespace bar");
19639   verifyFormat("namespace bar {\n"
19640                "// broken:\n"
19641                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
19642                "} // namespace bar");
19643   verifyFormat("namespace bar {\n"
19644                "// broken:\n"
19645                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
19646                "} // namespace bar");
19647   verifyFormat("namespace bar {\n"
19648                "// broken:\n"
19649                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
19650                "} // namespace bar");
19651   verifyFormat("namespace bar {\n"
19652                "// broken:\n"
19653                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
19654                "} // namespace bar");
19655   verifyFormat("[]() -> a<1> {};");
19656   verifyFormat("[]() -> a<1> { ; };");
19657   verifyFormat("[]() -> a<1> { ; }();");
19658   verifyFormat("[a, a]() -> a<true> {};");
19659   verifyFormat("[]() -> a<true> {};");
19660   verifyFormat("[]() -> a<true> { ; };");
19661   verifyFormat("[]() -> a<true> { ; }();");
19662   verifyFormat("[a, a]() -> a<false> {};");
19663   verifyFormat("[]() -> a<false> {};");
19664   verifyFormat("[]() -> a<false> { ; };");
19665   verifyFormat("[]() -> a<false> { ; }();");
19666   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
19667   verifyFormat("namespace bar {\n"
19668                "auto foo{[]() -> foo<false> { ; }};\n"
19669                "} // namespace bar");
19670   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
19671                "                   int j) -> int {\n"
19672                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
19673                "};");
19674   verifyFormat(
19675       "aaaaaaaaaaaaaaaaaaaaaa(\n"
19676       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
19677       "      return aaaaaaaaaaaaaaaaa;\n"
19678       "    });",
19679       getLLVMStyleWithColumns(70));
19680   verifyFormat("[]() //\n"
19681                "    -> int {\n"
19682                "  return 1; //\n"
19683                "};");
19684   verifyFormat("[]() -> Void<T...> {};");
19685   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
19686 
19687   // Lambdas with explicit template argument lists.
19688   verifyFormat(
19689       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
19690 
19691   // Multiple lambdas in the same parentheses change indentation rules. These
19692   // lambdas are forced to start on new lines.
19693   verifyFormat("SomeFunction(\n"
19694                "    []() {\n"
19695                "      //\n"
19696                "    },\n"
19697                "    []() {\n"
19698                "      //\n"
19699                "    });");
19700 
19701   // A lambda passed as arg0 is always pushed to the next line.
19702   verifyFormat("SomeFunction(\n"
19703                "    [this] {\n"
19704                "      //\n"
19705                "    },\n"
19706                "    1);\n");
19707 
19708   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
19709   // the arg0 case above.
19710   auto Style = getGoogleStyle();
19711   Style.BinPackArguments = false;
19712   verifyFormat("SomeFunction(\n"
19713                "    a,\n"
19714                "    [this] {\n"
19715                "      //\n"
19716                "    },\n"
19717                "    b);\n",
19718                Style);
19719   verifyFormat("SomeFunction(\n"
19720                "    a,\n"
19721                "    [this] {\n"
19722                "      //\n"
19723                "    },\n"
19724                "    b);\n");
19725 
19726   // A lambda with a very long line forces arg0 to be pushed out irrespective of
19727   // the BinPackArguments value (as long as the code is wide enough).
19728   verifyFormat(
19729       "something->SomeFunction(\n"
19730       "    a,\n"
19731       "    [this] {\n"
19732       "      "
19733       "D0000000000000000000000000000000000000000000000000000000000001();\n"
19734       "    },\n"
19735       "    b);\n");
19736 
19737   // A multi-line lambda is pulled up as long as the introducer fits on the
19738   // previous line and there are no further args.
19739   verifyFormat("function(1, [this, that] {\n"
19740                "  //\n"
19741                "});\n");
19742   verifyFormat("function([this, that] {\n"
19743                "  //\n"
19744                "});\n");
19745   // FIXME: this format is not ideal and we should consider forcing the first
19746   // arg onto its own line.
19747   verifyFormat("function(a, b, c, //\n"
19748                "         d, [this, that] {\n"
19749                "           //\n"
19750                "         });\n");
19751 
19752   // Multiple lambdas are treated correctly even when there is a short arg0.
19753   verifyFormat("SomeFunction(\n"
19754                "    1,\n"
19755                "    [this] {\n"
19756                "      //\n"
19757                "    },\n"
19758                "    [this] {\n"
19759                "      //\n"
19760                "    },\n"
19761                "    1);\n");
19762 
19763   // More complex introducers.
19764   verifyFormat("return [i, args...] {};");
19765 
19766   // Not lambdas.
19767   verifyFormat("constexpr char hello[]{\"hello\"};");
19768   verifyFormat("double &operator[](int i) { return 0; }\n"
19769                "int i;");
19770   verifyFormat("std::unique_ptr<int[]> foo() {}");
19771   verifyFormat("int i = a[a][a]->f();");
19772   verifyFormat("int i = (*b)[a]->f();");
19773 
19774   // Other corner cases.
19775   verifyFormat("void f() {\n"
19776                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
19777                "  );\n"
19778                "}");
19779 
19780   // Lambdas created through weird macros.
19781   verifyFormat("void f() {\n"
19782                "  MACRO((const AA &a) { return 1; });\n"
19783                "  MACRO((AA &a) { return 1; });\n"
19784                "}");
19785 
19786   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
19787                "      doo_dah();\n"
19788                "      doo_dah();\n"
19789                "    })) {\n"
19790                "}");
19791   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
19792                "                doo_dah();\n"
19793                "                doo_dah();\n"
19794                "              })) {\n"
19795                "}");
19796   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
19797                "                doo_dah();\n"
19798                "                doo_dah();\n"
19799                "              })) {\n"
19800                "}");
19801   verifyFormat("auto lambda = []() {\n"
19802                "  int a = 2\n"
19803                "#if A\n"
19804                "          + 2\n"
19805                "#endif\n"
19806                "      ;\n"
19807                "};");
19808 
19809   // Lambdas with complex multiline introducers.
19810   verifyFormat(
19811       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19812       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
19813       "        -> ::std::unordered_set<\n"
19814       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
19815       "      //\n"
19816       "    });");
19817 
19818   FormatStyle DoNotMerge = getLLVMStyle();
19819   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
19820   verifyFormat("auto c = []() {\n"
19821                "  return b;\n"
19822                "};",
19823                "auto c = []() { return b; };", DoNotMerge);
19824   verifyFormat("auto c = []() {\n"
19825                "};",
19826                " auto c = []() {};", DoNotMerge);
19827 
19828   FormatStyle MergeEmptyOnly = getLLVMStyle();
19829   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
19830   verifyFormat("auto c = []() {\n"
19831                "  return b;\n"
19832                "};",
19833                "auto c = []() {\n"
19834                "  return b;\n"
19835                " };",
19836                MergeEmptyOnly);
19837   verifyFormat("auto c = []() {};",
19838                "auto c = []() {\n"
19839                "};",
19840                MergeEmptyOnly);
19841 
19842   FormatStyle MergeInline = getLLVMStyle();
19843   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
19844   verifyFormat("auto c = []() {\n"
19845                "  return b;\n"
19846                "};",
19847                "auto c = []() { return b; };", MergeInline);
19848   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
19849                MergeInline);
19850   verifyFormat("function([]() { return b; }, a)",
19851                "function([]() { return b; }, a)", MergeInline);
19852   verifyFormat("function(a, []() { return b; })",
19853                "function(a, []() { return b; })", MergeInline);
19854 
19855   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
19856   // AllowShortLambdasOnASingleLine
19857   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
19858   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
19859   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
19860   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19861       FormatStyle::ShortLambdaStyle::SLS_None;
19862   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
19863                "    []()\n"
19864                "    {\n"
19865                "      return 17;\n"
19866                "    });",
19867                LLVMWithBeforeLambdaBody);
19868   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
19869                "    []()\n"
19870                "    {\n"
19871                "    });",
19872                LLVMWithBeforeLambdaBody);
19873   verifyFormat("auto fct_SLS_None = []()\n"
19874                "{\n"
19875                "  return 17;\n"
19876                "};",
19877                LLVMWithBeforeLambdaBody);
19878   verifyFormat("TwoNestedLambdas_SLS_None(\n"
19879                "    []()\n"
19880                "    {\n"
19881                "      return Call(\n"
19882                "          []()\n"
19883                "          {\n"
19884                "            return 17;\n"
19885                "          });\n"
19886                "    });",
19887                LLVMWithBeforeLambdaBody);
19888   verifyFormat("void Fct() {\n"
19889                "  return {[]()\n"
19890                "          {\n"
19891                "            return 17;\n"
19892                "          }};\n"
19893                "}",
19894                LLVMWithBeforeLambdaBody);
19895 
19896   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19897       FormatStyle::ShortLambdaStyle::SLS_Empty;
19898   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
19899                "    []()\n"
19900                "    {\n"
19901                "      return 17;\n"
19902                "    });",
19903                LLVMWithBeforeLambdaBody);
19904   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
19905                LLVMWithBeforeLambdaBody);
19906   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
19907                "ongFunctionName_SLS_Empty(\n"
19908                "    []() {});",
19909                LLVMWithBeforeLambdaBody);
19910   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
19911                "                                []()\n"
19912                "                                {\n"
19913                "                                  return 17;\n"
19914                "                                });",
19915                LLVMWithBeforeLambdaBody);
19916   verifyFormat("auto fct_SLS_Empty = []()\n"
19917                "{\n"
19918                "  return 17;\n"
19919                "};",
19920                LLVMWithBeforeLambdaBody);
19921   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
19922                "    []()\n"
19923                "    {\n"
19924                "      return Call([]() {});\n"
19925                "    });",
19926                LLVMWithBeforeLambdaBody);
19927   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
19928                "                           []()\n"
19929                "                           {\n"
19930                "                             return Call([]() {});\n"
19931                "                           });",
19932                LLVMWithBeforeLambdaBody);
19933   verifyFormat(
19934       "FctWithLongLineInLambda_SLS_Empty(\n"
19935       "    []()\n"
19936       "    {\n"
19937       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
19938       "                               AndShouldNotBeConsiderAsInline,\n"
19939       "                               LambdaBodyMustBeBreak);\n"
19940       "    });",
19941       LLVMWithBeforeLambdaBody);
19942 
19943   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19944       FormatStyle::ShortLambdaStyle::SLS_Inline;
19945   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
19946                LLVMWithBeforeLambdaBody);
19947   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
19948                LLVMWithBeforeLambdaBody);
19949   verifyFormat("auto fct_SLS_Inline = []()\n"
19950                "{\n"
19951                "  return 17;\n"
19952                "};",
19953                LLVMWithBeforeLambdaBody);
19954   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
19955                "17; }); });",
19956                LLVMWithBeforeLambdaBody);
19957   verifyFormat(
19958       "FctWithLongLineInLambda_SLS_Inline(\n"
19959       "    []()\n"
19960       "    {\n"
19961       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
19962       "                               AndShouldNotBeConsiderAsInline,\n"
19963       "                               LambdaBodyMustBeBreak);\n"
19964       "    });",
19965       LLVMWithBeforeLambdaBody);
19966   verifyFormat("FctWithMultipleParams_SLS_Inline("
19967                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
19968                "                                 []() { return 17; });",
19969                LLVMWithBeforeLambdaBody);
19970   verifyFormat(
19971       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
19972       LLVMWithBeforeLambdaBody);
19973 
19974   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19975       FormatStyle::ShortLambdaStyle::SLS_All;
19976   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
19977                LLVMWithBeforeLambdaBody);
19978   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
19979                LLVMWithBeforeLambdaBody);
19980   verifyFormat("auto fct_SLS_All = []() { return 17; };",
19981                LLVMWithBeforeLambdaBody);
19982   verifyFormat("FctWithOneParam_SLS_All(\n"
19983                "    []()\n"
19984                "    {\n"
19985                "      // A cool function...\n"
19986                "      return 43;\n"
19987                "    });",
19988                LLVMWithBeforeLambdaBody);
19989   verifyFormat("FctWithMultipleParams_SLS_All("
19990                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
19991                "                              []() { return 17; });",
19992                LLVMWithBeforeLambdaBody);
19993   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
19994                LLVMWithBeforeLambdaBody);
19995   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
19996                LLVMWithBeforeLambdaBody);
19997   verifyFormat(
19998       "FctWithLongLineInLambda_SLS_All(\n"
19999       "    []()\n"
20000       "    {\n"
20001       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20002       "                               AndShouldNotBeConsiderAsInline,\n"
20003       "                               LambdaBodyMustBeBreak);\n"
20004       "    });",
20005       LLVMWithBeforeLambdaBody);
20006   verifyFormat(
20007       "auto fct_SLS_All = []()\n"
20008       "{\n"
20009       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20010       "                           AndShouldNotBeConsiderAsInline,\n"
20011       "                           LambdaBodyMustBeBreak);\n"
20012       "};",
20013       LLVMWithBeforeLambdaBody);
20014   LLVMWithBeforeLambdaBody.BinPackParameters = false;
20015   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
20016                LLVMWithBeforeLambdaBody);
20017   verifyFormat(
20018       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
20019       "                                FirstParam,\n"
20020       "                                SecondParam,\n"
20021       "                                ThirdParam,\n"
20022       "                                FourthParam);",
20023       LLVMWithBeforeLambdaBody);
20024   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20025                "    []() { return "
20026                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
20027                "    FirstParam,\n"
20028                "    SecondParam,\n"
20029                "    ThirdParam,\n"
20030                "    FourthParam);",
20031                LLVMWithBeforeLambdaBody);
20032   verifyFormat(
20033       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
20034       "                                SecondParam,\n"
20035       "                                ThirdParam,\n"
20036       "                                FourthParam,\n"
20037       "                                []() { return SomeValueNotSoLong; });",
20038       LLVMWithBeforeLambdaBody);
20039   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20040                "    []()\n"
20041                "    {\n"
20042                "      return "
20043                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
20044                "eConsiderAsInline;\n"
20045                "    });",
20046                LLVMWithBeforeLambdaBody);
20047   verifyFormat(
20048       "FctWithLongLineInLambda_SLS_All(\n"
20049       "    []()\n"
20050       "    {\n"
20051       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20052       "                               AndShouldNotBeConsiderAsInline,\n"
20053       "                               LambdaBodyMustBeBreak);\n"
20054       "    });",
20055       LLVMWithBeforeLambdaBody);
20056   verifyFormat("FctWithTwoParams_SLS_All(\n"
20057                "    []()\n"
20058                "    {\n"
20059                "      // A cool function...\n"
20060                "      return 43;\n"
20061                "    },\n"
20062                "    87);",
20063                LLVMWithBeforeLambdaBody);
20064   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
20065                LLVMWithBeforeLambdaBody);
20066   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
20067                LLVMWithBeforeLambdaBody);
20068   verifyFormat(
20069       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
20070       LLVMWithBeforeLambdaBody);
20071   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
20072                "}); }, x);",
20073                LLVMWithBeforeLambdaBody);
20074   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20075                "    []()\n"
20076                "    {\n"
20077                "      // A cool function...\n"
20078                "      return Call([]() { return 17; });\n"
20079                "    });",
20080                LLVMWithBeforeLambdaBody);
20081   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20082                "    []()\n"
20083                "    {\n"
20084                "      return Call(\n"
20085                "          []()\n"
20086                "          {\n"
20087                "            // A cool function...\n"
20088                "            return 17;\n"
20089                "          });\n"
20090                "    });",
20091                LLVMWithBeforeLambdaBody);
20092 
20093   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20094       FormatStyle::ShortLambdaStyle::SLS_None;
20095 
20096   verifyFormat("auto select = [this]() -> const Library::Object *\n"
20097                "{\n"
20098                "  return MyAssignment::SelectFromList(this);\n"
20099                "};\n",
20100                LLVMWithBeforeLambdaBody);
20101 
20102   verifyFormat("auto select = [this]() -> const Library::Object &\n"
20103                "{\n"
20104                "  return MyAssignment::SelectFromList(this);\n"
20105                "};\n",
20106                LLVMWithBeforeLambdaBody);
20107 
20108   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
20109                "{\n"
20110                "  return MyAssignment::SelectFromList(this);\n"
20111                "};\n",
20112                LLVMWithBeforeLambdaBody);
20113 
20114   verifyFormat("namespace test {\n"
20115                "class Test {\n"
20116                "public:\n"
20117                "  Test() = default;\n"
20118                "};\n"
20119                "} // namespace test",
20120                LLVMWithBeforeLambdaBody);
20121 
20122   // Lambdas with different indentation styles.
20123   Style = getLLVMStyleWithColumns(100);
20124   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20125             "  return promise.then(\n"
20126             "      [this, &someVariable, someObject = "
20127             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20128             "        return someObject.startAsyncAction().then(\n"
20129             "            [this, &someVariable](AsyncActionResult result) "
20130             "mutable { result.processMore(); });\n"
20131             "      });\n"
20132             "}\n",
20133             format("SomeResult doSomething(SomeObject promise) {\n"
20134                    "  return promise.then([this, &someVariable, someObject = "
20135                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20136                    "    return someObject.startAsyncAction().then([this, "
20137                    "&someVariable](AsyncActionResult result) mutable {\n"
20138                    "      result.processMore();\n"
20139                    "    });\n"
20140                    "  });\n"
20141                    "}\n",
20142                    Style));
20143   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20144   verifyFormat("test() {\n"
20145                "  ([]() -> {\n"
20146                "    int b = 32;\n"
20147                "    return 3;\n"
20148                "  }).foo();\n"
20149                "}",
20150                Style);
20151   verifyFormat("test() {\n"
20152                "  []() -> {\n"
20153                "    int b = 32;\n"
20154                "    return 3;\n"
20155                "  }\n"
20156                "}",
20157                Style);
20158   verifyFormat("std::sort(v.begin(), v.end(),\n"
20159                "          [](const auto &someLongArgumentName, const auto "
20160                "&someOtherLongArgumentName) {\n"
20161                "  return someLongArgumentName.someMemberVariable < "
20162                "someOtherLongArgumentName.someMemberVariable;\n"
20163                "});",
20164                Style);
20165   verifyFormat("test() {\n"
20166                "  (\n"
20167                "      []() -> {\n"
20168                "        int b = 32;\n"
20169                "        return 3;\n"
20170                "      },\n"
20171                "      foo, bar)\n"
20172                "      .foo();\n"
20173                "}",
20174                Style);
20175   verifyFormat("test() {\n"
20176                "  ([]() -> {\n"
20177                "    int b = 32;\n"
20178                "    return 3;\n"
20179                "  })\n"
20180                "      .foo()\n"
20181                "      .bar();\n"
20182                "}",
20183                Style);
20184   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20185             "  return promise.then(\n"
20186             "      [this, &someVariable, someObject = "
20187             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20188             "    return someObject.startAsyncAction().then(\n"
20189             "        [this, &someVariable](AsyncActionResult result) mutable { "
20190             "result.processMore(); });\n"
20191             "  });\n"
20192             "}\n",
20193             format("SomeResult doSomething(SomeObject promise) {\n"
20194                    "  return promise.then([this, &someVariable, someObject = "
20195                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20196                    "    return someObject.startAsyncAction().then([this, "
20197                    "&someVariable](AsyncActionResult result) mutable {\n"
20198                    "      result.processMore();\n"
20199                    "    });\n"
20200                    "  });\n"
20201                    "}\n",
20202                    Style));
20203   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20204             "  return promise.then([this, &someVariable] {\n"
20205             "    return someObject.startAsyncAction().then(\n"
20206             "        [this, &someVariable](AsyncActionResult result) mutable { "
20207             "result.processMore(); });\n"
20208             "  });\n"
20209             "}\n",
20210             format("SomeResult doSomething(SomeObject promise) {\n"
20211                    "  return promise.then([this, &someVariable] {\n"
20212                    "    return someObject.startAsyncAction().then([this, "
20213                    "&someVariable](AsyncActionResult result) mutable {\n"
20214                    "      result.processMore();\n"
20215                    "    });\n"
20216                    "  });\n"
20217                    "}\n",
20218                    Style));
20219   Style = getGoogleStyle();
20220   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20221   EXPECT_EQ("#define A                                       \\\n"
20222             "  [] {                                          \\\n"
20223             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
20224             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
20225             "      }",
20226             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
20227                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
20228                    Style));
20229   // TODO: The current formatting has a minor issue that's not worth fixing
20230   // right now whereby the closing brace is indented relative to the signature
20231   // instead of being aligned. This only happens with macros.
20232 }
20233 
20234 TEST_F(FormatTest, LambdaWithLineComments) {
20235   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20236   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20237   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20238   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20239       FormatStyle::ShortLambdaStyle::SLS_All;
20240 
20241   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
20242   verifyFormat("auto k = []() // comment\n"
20243                "{ return; }",
20244                LLVMWithBeforeLambdaBody);
20245   verifyFormat("auto k = []() /* comment */ { return; }",
20246                LLVMWithBeforeLambdaBody);
20247   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
20248                LLVMWithBeforeLambdaBody);
20249   verifyFormat("auto k = []() // X\n"
20250                "{ return; }",
20251                LLVMWithBeforeLambdaBody);
20252   verifyFormat(
20253       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
20254       "{ return; }",
20255       LLVMWithBeforeLambdaBody);
20256 }
20257 
20258 TEST_F(FormatTest, EmptyLinesInLambdas) {
20259   verifyFormat("auto lambda = []() {\n"
20260                "  x(); //\n"
20261                "};",
20262                "auto lambda = []() {\n"
20263                "\n"
20264                "  x(); //\n"
20265                "\n"
20266                "};");
20267 }
20268 
20269 TEST_F(FormatTest, FormatsBlocks) {
20270   FormatStyle ShortBlocks = getLLVMStyle();
20271   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
20272   verifyFormat("int (^Block)(int, int);", ShortBlocks);
20273   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
20274   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
20275   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
20276   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
20277   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
20278 
20279   verifyFormat("foo(^{ bar(); });", ShortBlocks);
20280   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
20281   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
20282 
20283   verifyFormat("[operation setCompletionBlock:^{\n"
20284                "  [self onOperationDone];\n"
20285                "}];");
20286   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
20287                "  [self onOperationDone];\n"
20288                "}]};");
20289   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
20290                "  f();\n"
20291                "}];");
20292   verifyFormat("int a = [operation block:^int(int *i) {\n"
20293                "  return 1;\n"
20294                "}];");
20295   verifyFormat("[myObject doSomethingWith:arg1\n"
20296                "                      aaa:^int(int *a) {\n"
20297                "                        return 1;\n"
20298                "                      }\n"
20299                "                      bbb:f(a * bbbbbbbb)];");
20300 
20301   verifyFormat("[operation setCompletionBlock:^{\n"
20302                "  [self.delegate newDataAvailable];\n"
20303                "}];",
20304                getLLVMStyleWithColumns(60));
20305   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
20306                "  NSString *path = [self sessionFilePath];\n"
20307                "  if (path) {\n"
20308                "    // ...\n"
20309                "  }\n"
20310                "});");
20311   verifyFormat("[[SessionService sharedService]\n"
20312                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20313                "      if (window) {\n"
20314                "        [self windowDidLoad:window];\n"
20315                "      } else {\n"
20316                "        [self errorLoadingWindow];\n"
20317                "      }\n"
20318                "    }];");
20319   verifyFormat("void (^largeBlock)(void) = ^{\n"
20320                "  // ...\n"
20321                "};\n",
20322                getLLVMStyleWithColumns(40));
20323   verifyFormat("[[SessionService sharedService]\n"
20324                "    loadWindowWithCompletionBlock: //\n"
20325                "        ^(SessionWindow *window) {\n"
20326                "          if (window) {\n"
20327                "            [self windowDidLoad:window];\n"
20328                "          } else {\n"
20329                "            [self errorLoadingWindow];\n"
20330                "          }\n"
20331                "        }];",
20332                getLLVMStyleWithColumns(60));
20333   verifyFormat("[myObject doSomethingWith:arg1\n"
20334                "    firstBlock:^(Foo *a) {\n"
20335                "      // ...\n"
20336                "      int i;\n"
20337                "    }\n"
20338                "    secondBlock:^(Bar *b) {\n"
20339                "      // ...\n"
20340                "      int i;\n"
20341                "    }\n"
20342                "    thirdBlock:^Foo(Bar *b) {\n"
20343                "      // ...\n"
20344                "      int i;\n"
20345                "    }];");
20346   verifyFormat("[myObject doSomethingWith:arg1\n"
20347                "               firstBlock:-1\n"
20348                "              secondBlock:^(Bar *b) {\n"
20349                "                // ...\n"
20350                "                int i;\n"
20351                "              }];");
20352 
20353   verifyFormat("f(^{\n"
20354                "  @autoreleasepool {\n"
20355                "    if (a) {\n"
20356                "      g();\n"
20357                "    }\n"
20358                "  }\n"
20359                "});");
20360   verifyFormat("Block b = ^int *(A *a, B *b) {}");
20361   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
20362                "};");
20363 
20364   FormatStyle FourIndent = getLLVMStyle();
20365   FourIndent.ObjCBlockIndentWidth = 4;
20366   verifyFormat("[operation setCompletionBlock:^{\n"
20367                "    [self onOperationDone];\n"
20368                "}];",
20369                FourIndent);
20370 }
20371 
20372 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
20373   FormatStyle ZeroColumn = getLLVMStyle();
20374   ZeroColumn.ColumnLimit = 0;
20375 
20376   verifyFormat("[[SessionService sharedService] "
20377                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20378                "  if (window) {\n"
20379                "    [self windowDidLoad:window];\n"
20380                "  } else {\n"
20381                "    [self errorLoadingWindow];\n"
20382                "  }\n"
20383                "}];",
20384                ZeroColumn);
20385   EXPECT_EQ("[[SessionService sharedService]\n"
20386             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20387             "      if (window) {\n"
20388             "        [self windowDidLoad:window];\n"
20389             "      } else {\n"
20390             "        [self errorLoadingWindow];\n"
20391             "      }\n"
20392             "    }];",
20393             format("[[SessionService sharedService]\n"
20394                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20395                    "                if (window) {\n"
20396                    "    [self windowDidLoad:window];\n"
20397                    "  } else {\n"
20398                    "    [self errorLoadingWindow];\n"
20399                    "  }\n"
20400                    "}];",
20401                    ZeroColumn));
20402   verifyFormat("[myObject doSomethingWith:arg1\n"
20403                "    firstBlock:^(Foo *a) {\n"
20404                "      // ...\n"
20405                "      int i;\n"
20406                "    }\n"
20407                "    secondBlock:^(Bar *b) {\n"
20408                "      // ...\n"
20409                "      int i;\n"
20410                "    }\n"
20411                "    thirdBlock:^Foo(Bar *b) {\n"
20412                "      // ...\n"
20413                "      int i;\n"
20414                "    }];",
20415                ZeroColumn);
20416   verifyFormat("f(^{\n"
20417                "  @autoreleasepool {\n"
20418                "    if (a) {\n"
20419                "      g();\n"
20420                "    }\n"
20421                "  }\n"
20422                "});",
20423                ZeroColumn);
20424   verifyFormat("void (^largeBlock)(void) = ^{\n"
20425                "  // ...\n"
20426                "};",
20427                ZeroColumn);
20428 
20429   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
20430   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
20431             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
20432   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
20433   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
20434             "  int i;\n"
20435             "};",
20436             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
20437 }
20438 
20439 TEST_F(FormatTest, SupportsCRLF) {
20440   EXPECT_EQ("int a;\r\n"
20441             "int b;\r\n"
20442             "int c;\r\n",
20443             format("int a;\r\n"
20444                    "  int b;\r\n"
20445                    "    int c;\r\n",
20446                    getLLVMStyle()));
20447   EXPECT_EQ("int a;\r\n"
20448             "int b;\r\n"
20449             "int c;\r\n",
20450             format("int a;\r\n"
20451                    "  int b;\n"
20452                    "    int c;\r\n",
20453                    getLLVMStyle()));
20454   EXPECT_EQ("int a;\n"
20455             "int b;\n"
20456             "int c;\n",
20457             format("int a;\r\n"
20458                    "  int b;\n"
20459                    "    int c;\n",
20460                    getLLVMStyle()));
20461   EXPECT_EQ("\"aaaaaaa \"\r\n"
20462             "\"bbbbbbb\";\r\n",
20463             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
20464   EXPECT_EQ("#define A \\\r\n"
20465             "  b;      \\\r\n"
20466             "  c;      \\\r\n"
20467             "  d;\r\n",
20468             format("#define A \\\r\n"
20469                    "  b; \\\r\n"
20470                    "  c; d; \r\n",
20471                    getGoogleStyle()));
20472 
20473   EXPECT_EQ("/*\r\n"
20474             "multi line block comments\r\n"
20475             "should not introduce\r\n"
20476             "an extra carriage return\r\n"
20477             "*/\r\n",
20478             format("/*\r\n"
20479                    "multi line block comments\r\n"
20480                    "should not introduce\r\n"
20481                    "an extra carriage return\r\n"
20482                    "*/\r\n"));
20483   EXPECT_EQ("/*\r\n"
20484             "\r\n"
20485             "*/",
20486             format("/*\r\n"
20487                    "    \r\r\r\n"
20488                    "*/"));
20489 
20490   FormatStyle style = getLLVMStyle();
20491 
20492   style.DeriveLineEnding = true;
20493   style.UseCRLF = false;
20494   EXPECT_EQ("union FooBarBazQux {\n"
20495             "  int foo;\n"
20496             "  int bar;\n"
20497             "  int baz;\n"
20498             "};",
20499             format("union FooBarBazQux {\r\n"
20500                    "  int foo;\n"
20501                    "  int bar;\r\n"
20502                    "  int baz;\n"
20503                    "};",
20504                    style));
20505   style.UseCRLF = true;
20506   EXPECT_EQ("union FooBarBazQux {\r\n"
20507             "  int foo;\r\n"
20508             "  int bar;\r\n"
20509             "  int baz;\r\n"
20510             "};",
20511             format("union FooBarBazQux {\r\n"
20512                    "  int foo;\n"
20513                    "  int bar;\r\n"
20514                    "  int baz;\n"
20515                    "};",
20516                    style));
20517 
20518   style.DeriveLineEnding = false;
20519   style.UseCRLF = false;
20520   EXPECT_EQ("union FooBarBazQux {\n"
20521             "  int foo;\n"
20522             "  int bar;\n"
20523             "  int baz;\n"
20524             "  int qux;\n"
20525             "};",
20526             format("union FooBarBazQux {\r\n"
20527                    "  int foo;\n"
20528                    "  int bar;\r\n"
20529                    "  int baz;\n"
20530                    "  int qux;\r\n"
20531                    "};",
20532                    style));
20533   style.UseCRLF = true;
20534   EXPECT_EQ("union FooBarBazQux {\r\n"
20535             "  int foo;\r\n"
20536             "  int bar;\r\n"
20537             "  int baz;\r\n"
20538             "  int qux;\r\n"
20539             "};",
20540             format("union FooBarBazQux {\r\n"
20541                    "  int foo;\n"
20542                    "  int bar;\r\n"
20543                    "  int baz;\n"
20544                    "  int qux;\n"
20545                    "};",
20546                    style));
20547 
20548   style.DeriveLineEnding = true;
20549   style.UseCRLF = false;
20550   EXPECT_EQ("union FooBarBazQux {\r\n"
20551             "  int foo;\r\n"
20552             "  int bar;\r\n"
20553             "  int baz;\r\n"
20554             "  int qux;\r\n"
20555             "};",
20556             format("union FooBarBazQux {\r\n"
20557                    "  int foo;\n"
20558                    "  int bar;\r\n"
20559                    "  int baz;\n"
20560                    "  int qux;\r\n"
20561                    "};",
20562                    style));
20563   style.UseCRLF = true;
20564   EXPECT_EQ("union FooBarBazQux {\n"
20565             "  int foo;\n"
20566             "  int bar;\n"
20567             "  int baz;\n"
20568             "  int qux;\n"
20569             "};",
20570             format("union FooBarBazQux {\r\n"
20571                    "  int foo;\n"
20572                    "  int bar;\r\n"
20573                    "  int baz;\n"
20574                    "  int qux;\n"
20575                    "};",
20576                    style));
20577 }
20578 
20579 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
20580   verifyFormat("MY_CLASS(C) {\n"
20581                "  int i;\n"
20582                "  int j;\n"
20583                "};");
20584 }
20585 
20586 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
20587   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
20588   TwoIndent.ContinuationIndentWidth = 2;
20589 
20590   EXPECT_EQ("int i =\n"
20591             "  longFunction(\n"
20592             "    arg);",
20593             format("int i = longFunction(arg);", TwoIndent));
20594 
20595   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
20596   SixIndent.ContinuationIndentWidth = 6;
20597 
20598   EXPECT_EQ("int i =\n"
20599             "      longFunction(\n"
20600             "            arg);",
20601             format("int i = longFunction(arg);", SixIndent));
20602 }
20603 
20604 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
20605   FormatStyle Style = getLLVMStyle();
20606   verifyFormat("int Foo::getter(\n"
20607                "    //\n"
20608                ") const {\n"
20609                "  return foo;\n"
20610                "}",
20611                Style);
20612   verifyFormat("void Foo::setter(\n"
20613                "    //\n"
20614                ") {\n"
20615                "  foo = 1;\n"
20616                "}",
20617                Style);
20618 }
20619 
20620 TEST_F(FormatTest, SpacesInAngles) {
20621   FormatStyle Spaces = getLLVMStyle();
20622   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
20623 
20624   verifyFormat("vector< ::std::string > x1;", Spaces);
20625   verifyFormat("Foo< int, Bar > x2;", Spaces);
20626   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
20627 
20628   verifyFormat("static_cast< int >(arg);", Spaces);
20629   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
20630   verifyFormat("f< int, float >();", Spaces);
20631   verifyFormat("template <> g() {}", Spaces);
20632   verifyFormat("template < std::vector< int > > f() {}", Spaces);
20633   verifyFormat("std::function< void(int, int) > fct;", Spaces);
20634   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
20635                Spaces);
20636 
20637   Spaces.Standard = FormatStyle::LS_Cpp03;
20638   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
20639   verifyFormat("A< A< int > >();", Spaces);
20640 
20641   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
20642   verifyFormat("A<A<int> >();", Spaces);
20643 
20644   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
20645   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
20646                Spaces);
20647   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
20648                Spaces);
20649 
20650   verifyFormat("A<A<int> >();", Spaces);
20651   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
20652   verifyFormat("A< A< int > >();", Spaces);
20653 
20654   Spaces.Standard = FormatStyle::LS_Cpp11;
20655   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
20656   verifyFormat("A< A< int > >();", Spaces);
20657 
20658   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
20659   verifyFormat("vector<::std::string> x4;", Spaces);
20660   verifyFormat("vector<int> x5;", Spaces);
20661   verifyFormat("Foo<int, Bar> x6;", Spaces);
20662   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
20663 
20664   verifyFormat("A<A<int>>();", Spaces);
20665 
20666   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
20667   verifyFormat("vector<::std::string> x4;", Spaces);
20668   verifyFormat("vector< ::std::string > x4;", Spaces);
20669   verifyFormat("vector<int> x5;", Spaces);
20670   verifyFormat("vector< int > x5;", Spaces);
20671   verifyFormat("Foo<int, Bar> x6;", Spaces);
20672   verifyFormat("Foo< int, Bar > x6;", Spaces);
20673   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
20674   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
20675 
20676   verifyFormat("A<A<int>>();", Spaces);
20677   verifyFormat("A< A< int > >();", Spaces);
20678   verifyFormat("A<A<int > >();", Spaces);
20679   verifyFormat("A< A< int>>();", Spaces);
20680 }
20681 
20682 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
20683   FormatStyle Style = getLLVMStyle();
20684   Style.SpaceAfterTemplateKeyword = false;
20685   verifyFormat("template<int> void foo();", Style);
20686 }
20687 
20688 TEST_F(FormatTest, TripleAngleBrackets) {
20689   verifyFormat("f<<<1, 1>>>();");
20690   verifyFormat("f<<<1, 1, 1, s>>>();");
20691   verifyFormat("f<<<a, b, c, d>>>();");
20692   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
20693   verifyFormat("f<param><<<1, 1>>>();");
20694   verifyFormat("f<1><<<1, 1>>>();");
20695   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
20696   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
20697                "aaaaaaaaaaa<<<\n    1, 1>>>();");
20698   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
20699                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
20700 }
20701 
20702 TEST_F(FormatTest, MergeLessLessAtEnd) {
20703   verifyFormat("<<");
20704   EXPECT_EQ("< < <", format("\\\n<<<"));
20705   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
20706                "aaallvm::outs() <<");
20707   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
20708                "aaaallvm::outs()\n    <<");
20709 }
20710 
20711 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
20712   std::string code = "#if A\n"
20713                      "#if B\n"
20714                      "a.\n"
20715                      "#endif\n"
20716                      "    a = 1;\n"
20717                      "#else\n"
20718                      "#endif\n"
20719                      "#if C\n"
20720                      "#else\n"
20721                      "#endif\n";
20722   EXPECT_EQ(code, format(code));
20723 }
20724 
20725 TEST_F(FormatTest, HandleConflictMarkers) {
20726   // Git/SVN conflict markers.
20727   EXPECT_EQ("int a;\n"
20728             "void f() {\n"
20729             "  callme(some(parameter1,\n"
20730             "<<<<<<< text by the vcs\n"
20731             "              parameter2),\n"
20732             "||||||| text by the vcs\n"
20733             "              parameter2),\n"
20734             "         parameter3,\n"
20735             "======= text by the vcs\n"
20736             "              parameter2, parameter3),\n"
20737             ">>>>>>> text by the vcs\n"
20738             "         otherparameter);\n",
20739             format("int a;\n"
20740                    "void f() {\n"
20741                    "  callme(some(parameter1,\n"
20742                    "<<<<<<< text by the vcs\n"
20743                    "  parameter2),\n"
20744                    "||||||| text by the vcs\n"
20745                    "  parameter2),\n"
20746                    "  parameter3,\n"
20747                    "======= text by the vcs\n"
20748                    "  parameter2,\n"
20749                    "  parameter3),\n"
20750                    ">>>>>>> text by the vcs\n"
20751                    "  otherparameter);\n"));
20752 
20753   // Perforce markers.
20754   EXPECT_EQ("void f() {\n"
20755             "  function(\n"
20756             ">>>> text by the vcs\n"
20757             "      parameter,\n"
20758             "==== text by the vcs\n"
20759             "      parameter,\n"
20760             "==== text by the vcs\n"
20761             "      parameter,\n"
20762             "<<<< text by the vcs\n"
20763             "      parameter);\n",
20764             format("void f() {\n"
20765                    "  function(\n"
20766                    ">>>> text by the vcs\n"
20767                    "  parameter,\n"
20768                    "==== text by the vcs\n"
20769                    "  parameter,\n"
20770                    "==== text by the vcs\n"
20771                    "  parameter,\n"
20772                    "<<<< text by the vcs\n"
20773                    "  parameter);\n"));
20774 
20775   EXPECT_EQ("<<<<<<<\n"
20776             "|||||||\n"
20777             "=======\n"
20778             ">>>>>>>",
20779             format("<<<<<<<\n"
20780                    "|||||||\n"
20781                    "=======\n"
20782                    ">>>>>>>"));
20783 
20784   EXPECT_EQ("<<<<<<<\n"
20785             "|||||||\n"
20786             "int i;\n"
20787             "=======\n"
20788             ">>>>>>>",
20789             format("<<<<<<<\n"
20790                    "|||||||\n"
20791                    "int i;\n"
20792                    "=======\n"
20793                    ">>>>>>>"));
20794 
20795   // FIXME: Handle parsing of macros around conflict markers correctly:
20796   EXPECT_EQ("#define Macro \\\n"
20797             "<<<<<<<\n"
20798             "Something \\\n"
20799             "|||||||\n"
20800             "Else \\\n"
20801             "=======\n"
20802             "Other \\\n"
20803             ">>>>>>>\n"
20804             "    End int i;\n",
20805             format("#define Macro \\\n"
20806                    "<<<<<<<\n"
20807                    "  Something \\\n"
20808                    "|||||||\n"
20809                    "  Else \\\n"
20810                    "=======\n"
20811                    "  Other \\\n"
20812                    ">>>>>>>\n"
20813                    "  End\n"
20814                    "int i;\n"));
20815 }
20816 
20817 TEST_F(FormatTest, DisableRegions) {
20818   EXPECT_EQ("int i;\n"
20819             "// clang-format off\n"
20820             "  int j;\n"
20821             "// clang-format on\n"
20822             "int k;",
20823             format(" int  i;\n"
20824                    "   // clang-format off\n"
20825                    "  int j;\n"
20826                    " // clang-format on\n"
20827                    "   int   k;"));
20828   EXPECT_EQ("int i;\n"
20829             "/* clang-format off */\n"
20830             "  int j;\n"
20831             "/* clang-format on */\n"
20832             "int k;",
20833             format(" int  i;\n"
20834                    "   /* clang-format off */\n"
20835                    "  int j;\n"
20836                    " /* clang-format on */\n"
20837                    "   int   k;"));
20838 
20839   // Don't reflow comments within disabled regions.
20840   EXPECT_EQ("// clang-format off\n"
20841             "// long long long long long long line\n"
20842             "/* clang-format on */\n"
20843             "/* long long long\n"
20844             " * long long long\n"
20845             " * line */\n"
20846             "int i;\n"
20847             "/* clang-format off */\n"
20848             "/* long long long long long long line */\n",
20849             format("// clang-format off\n"
20850                    "// long long long long long long line\n"
20851                    "/* clang-format on */\n"
20852                    "/* long long long long long long line */\n"
20853                    "int i;\n"
20854                    "/* clang-format off */\n"
20855                    "/* long long long long long long line */\n",
20856                    getLLVMStyleWithColumns(20)));
20857 }
20858 
20859 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
20860   format("? ) =");
20861   verifyNoCrash("#define a\\\n /**/}");
20862 }
20863 
20864 TEST_F(FormatTest, FormatsTableGenCode) {
20865   FormatStyle Style = getLLVMStyle();
20866   Style.Language = FormatStyle::LK_TableGen;
20867   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
20868 }
20869 
20870 TEST_F(FormatTest, ArrayOfTemplates) {
20871   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
20872             format("auto a = new unique_ptr<int > [ 10];"));
20873 
20874   FormatStyle Spaces = getLLVMStyle();
20875   Spaces.SpacesInSquareBrackets = true;
20876   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
20877             format("auto a = new unique_ptr<int > [10];", Spaces));
20878 }
20879 
20880 TEST_F(FormatTest, ArrayAsTemplateType) {
20881   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
20882             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
20883 
20884   FormatStyle Spaces = getLLVMStyle();
20885   Spaces.SpacesInSquareBrackets = true;
20886   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
20887             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
20888 }
20889 
20890 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
20891 
20892 TEST(FormatStyle, GetStyleWithEmptyFileName) {
20893   llvm::vfs::InMemoryFileSystem FS;
20894   auto Style1 = getStyle("file", "", "Google", "", &FS);
20895   ASSERT_TRUE((bool)Style1);
20896   ASSERT_EQ(*Style1, getGoogleStyle());
20897 }
20898 
20899 TEST(FormatStyle, GetStyleOfFile) {
20900   llvm::vfs::InMemoryFileSystem FS;
20901   // Test 1: format file in the same directory.
20902   ASSERT_TRUE(
20903       FS.addFile("/a/.clang-format", 0,
20904                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
20905   ASSERT_TRUE(
20906       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
20907   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
20908   ASSERT_TRUE((bool)Style1);
20909   ASSERT_EQ(*Style1, getLLVMStyle());
20910 
20911   // Test 2.1: fallback to default.
20912   ASSERT_TRUE(
20913       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
20914   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
20915   ASSERT_TRUE((bool)Style2);
20916   ASSERT_EQ(*Style2, getMozillaStyle());
20917 
20918   // Test 2.2: no format on 'none' fallback style.
20919   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
20920   ASSERT_TRUE((bool)Style2);
20921   ASSERT_EQ(*Style2, getNoStyle());
20922 
20923   // Test 2.3: format if config is found with no based style while fallback is
20924   // 'none'.
20925   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
20926                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
20927   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
20928   ASSERT_TRUE((bool)Style2);
20929   ASSERT_EQ(*Style2, getLLVMStyle());
20930 
20931   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
20932   Style2 = getStyle("{}", "a.h", "none", "", &FS);
20933   ASSERT_TRUE((bool)Style2);
20934   ASSERT_EQ(*Style2, getLLVMStyle());
20935 
20936   // Test 3: format file in parent directory.
20937   ASSERT_TRUE(
20938       FS.addFile("/c/.clang-format", 0,
20939                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
20940   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
20941                          llvm::MemoryBuffer::getMemBuffer("int i;")));
20942   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
20943   ASSERT_TRUE((bool)Style3);
20944   ASSERT_EQ(*Style3, getGoogleStyle());
20945 
20946   // Test 4: error on invalid fallback style
20947   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
20948   ASSERT_FALSE((bool)Style4);
20949   llvm::consumeError(Style4.takeError());
20950 
20951   // Test 5: error on invalid yaml on command line
20952   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
20953   ASSERT_FALSE((bool)Style5);
20954   llvm::consumeError(Style5.takeError());
20955 
20956   // Test 6: error on invalid style
20957   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
20958   ASSERT_FALSE((bool)Style6);
20959   llvm::consumeError(Style6.takeError());
20960 
20961   // Test 7: found config file, error on parsing it
20962   ASSERT_TRUE(
20963       FS.addFile("/d/.clang-format", 0,
20964                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
20965                                                   "InvalidKey: InvalidValue")));
20966   ASSERT_TRUE(
20967       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
20968   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
20969   ASSERT_FALSE((bool)Style7a);
20970   llvm::consumeError(Style7a.takeError());
20971 
20972   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
20973   ASSERT_TRUE((bool)Style7b);
20974 
20975   // Test 8: inferred per-language defaults apply.
20976   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
20977   ASSERT_TRUE((bool)StyleTd);
20978   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
20979 
20980   // Test 9.1: overwriting a file style, when parent no file exists with no
20981   // fallback style
20982   ASSERT_TRUE(FS.addFile(
20983       "/e/sub/.clang-format", 0,
20984       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
20985                                        "ColumnLimit: 20")));
20986   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
20987                          llvm::MemoryBuffer::getMemBuffer("int i;")));
20988   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
20989   ASSERT_TRUE(static_cast<bool>(Style9));
20990   ASSERT_EQ(*Style9, [] {
20991     auto Style = getNoStyle();
20992     Style.ColumnLimit = 20;
20993     return Style;
20994   }());
20995 
20996   // Test 9.2: with LLVM fallback style
20997   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
20998   ASSERT_TRUE(static_cast<bool>(Style9));
20999   ASSERT_EQ(*Style9, [] {
21000     auto Style = getLLVMStyle();
21001     Style.ColumnLimit = 20;
21002     return Style;
21003   }());
21004 
21005   // Test 9.3: with a parent file
21006   ASSERT_TRUE(
21007       FS.addFile("/e/.clang-format", 0,
21008                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
21009                                                   "UseTab: Always")));
21010   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21011   ASSERT_TRUE(static_cast<bool>(Style9));
21012   ASSERT_EQ(*Style9, [] {
21013     auto Style = getGoogleStyle();
21014     Style.ColumnLimit = 20;
21015     Style.UseTab = FormatStyle::UT_Always;
21016     return Style;
21017   }());
21018 
21019   // Test 9.4: propagate more than one level
21020   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
21021                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21022   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
21023                          llvm::MemoryBuffer::getMemBuffer(
21024                              "BasedOnStyle: InheritParentConfig\n"
21025                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
21026   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
21027 
21028   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
21029     auto Style = getGoogleStyle();
21030     Style.ColumnLimit = 20;
21031     Style.UseTab = FormatStyle::UT_Always;
21032     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21033     return Style;
21034   }();
21035 
21036   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21037   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21038   ASSERT_TRUE(static_cast<bool>(Style9));
21039   ASSERT_EQ(*Style9, SubSubStyle);
21040 
21041   // Test 9.5: use InheritParentConfig as style name
21042   Style9 =
21043       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
21044   ASSERT_TRUE(static_cast<bool>(Style9));
21045   ASSERT_EQ(*Style9, SubSubStyle);
21046 
21047   // Test 9.6: use command line style with inheritance
21048   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
21049                     "none", "", &FS);
21050   ASSERT_TRUE(static_cast<bool>(Style9));
21051   ASSERT_EQ(*Style9, SubSubStyle);
21052 
21053   // Test 9.7: use command line style with inheritance and own config
21054   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
21055                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
21056                     "/e/sub/code.cpp", "none", "", &FS);
21057   ASSERT_TRUE(static_cast<bool>(Style9));
21058   ASSERT_EQ(*Style9, SubSubStyle);
21059 
21060   // Test 9.8: use inheritance from a file without BasedOnStyle
21061   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
21062                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
21063   ASSERT_TRUE(
21064       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
21065                  llvm::MemoryBuffer::getMemBuffer(
21066                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
21067   // Make sure we do not use the fallback style
21068   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
21069   ASSERT_TRUE(static_cast<bool>(Style9));
21070   ASSERT_EQ(*Style9, [] {
21071     auto Style = getLLVMStyle();
21072     Style.ColumnLimit = 123;
21073     return Style;
21074   }());
21075 
21076   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
21077   ASSERT_TRUE(static_cast<bool>(Style9));
21078   ASSERT_EQ(*Style9, [] {
21079     auto Style = getLLVMStyle();
21080     Style.ColumnLimit = 123;
21081     Style.IndentWidth = 7;
21082     return Style;
21083   }());
21084 }
21085 
21086 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
21087   // Column limit is 20.
21088   std::string Code = "Type *a =\n"
21089                      "    new Type();\n"
21090                      "g(iiiii, 0, jjjjj,\n"
21091                      "  0, kkkkk, 0, mm);\n"
21092                      "int  bad     = format   ;";
21093   std::string Expected = "auto a = new Type();\n"
21094                          "g(iiiii, nullptr,\n"
21095                          "  jjjjj, nullptr,\n"
21096                          "  kkkkk, nullptr,\n"
21097                          "  mm);\n"
21098                          "int  bad     = format   ;";
21099   FileID ID = Context.createInMemoryFile("format.cpp", Code);
21100   tooling::Replacements Replaces = toReplacements(
21101       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
21102                             "auto "),
21103        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
21104                             "nullptr"),
21105        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
21106                             "nullptr"),
21107        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
21108                             "nullptr")});
21109 
21110   format::FormatStyle Style = format::getLLVMStyle();
21111   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
21112   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21113   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21114       << llvm::toString(FormattedReplaces.takeError()) << "\n";
21115   auto Result = applyAllReplacements(Code, *FormattedReplaces);
21116   EXPECT_TRUE(static_cast<bool>(Result));
21117   EXPECT_EQ(Expected, *Result);
21118 }
21119 
21120 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
21121   std::string Code = "#include \"a.h\"\n"
21122                      "#include \"c.h\"\n"
21123                      "\n"
21124                      "int main() {\n"
21125                      "  return 0;\n"
21126                      "}";
21127   std::string Expected = "#include \"a.h\"\n"
21128                          "#include \"b.h\"\n"
21129                          "#include \"c.h\"\n"
21130                          "\n"
21131                          "int main() {\n"
21132                          "  return 0;\n"
21133                          "}";
21134   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
21135   tooling::Replacements Replaces = toReplacements(
21136       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
21137                             "#include \"b.h\"\n")});
21138 
21139   format::FormatStyle Style = format::getLLVMStyle();
21140   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
21141   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21142   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21143       << llvm::toString(FormattedReplaces.takeError()) << "\n";
21144   auto Result = applyAllReplacements(Code, *FormattedReplaces);
21145   EXPECT_TRUE(static_cast<bool>(Result));
21146   EXPECT_EQ(Expected, *Result);
21147 }
21148 
21149 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
21150   EXPECT_EQ("using std::cin;\n"
21151             "using std::cout;",
21152             format("using std::cout;\n"
21153                    "using std::cin;",
21154                    getGoogleStyle()));
21155 }
21156 
21157 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
21158   format::FormatStyle Style = format::getLLVMStyle();
21159   Style.Standard = FormatStyle::LS_Cpp03;
21160   // cpp03 recognize this string as identifier u8 and literal character 'a'
21161   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
21162 }
21163 
21164 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
21165   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
21166   // all modes, including C++11, C++14 and C++17
21167   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
21168 }
21169 
21170 TEST_F(FormatTest, DoNotFormatLikelyXml) {
21171   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
21172   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
21173 }
21174 
21175 TEST_F(FormatTest, StructuredBindings) {
21176   // Structured bindings is a C++17 feature.
21177   // all modes, including C++11, C++14 and C++17
21178   verifyFormat("auto [a, b] = f();");
21179   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
21180   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
21181   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
21182   EXPECT_EQ("auto const volatile [a, b] = f();",
21183             format("auto  const   volatile[a, b] = f();"));
21184   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
21185   EXPECT_EQ("auto &[a, b, c] = f();",
21186             format("auto   &[  a  ,  b,c   ] = f();"));
21187   EXPECT_EQ("auto &&[a, b, c] = f();",
21188             format("auto   &&[  a  ,  b,c   ] = f();"));
21189   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
21190   EXPECT_EQ("auto const volatile &&[a, b] = f();",
21191             format("auto  const  volatile  &&[a, b] = f();"));
21192   EXPECT_EQ("auto const &&[a, b] = f();",
21193             format("auto  const   &&  [a, b] = f();"));
21194   EXPECT_EQ("const auto &[a, b] = f();",
21195             format("const  auto  &  [a, b] = f();"));
21196   EXPECT_EQ("const auto volatile &&[a, b] = f();",
21197             format("const  auto   volatile  &&[a, b] = f();"));
21198   EXPECT_EQ("volatile const auto &&[a, b] = f();",
21199             format("volatile  const  auto   &&[a, b] = f();"));
21200   EXPECT_EQ("const auto &&[a, b] = f();",
21201             format("const  auto  &&  [a, b] = f();"));
21202 
21203   // Make sure we don't mistake structured bindings for lambdas.
21204   FormatStyle PointerMiddle = getLLVMStyle();
21205   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
21206   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
21207   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
21208   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
21209   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
21210   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
21211   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
21212   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
21213   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
21214   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
21215   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
21216   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
21217   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
21218 
21219   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
21220             format("for (const auto   &&   [a, b] : some_range) {\n}"));
21221   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
21222             format("for (const auto   &   [a, b] : some_range) {\n}"));
21223   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
21224             format("for (const auto[a, b] : some_range) {\n}"));
21225   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
21226   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
21227   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
21228   EXPECT_EQ("auto const &[x, y](expr);",
21229             format("auto  const  &  [x,y]  (expr);"));
21230   EXPECT_EQ("auto const &&[x, y](expr);",
21231             format("auto  const  &&  [x,y]  (expr);"));
21232   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
21233   EXPECT_EQ("auto const &[x, y]{expr};",
21234             format("auto  const  &  [x,y]  {expr};"));
21235   EXPECT_EQ("auto const &&[x, y]{expr};",
21236             format("auto  const  &&  [x,y]  {expr};"));
21237 
21238   format::FormatStyle Spaces = format::getLLVMStyle();
21239   Spaces.SpacesInSquareBrackets = true;
21240   verifyFormat("auto [ a, b ] = f();", Spaces);
21241   verifyFormat("auto &&[ a, b ] = f();", Spaces);
21242   verifyFormat("auto &[ a, b ] = f();", Spaces);
21243   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
21244   verifyFormat("auto const &[ a, b ] = f();", Spaces);
21245 }
21246 
21247 TEST_F(FormatTest, FileAndCode) {
21248   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
21249   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
21250   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
21251   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
21252   EXPECT_EQ(FormatStyle::LK_ObjC,
21253             guessLanguage("foo.h", "@interface Foo\n@end\n"));
21254   EXPECT_EQ(
21255       FormatStyle::LK_ObjC,
21256       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
21257   EXPECT_EQ(FormatStyle::LK_ObjC,
21258             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
21259   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
21260   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
21261   EXPECT_EQ(FormatStyle::LK_ObjC,
21262             guessLanguage("foo", "@interface Foo\n@end\n"));
21263   EXPECT_EQ(FormatStyle::LK_ObjC,
21264             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
21265   EXPECT_EQ(
21266       FormatStyle::LK_ObjC,
21267       guessLanguage("foo.h",
21268                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
21269   EXPECT_EQ(
21270       FormatStyle::LK_Cpp,
21271       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
21272 }
21273 
21274 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
21275   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
21276   EXPECT_EQ(FormatStyle::LK_ObjC,
21277             guessLanguage("foo.h", "array[[calculator getIndex]];"));
21278   EXPECT_EQ(FormatStyle::LK_Cpp,
21279             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
21280   EXPECT_EQ(
21281       FormatStyle::LK_Cpp,
21282       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
21283   EXPECT_EQ(FormatStyle::LK_ObjC,
21284             guessLanguage("foo.h", "[[noreturn foo] bar];"));
21285   EXPECT_EQ(FormatStyle::LK_Cpp,
21286             guessLanguage("foo.h", "[[clang::fallthrough]];"));
21287   EXPECT_EQ(FormatStyle::LK_ObjC,
21288             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
21289   EXPECT_EQ(FormatStyle::LK_Cpp,
21290             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
21291   EXPECT_EQ(FormatStyle::LK_Cpp,
21292             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
21293   EXPECT_EQ(FormatStyle::LK_ObjC,
21294             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
21295   EXPECT_EQ(FormatStyle::LK_Cpp,
21296             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
21297   EXPECT_EQ(
21298       FormatStyle::LK_Cpp,
21299       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
21300   EXPECT_EQ(
21301       FormatStyle::LK_Cpp,
21302       guessLanguage("foo.h",
21303                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
21304   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
21305 }
21306 
21307 TEST_F(FormatTest, GuessLanguageWithCaret) {
21308   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
21309   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
21310   EXPECT_EQ(FormatStyle::LK_ObjC,
21311             guessLanguage("foo.h", "int(^)(char, float);"));
21312   EXPECT_EQ(FormatStyle::LK_ObjC,
21313             guessLanguage("foo.h", "int(^foo)(char, float);"));
21314   EXPECT_EQ(FormatStyle::LK_ObjC,
21315             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
21316   EXPECT_EQ(FormatStyle::LK_ObjC,
21317             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
21318   EXPECT_EQ(
21319       FormatStyle::LK_ObjC,
21320       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
21321 }
21322 
21323 TEST_F(FormatTest, GuessLanguageWithPragmas) {
21324   EXPECT_EQ(FormatStyle::LK_Cpp,
21325             guessLanguage("foo.h", "__pragma(warning(disable:))"));
21326   EXPECT_EQ(FormatStyle::LK_Cpp,
21327             guessLanguage("foo.h", "#pragma(warning(disable:))"));
21328   EXPECT_EQ(FormatStyle::LK_Cpp,
21329             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
21330 }
21331 
21332 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
21333   // ASM symbolic names are identifiers that must be surrounded by [] without
21334   // space in between:
21335   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
21336 
21337   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
21338   verifyFormat(R"(//
21339 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
21340 )");
21341 
21342   // A list of several ASM symbolic names.
21343   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
21344 
21345   // ASM symbolic names in inline ASM with inputs and outputs.
21346   verifyFormat(R"(//
21347 asm("cmoveq %1, %2, %[result]"
21348     : [result] "=r"(result)
21349     : "r"(test), "r"(new), "[result]"(old));
21350 )");
21351 
21352   // ASM symbolic names in inline ASM with no outputs.
21353   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
21354 }
21355 
21356 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
21357   EXPECT_EQ(FormatStyle::LK_Cpp,
21358             guessLanguage("foo.h", "void f() {\n"
21359                                    "  asm (\"mov %[e], %[d]\"\n"
21360                                    "     : [d] \"=rm\" (d)\n"
21361                                    "       [e] \"rm\" (*e));\n"
21362                                    "}"));
21363   EXPECT_EQ(FormatStyle::LK_Cpp,
21364             guessLanguage("foo.h", "void f() {\n"
21365                                    "  _asm (\"mov %[e], %[d]\"\n"
21366                                    "     : [d] \"=rm\" (d)\n"
21367                                    "       [e] \"rm\" (*e));\n"
21368                                    "}"));
21369   EXPECT_EQ(FormatStyle::LK_Cpp,
21370             guessLanguage("foo.h", "void f() {\n"
21371                                    "  __asm (\"mov %[e], %[d]\"\n"
21372                                    "     : [d] \"=rm\" (d)\n"
21373                                    "       [e] \"rm\" (*e));\n"
21374                                    "}"));
21375   EXPECT_EQ(FormatStyle::LK_Cpp,
21376             guessLanguage("foo.h", "void f() {\n"
21377                                    "  __asm__ (\"mov %[e], %[d]\"\n"
21378                                    "     : [d] \"=rm\" (d)\n"
21379                                    "       [e] \"rm\" (*e));\n"
21380                                    "}"));
21381   EXPECT_EQ(FormatStyle::LK_Cpp,
21382             guessLanguage("foo.h", "void f() {\n"
21383                                    "  asm (\"mov %[e], %[d]\"\n"
21384                                    "     : [d] \"=rm\" (d),\n"
21385                                    "       [e] \"rm\" (*e));\n"
21386                                    "}"));
21387   EXPECT_EQ(FormatStyle::LK_Cpp,
21388             guessLanguage("foo.h", "void f() {\n"
21389                                    "  asm volatile (\"mov %[e], %[d]\"\n"
21390                                    "     : [d] \"=rm\" (d)\n"
21391                                    "       [e] \"rm\" (*e));\n"
21392                                    "}"));
21393 }
21394 
21395 TEST_F(FormatTest, GuessLanguageWithChildLines) {
21396   EXPECT_EQ(FormatStyle::LK_Cpp,
21397             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
21398   EXPECT_EQ(FormatStyle::LK_ObjC,
21399             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
21400   EXPECT_EQ(
21401       FormatStyle::LK_Cpp,
21402       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
21403   EXPECT_EQ(
21404       FormatStyle::LK_ObjC,
21405       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
21406 }
21407 
21408 TEST_F(FormatTest, TypenameMacros) {
21409   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
21410 
21411   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
21412   FormatStyle Google = getGoogleStyleWithColumns(0);
21413   Google.TypenameMacros = TypenameMacros;
21414   verifyFormat("struct foo {\n"
21415                "  int bar;\n"
21416                "  TAILQ_ENTRY(a) bleh;\n"
21417                "};",
21418                Google);
21419 
21420   FormatStyle Macros = getLLVMStyle();
21421   Macros.TypenameMacros = TypenameMacros;
21422 
21423   verifyFormat("STACK_OF(int) a;", Macros);
21424   verifyFormat("STACK_OF(int) *a;", Macros);
21425   verifyFormat("STACK_OF(int const *) *a;", Macros);
21426   verifyFormat("STACK_OF(int *const) *a;", Macros);
21427   verifyFormat("STACK_OF(int, string) a;", Macros);
21428   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
21429   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
21430   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
21431   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
21432   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
21433   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
21434 
21435   Macros.PointerAlignment = FormatStyle::PAS_Left;
21436   verifyFormat("STACK_OF(int)* a;", Macros);
21437   verifyFormat("STACK_OF(int*)* a;", Macros);
21438   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
21439   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
21440   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
21441 }
21442 
21443 TEST_F(FormatTest, AtomicQualifier) {
21444   // Check that we treate _Atomic as a type and not a function call
21445   FormatStyle Google = getGoogleStyleWithColumns(0);
21446   verifyFormat("struct foo {\n"
21447                "  int a1;\n"
21448                "  _Atomic(a) a2;\n"
21449                "  _Atomic(_Atomic(int) *const) a3;\n"
21450                "};",
21451                Google);
21452   verifyFormat("_Atomic(uint64_t) a;");
21453   verifyFormat("_Atomic(uint64_t) *a;");
21454   verifyFormat("_Atomic(uint64_t const *) *a;");
21455   verifyFormat("_Atomic(uint64_t *const) *a;");
21456   verifyFormat("_Atomic(const uint64_t *) *a;");
21457   verifyFormat("_Atomic(uint64_t) a;");
21458   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
21459   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
21460   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
21461   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
21462 
21463   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
21464   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
21465   FormatStyle Style = getLLVMStyle();
21466   Style.PointerAlignment = FormatStyle::PAS_Left;
21467   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
21468   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
21469   verifyFormat("_Atomic(int)* a;", Style);
21470   verifyFormat("_Atomic(int*)* a;", Style);
21471   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
21472 
21473   Style.SpacesInCStyleCastParentheses = true;
21474   Style.SpacesInParentheses = false;
21475   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
21476   Style.SpacesInCStyleCastParentheses = false;
21477   Style.SpacesInParentheses = true;
21478   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
21479   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
21480 }
21481 
21482 TEST_F(FormatTest, AmbersandInLamda) {
21483   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
21484   FormatStyle AlignStyle = getLLVMStyle();
21485   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
21486   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
21487   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
21488   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
21489 }
21490 
21491 TEST_F(FormatTest, SpacesInConditionalStatement) {
21492   FormatStyle Spaces = getLLVMStyle();
21493   Spaces.IfMacros.clear();
21494   Spaces.IfMacros.push_back("MYIF");
21495   Spaces.SpacesInConditionalStatement = true;
21496   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
21497   verifyFormat("if ( !a )\n  return;", Spaces);
21498   verifyFormat("if ( a )\n  return;", Spaces);
21499   verifyFormat("if constexpr ( a )\n  return;", Spaces);
21500   verifyFormat("MYIF ( a )\n  return;", Spaces);
21501   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
21502   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
21503   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
21504   verifyFormat("while ( a )\n  return;", Spaces);
21505   verifyFormat("while ( (a && b) )\n  return;", Spaces);
21506   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
21507   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
21508   // Check that space on the left of "::" is inserted as expected at beginning
21509   // of condition.
21510   verifyFormat("while ( ::func() )\n  return;", Spaces);
21511 
21512   // Check impact of ControlStatementsExceptControlMacros is honored.
21513   Spaces.SpaceBeforeParens =
21514       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
21515   verifyFormat("MYIF( a )\n  return;", Spaces);
21516   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
21517   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
21518 }
21519 
21520 TEST_F(FormatTest, AlternativeOperators) {
21521   // Test case for ensuring alternate operators are not
21522   // combined with their right most neighbour.
21523   verifyFormat("int a and b;");
21524   verifyFormat("int a and_eq b;");
21525   verifyFormat("int a bitand b;");
21526   verifyFormat("int a bitor b;");
21527   verifyFormat("int a compl b;");
21528   verifyFormat("int a not b;");
21529   verifyFormat("int a not_eq b;");
21530   verifyFormat("int a or b;");
21531   verifyFormat("int a xor b;");
21532   verifyFormat("int a xor_eq b;");
21533   verifyFormat("return this not_eq bitand other;");
21534   verifyFormat("bool operator not_eq(const X bitand other)");
21535 
21536   verifyFormat("int a and 5;");
21537   verifyFormat("int a and_eq 5;");
21538   verifyFormat("int a bitand 5;");
21539   verifyFormat("int a bitor 5;");
21540   verifyFormat("int a compl 5;");
21541   verifyFormat("int a not 5;");
21542   verifyFormat("int a not_eq 5;");
21543   verifyFormat("int a or 5;");
21544   verifyFormat("int a xor 5;");
21545   verifyFormat("int a xor_eq 5;");
21546 
21547   verifyFormat("int a compl(5);");
21548   verifyFormat("int a not(5);");
21549 
21550   /* FIXME handle alternate tokens
21551    * https://en.cppreference.com/w/cpp/language/operator_alternative
21552   // alternative tokens
21553   verifyFormat("compl foo();");     //  ~foo();
21554   verifyFormat("foo() <%%>;");      // foo();
21555   verifyFormat("void foo() <%%>;"); // void foo(){}
21556   verifyFormat("int a <:1:>;");     // int a[1];[
21557   verifyFormat("%:define ABC abc"); // #define ABC abc
21558   verifyFormat("%:%:");             // ##
21559   */
21560 }
21561 
21562 TEST_F(FormatTest, STLWhileNotDefineChed) {
21563   verifyFormat("#if defined(while)\n"
21564                "#define while EMIT WARNING C4005\n"
21565                "#endif // while");
21566 }
21567 
21568 TEST_F(FormatTest, OperatorSpacing) {
21569   FormatStyle Style = getLLVMStyle();
21570   Style.PointerAlignment = FormatStyle::PAS_Right;
21571   verifyFormat("Foo::operator*();", Style);
21572   verifyFormat("Foo::operator void *();", Style);
21573   verifyFormat("Foo::operator void **();", Style);
21574   verifyFormat("Foo::operator void *&();", Style);
21575   verifyFormat("Foo::operator void *&&();", Style);
21576   verifyFormat("Foo::operator void const *();", Style);
21577   verifyFormat("Foo::operator void const **();", Style);
21578   verifyFormat("Foo::operator void const *&();", Style);
21579   verifyFormat("Foo::operator void const *&&();", Style);
21580   verifyFormat("Foo::operator()(void *);", Style);
21581   verifyFormat("Foo::operator*(void *);", Style);
21582   verifyFormat("Foo::operator*();", Style);
21583   verifyFormat("Foo::operator**();", Style);
21584   verifyFormat("Foo::operator&();", Style);
21585   verifyFormat("Foo::operator<int> *();", Style);
21586   verifyFormat("Foo::operator<Foo> *();", Style);
21587   verifyFormat("Foo::operator<int> **();", Style);
21588   verifyFormat("Foo::operator<Foo> **();", Style);
21589   verifyFormat("Foo::operator<int> &();", Style);
21590   verifyFormat("Foo::operator<Foo> &();", Style);
21591   verifyFormat("Foo::operator<int> &&();", Style);
21592   verifyFormat("Foo::operator<Foo> &&();", Style);
21593   verifyFormat("Foo::operator<int> *&();", Style);
21594   verifyFormat("Foo::operator<Foo> *&();", Style);
21595   verifyFormat("Foo::operator<int> *&&();", Style);
21596   verifyFormat("Foo::operator<Foo> *&&();", Style);
21597   verifyFormat("operator*(int (*)(), class Foo);", Style);
21598 
21599   verifyFormat("Foo::operator&();", Style);
21600   verifyFormat("Foo::operator void &();", Style);
21601   verifyFormat("Foo::operator void const &();", Style);
21602   verifyFormat("Foo::operator()(void &);", Style);
21603   verifyFormat("Foo::operator&(void &);", Style);
21604   verifyFormat("Foo::operator&();", Style);
21605   verifyFormat("operator&(int (&)(), class Foo);", Style);
21606 
21607   verifyFormat("Foo::operator&&();", Style);
21608   verifyFormat("Foo::operator**();", Style);
21609   verifyFormat("Foo::operator void &&();", Style);
21610   verifyFormat("Foo::operator void const &&();", Style);
21611   verifyFormat("Foo::operator()(void &&);", Style);
21612   verifyFormat("Foo::operator&&(void &&);", Style);
21613   verifyFormat("Foo::operator&&();", Style);
21614   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
21615   verifyFormat("operator const nsTArrayRight<E> &()", Style);
21616   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
21617                Style);
21618   verifyFormat("operator void **()", Style);
21619   verifyFormat("operator const FooRight<Object> &()", Style);
21620   verifyFormat("operator const FooRight<Object> *()", Style);
21621   verifyFormat("operator const FooRight<Object> **()", Style);
21622   verifyFormat("operator const FooRight<Object> *&()", Style);
21623   verifyFormat("operator const FooRight<Object> *&&()", Style);
21624 
21625   Style.PointerAlignment = FormatStyle::PAS_Left;
21626   verifyFormat("Foo::operator*();", Style);
21627   verifyFormat("Foo::operator**();", Style);
21628   verifyFormat("Foo::operator void*();", Style);
21629   verifyFormat("Foo::operator void**();", Style);
21630   verifyFormat("Foo::operator void*&();", Style);
21631   verifyFormat("Foo::operator void*&&();", Style);
21632   verifyFormat("Foo::operator void const*();", Style);
21633   verifyFormat("Foo::operator void const**();", Style);
21634   verifyFormat("Foo::operator void const*&();", Style);
21635   verifyFormat("Foo::operator void const*&&();", Style);
21636   verifyFormat("Foo::operator/*comment*/ void*();", Style);
21637   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
21638   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
21639   verifyFormat("Foo::operator()(void*);", Style);
21640   verifyFormat("Foo::operator*(void*);", Style);
21641   verifyFormat("Foo::operator*();", Style);
21642   verifyFormat("Foo::operator<int>*();", Style);
21643   verifyFormat("Foo::operator<Foo>*();", Style);
21644   verifyFormat("Foo::operator<int>**();", Style);
21645   verifyFormat("Foo::operator<Foo>**();", Style);
21646   verifyFormat("Foo::operator<Foo>*&();", Style);
21647   verifyFormat("Foo::operator<int>&();", Style);
21648   verifyFormat("Foo::operator<Foo>&();", Style);
21649   verifyFormat("Foo::operator<int>&&();", Style);
21650   verifyFormat("Foo::operator<Foo>&&();", Style);
21651   verifyFormat("Foo::operator<int>*&();", Style);
21652   verifyFormat("Foo::operator<Foo>*&();", Style);
21653   verifyFormat("operator*(int (*)(), class Foo);", Style);
21654 
21655   verifyFormat("Foo::operator&();", Style);
21656   verifyFormat("Foo::operator void&();", Style);
21657   verifyFormat("Foo::operator void const&();", Style);
21658   verifyFormat("Foo::operator/*comment*/ void&();", Style);
21659   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
21660   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
21661   verifyFormat("Foo::operator()(void&);", Style);
21662   verifyFormat("Foo::operator&(void&);", Style);
21663   verifyFormat("Foo::operator&();", Style);
21664   verifyFormat("operator&(int (&)(), class Foo);", Style);
21665 
21666   verifyFormat("Foo::operator&&();", Style);
21667   verifyFormat("Foo::operator void&&();", Style);
21668   verifyFormat("Foo::operator void const&&();", Style);
21669   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
21670   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
21671   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
21672   verifyFormat("Foo::operator()(void&&);", Style);
21673   verifyFormat("Foo::operator&&(void&&);", Style);
21674   verifyFormat("Foo::operator&&();", Style);
21675   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
21676   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
21677   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
21678                Style);
21679   verifyFormat("operator void**()", Style);
21680   verifyFormat("operator const FooLeft<Object>&()", Style);
21681   verifyFormat("operator const FooLeft<Object>*()", Style);
21682   verifyFormat("operator const FooLeft<Object>**()", Style);
21683   verifyFormat("operator const FooLeft<Object>*&()", Style);
21684   verifyFormat("operator const FooLeft<Object>*&&()", Style);
21685 
21686   // PR45107
21687   verifyFormat("operator Vector<String>&();", Style);
21688   verifyFormat("operator const Vector<String>&();", Style);
21689   verifyFormat("operator foo::Bar*();", Style);
21690   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
21691   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
21692                Style);
21693 
21694   Style.PointerAlignment = FormatStyle::PAS_Middle;
21695   verifyFormat("Foo::operator*();", Style);
21696   verifyFormat("Foo::operator void *();", Style);
21697   verifyFormat("Foo::operator()(void *);", Style);
21698   verifyFormat("Foo::operator*(void *);", Style);
21699   verifyFormat("Foo::operator*();", Style);
21700   verifyFormat("operator*(int (*)(), class Foo);", Style);
21701 
21702   verifyFormat("Foo::operator&();", Style);
21703   verifyFormat("Foo::operator void &();", Style);
21704   verifyFormat("Foo::operator void const &();", Style);
21705   verifyFormat("Foo::operator()(void &);", Style);
21706   verifyFormat("Foo::operator&(void &);", Style);
21707   verifyFormat("Foo::operator&();", Style);
21708   verifyFormat("operator&(int (&)(), class Foo);", Style);
21709 
21710   verifyFormat("Foo::operator&&();", Style);
21711   verifyFormat("Foo::operator void &&();", Style);
21712   verifyFormat("Foo::operator void const &&();", Style);
21713   verifyFormat("Foo::operator()(void &&);", Style);
21714   verifyFormat("Foo::operator&&(void &&);", Style);
21715   verifyFormat("Foo::operator&&();", Style);
21716   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
21717 }
21718 
21719 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
21720   FormatStyle Style = getLLVMStyle();
21721   // PR46157
21722   verifyFormat("foo(operator+, -42);", Style);
21723   verifyFormat("foo(operator++, -42);", Style);
21724   verifyFormat("foo(operator--, -42);", Style);
21725   verifyFormat("foo(-42, operator--);", Style);
21726   verifyFormat("foo(-42, operator, );", Style);
21727   verifyFormat("foo(operator, , -42);", Style);
21728 }
21729 
21730 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
21731   FormatStyle Style = getLLVMStyle();
21732   Style.WhitespaceSensitiveMacros.push_back("FOO");
21733 
21734   // Don't use the helpers here, since 'mess up' will change the whitespace
21735   // and these are all whitespace sensitive by definition
21736   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
21737             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
21738   EXPECT_EQ(
21739       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
21740       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
21741   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
21742             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
21743   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
21744             "       Still=Intentional);",
21745             format("FOO(String-ized&Messy+But,: :\n"
21746                    "       Still=Intentional);",
21747                    Style));
21748   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
21749   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
21750             "       Still=Intentional);",
21751             format("FOO(String-ized=&Messy+But,: :\n"
21752                    "       Still=Intentional);",
21753                    Style));
21754 
21755   Style.ColumnLimit = 21;
21756   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
21757             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
21758 }
21759 
21760 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
21761   // These tests are not in NamespaceFixer because that doesn't
21762   // test its interaction with line wrapping
21763   FormatStyle Style = getLLVMStyle();
21764   Style.ColumnLimit = 80;
21765   verifyFormat("namespace {\n"
21766                "int i;\n"
21767                "int j;\n"
21768                "} // namespace",
21769                Style);
21770 
21771   verifyFormat("namespace AAA {\n"
21772                "int i;\n"
21773                "int j;\n"
21774                "} // namespace AAA",
21775                Style);
21776 
21777   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
21778             "int i;\n"
21779             "int j;\n"
21780             "} // namespace Averyveryveryverylongnamespace",
21781             format("namespace Averyveryveryverylongnamespace {\n"
21782                    "int i;\n"
21783                    "int j;\n"
21784                    "}",
21785                    Style));
21786 
21787   EXPECT_EQ(
21788       "namespace "
21789       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
21790       "    went::mad::now {\n"
21791       "int i;\n"
21792       "int j;\n"
21793       "} // namespace\n"
21794       "  // "
21795       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
21796       "went::mad::now",
21797       format("namespace "
21798              "would::it::save::you::a::lot::of::time::if_::i::"
21799              "just::gave::up::and_::went::mad::now {\n"
21800              "int i;\n"
21801              "int j;\n"
21802              "}",
21803              Style));
21804 
21805   // This used to duplicate the comment again and again on subsequent runs
21806   EXPECT_EQ(
21807       "namespace "
21808       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
21809       "    went::mad::now {\n"
21810       "int i;\n"
21811       "int j;\n"
21812       "} // namespace\n"
21813       "  // "
21814       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
21815       "went::mad::now",
21816       format("namespace "
21817              "would::it::save::you::a::lot::of::time::if_::i::"
21818              "just::gave::up::and_::went::mad::now {\n"
21819              "int i;\n"
21820              "int j;\n"
21821              "} // namespace\n"
21822              "  // "
21823              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
21824              "and_::went::mad::now",
21825              Style));
21826 }
21827 
21828 TEST_F(FormatTest, LikelyUnlikely) {
21829   FormatStyle Style = getLLVMStyle();
21830 
21831   verifyFormat("if (argc > 5) [[unlikely]] {\n"
21832                "  return 29;\n"
21833                "}",
21834                Style);
21835 
21836   verifyFormat("if (argc > 5) [[likely]] {\n"
21837                "  return 29;\n"
21838                "}",
21839                Style);
21840 
21841   verifyFormat("if (argc > 5) [[unlikely]] {\n"
21842                "  return 29;\n"
21843                "} else [[likely]] {\n"
21844                "  return 42;\n"
21845                "}\n",
21846                Style);
21847 
21848   verifyFormat("if (argc > 5) [[unlikely]] {\n"
21849                "  return 29;\n"
21850                "} else if (argc > 10) [[likely]] {\n"
21851                "  return 99;\n"
21852                "} else {\n"
21853                "  return 42;\n"
21854                "}\n",
21855                Style);
21856 
21857   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
21858                "  return 29;\n"
21859                "}",
21860                Style);
21861 }
21862 
21863 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
21864   verifyFormat("Constructor()\n"
21865                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21866                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
21867                "aaaaaaaaaaaaaaaaaat))");
21868   verifyFormat("Constructor()\n"
21869                "    : aaaaaaaaaaaaa(aaaaaa), "
21870                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
21871 
21872   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
21873   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
21874   verifyFormat("Constructor()\n"
21875                "    : aaaaaa(aaaaaa),\n"
21876                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21877                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
21878                StyleWithWhitespacePenalty);
21879   verifyFormat("Constructor()\n"
21880                "    : aaaaaaaaaaaaa(aaaaaa), "
21881                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
21882                StyleWithWhitespacePenalty);
21883 }
21884 
21885 TEST_F(FormatTest, LLVMDefaultStyle) {
21886   FormatStyle Style = getLLVMStyle();
21887   verifyFormat("extern \"C\" {\n"
21888                "int foo();\n"
21889                "}",
21890                Style);
21891 }
21892 TEST_F(FormatTest, GNUDefaultStyle) {
21893   FormatStyle Style = getGNUStyle();
21894   verifyFormat("extern \"C\"\n"
21895                "{\n"
21896                "  int foo ();\n"
21897                "}",
21898                Style);
21899 }
21900 TEST_F(FormatTest, MozillaDefaultStyle) {
21901   FormatStyle Style = getMozillaStyle();
21902   verifyFormat("extern \"C\"\n"
21903                "{\n"
21904                "  int foo();\n"
21905                "}",
21906                Style);
21907 }
21908 TEST_F(FormatTest, GoogleDefaultStyle) {
21909   FormatStyle Style = getGoogleStyle();
21910   verifyFormat("extern \"C\" {\n"
21911                "int foo();\n"
21912                "}",
21913                Style);
21914 }
21915 TEST_F(FormatTest, ChromiumDefaultStyle) {
21916   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
21917   verifyFormat("extern \"C\" {\n"
21918                "int foo();\n"
21919                "}",
21920                Style);
21921 }
21922 TEST_F(FormatTest, MicrosoftDefaultStyle) {
21923   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
21924   verifyFormat("extern \"C\"\n"
21925                "{\n"
21926                "    int foo();\n"
21927                "}",
21928                Style);
21929 }
21930 TEST_F(FormatTest, WebKitDefaultStyle) {
21931   FormatStyle Style = getWebKitStyle();
21932   verifyFormat("extern \"C\" {\n"
21933                "int foo();\n"
21934                "}",
21935                Style);
21936 }
21937 
21938 TEST_F(FormatTest, ConceptsAndRequires) {
21939   FormatStyle Style = getLLVMStyle();
21940   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
21941 
21942   verifyFormat("template <typename T>\n"
21943                "concept Hashable = requires(T a) {\n"
21944                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
21945                "};",
21946                Style);
21947   verifyFormat("template <typename T>\n"
21948                "concept EqualityComparable = requires(T a, T b) {\n"
21949                "  { a == b } -> bool;\n"
21950                "};",
21951                Style);
21952   verifyFormat("template <typename T>\n"
21953                "concept EqualityComparable = requires(T a, T b) {\n"
21954                "  { a == b } -> bool;\n"
21955                "  { a != b } -> bool;\n"
21956                "};",
21957                Style);
21958   verifyFormat("template <typename T>\n"
21959                "concept EqualityComparable = requires(T a, T b) {\n"
21960                "  { a == b } -> bool;\n"
21961                "  { a != b } -> bool;\n"
21962                "};",
21963                Style);
21964 
21965   verifyFormat("template <typename It>\n"
21966                "requires Iterator<It>\n"
21967                "void sort(It begin, It end) {\n"
21968                "  //....\n"
21969                "}",
21970                Style);
21971 
21972   verifyFormat("template <typename T>\n"
21973                "concept Large = sizeof(T) > 10;",
21974                Style);
21975 
21976   verifyFormat("template <typename T, typename U>\n"
21977                "concept FooableWith = requires(T t, U u) {\n"
21978                "  typename T::foo_type;\n"
21979                "  { t.foo(u) } -> typename T::foo_type;\n"
21980                "  t++;\n"
21981                "};\n"
21982                "void doFoo(FooableWith<int> auto t) {\n"
21983                "  t.foo(3);\n"
21984                "}",
21985                Style);
21986   verifyFormat("template <typename T>\n"
21987                "concept Context = sizeof(T) == 1;",
21988                Style);
21989   verifyFormat("template <typename T>\n"
21990                "concept Context = is_specialization_of_v<context, T>;",
21991                Style);
21992   verifyFormat("template <typename T>\n"
21993                "concept Node = std::is_object_v<T>;",
21994                Style);
21995   verifyFormat("template <typename T>\n"
21996                "concept Tree = true;",
21997                Style);
21998 
21999   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
22000                "  //...\n"
22001                "}",
22002                Style);
22003 
22004   verifyFormat(
22005       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
22006       "  //...\n"
22007       "}",
22008       Style);
22009 
22010   verifyFormat(
22011       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
22012       "  //...\n"
22013       "}",
22014       Style);
22015 
22016   verifyFormat("template <typename T>\n"
22017                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
22018                "Concept2<I> {\n"
22019                "  //...\n"
22020                "}",
22021                Style);
22022 
22023   verifyFormat("template <typename T>\n"
22024                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
22025                "Concept2<I> {\n"
22026                "  //...\n"
22027                "}",
22028                Style);
22029 
22030   verifyFormat(
22031       "template <typename T>\n"
22032       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
22033       "  //...\n"
22034       "}",
22035       Style);
22036 
22037   verifyFormat(
22038       "template <typename T>\n"
22039       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
22040       "  //...\n"
22041       "}",
22042       Style);
22043 
22044   verifyFormat("template <typename It>\n"
22045                "requires Foo<It>() && Bar<It> {\n"
22046                "  //....\n"
22047                "}",
22048                Style);
22049 
22050   verifyFormat("template <typename It>\n"
22051                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
22052                "  //....\n"
22053                "}",
22054                Style);
22055 
22056   verifyFormat("template <typename It>\n"
22057                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
22058                "  //....\n"
22059                "}",
22060                Style);
22061 
22062   verifyFormat(
22063       "template <typename It>\n"
22064       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
22065       "  //....\n"
22066       "}",
22067       Style);
22068 
22069   Style.IndentRequires = true;
22070   verifyFormat("template <typename It>\n"
22071                "  requires Iterator<It>\n"
22072                "void sort(It begin, It end) {\n"
22073                "  //....\n"
22074                "}",
22075                Style);
22076   verifyFormat("template <std::size index_>\n"
22077                "  requires(index_ < sizeof...(Children_))\n"
22078                "Tree auto &child() {\n"
22079                "  // ...\n"
22080                "}",
22081                Style);
22082 
22083   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
22084   verifyFormat("template <typename T>\n"
22085                "concept Hashable = requires (T a) {\n"
22086                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22087                "};",
22088                Style);
22089 
22090   verifyFormat("template <class T = void>\n"
22091                "  requires EqualityComparable<T> || Same<T, void>\n"
22092                "struct equal_to;",
22093                Style);
22094 
22095   verifyFormat("template <class T>\n"
22096                "  requires requires {\n"
22097                "    T{};\n"
22098                "    T (int);\n"
22099                "  }\n",
22100                Style);
22101 
22102   Style.ColumnLimit = 78;
22103   verifyFormat("template <typename T>\n"
22104                "concept Context = Traits<typename T::traits_type> and\n"
22105                "    Interface<typename T::interface_type> and\n"
22106                "    Request<typename T::request_type> and\n"
22107                "    Response<typename T::response_type> and\n"
22108                "    ContextExtension<typename T::extension_type> and\n"
22109                "    ::std::is_copy_constructable<T> and "
22110                "::std::is_move_constructable<T> and\n"
22111                "    requires (T c) {\n"
22112                "  { c.response; } -> Response;\n"
22113                "} and requires (T c) {\n"
22114                "  { c.request; } -> Request;\n"
22115                "}\n",
22116                Style);
22117 
22118   verifyFormat("template <typename T>\n"
22119                "concept Context = Traits<typename T::traits_type> or\n"
22120                "    Interface<typename T::interface_type> or\n"
22121                "    Request<typename T::request_type> or\n"
22122                "    Response<typename T::response_type> or\n"
22123                "    ContextExtension<typename T::extension_type> or\n"
22124                "    ::std::is_copy_constructable<T> or "
22125                "::std::is_move_constructable<T> or\n"
22126                "    requires (T c) {\n"
22127                "  { c.response; } -> Response;\n"
22128                "} or requires (T c) {\n"
22129                "  { c.request; } -> Request;\n"
22130                "}\n",
22131                Style);
22132 
22133   verifyFormat("template <typename T>\n"
22134                "concept Context = Traits<typename T::traits_type> &&\n"
22135                "    Interface<typename T::interface_type> &&\n"
22136                "    Request<typename T::request_type> &&\n"
22137                "    Response<typename T::response_type> &&\n"
22138                "    ContextExtension<typename T::extension_type> &&\n"
22139                "    ::std::is_copy_constructable<T> && "
22140                "::std::is_move_constructable<T> &&\n"
22141                "    requires (T c) {\n"
22142                "  { c.response; } -> Response;\n"
22143                "} && requires (T c) {\n"
22144                "  { c.request; } -> Request;\n"
22145                "}\n",
22146                Style);
22147 
22148   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
22149                "Constraint2<T>;");
22150 
22151   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
22152   Style.BraceWrapping.AfterFunction = true;
22153   Style.BraceWrapping.AfterClass = true;
22154   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
22155   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
22156   verifyFormat("void Foo () requires (std::copyable<T>)\n"
22157                "{\n"
22158                "  return\n"
22159                "}\n",
22160                Style);
22161 
22162   verifyFormat("void Foo () requires std::copyable<T>\n"
22163                "{\n"
22164                "  return\n"
22165                "}\n",
22166                Style);
22167 
22168   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22169                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
22170                "struct constant;",
22171                Style);
22172 
22173   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22174                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
22175                "struct constant;",
22176                Style);
22177 
22178   verifyFormat("template <class T>\n"
22179                "class plane_with_very_very_very_long_name\n"
22180                "{\n"
22181                "  constexpr plane_with_very_very_very_long_name () requires "
22182                "std::copyable<T>\n"
22183                "      : plane_with_very_very_very_long_name (1)\n"
22184                "  {\n"
22185                "  }\n"
22186                "}\n",
22187                Style);
22188 
22189   verifyFormat("template <class T>\n"
22190                "class plane_with_long_name\n"
22191                "{\n"
22192                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
22193                "      : plane_with_long_name (1)\n"
22194                "  {\n"
22195                "  }\n"
22196                "}\n",
22197                Style);
22198 
22199   Style.BreakBeforeConceptDeclarations = false;
22200   verifyFormat("template <typename T> concept Tree = true;", Style);
22201 
22202   Style.IndentRequires = false;
22203   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22204                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
22205                "struct constant;",
22206                Style);
22207 }
22208 
22209 TEST_F(FormatTest, StatementAttributeLikeMacros) {
22210   FormatStyle Style = getLLVMStyle();
22211   StringRef Source = "void Foo::slot() {\n"
22212                      "  unsigned char MyChar = 'x';\n"
22213                      "  emit signal(MyChar);\n"
22214                      "  Q_EMIT signal(MyChar);\n"
22215                      "}";
22216 
22217   EXPECT_EQ(Source, format(Source, Style));
22218 
22219   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
22220   EXPECT_EQ("void Foo::slot() {\n"
22221             "  unsigned char MyChar = 'x';\n"
22222             "  emit          signal(MyChar);\n"
22223             "  Q_EMIT signal(MyChar);\n"
22224             "}",
22225             format(Source, Style));
22226 
22227   Style.StatementAttributeLikeMacros.push_back("emit");
22228   EXPECT_EQ(Source, format(Source, Style));
22229 
22230   Style.StatementAttributeLikeMacros = {};
22231   EXPECT_EQ("void Foo::slot() {\n"
22232             "  unsigned char MyChar = 'x';\n"
22233             "  emit          signal(MyChar);\n"
22234             "  Q_EMIT        signal(MyChar);\n"
22235             "}",
22236             format(Source, Style));
22237 }
22238 
22239 TEST_F(FormatTest, IndentAccessModifiers) {
22240   FormatStyle Style = getLLVMStyle();
22241   Style.IndentAccessModifiers = true;
22242   // Members are *two* levels below the record;
22243   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
22244   verifyFormat("class C {\n"
22245                "    int i;\n"
22246                "};\n",
22247                Style);
22248   verifyFormat("union C {\n"
22249                "    int i;\n"
22250                "    unsigned u;\n"
22251                "};\n",
22252                Style);
22253   // Access modifiers should be indented one level below the record.
22254   verifyFormat("class C {\n"
22255                "  public:\n"
22256                "    int i;\n"
22257                "};\n",
22258                Style);
22259   verifyFormat("struct S {\n"
22260                "  private:\n"
22261                "    class C {\n"
22262                "        int j;\n"
22263                "\n"
22264                "      public:\n"
22265                "        C();\n"
22266                "    };\n"
22267                "\n"
22268                "  public:\n"
22269                "    int i;\n"
22270                "};\n",
22271                Style);
22272   // Enumerations are not records and should be unaffected.
22273   Style.AllowShortEnumsOnASingleLine = false;
22274   verifyFormat("enum class E {\n"
22275                "  A,\n"
22276                "  B\n"
22277                "};\n",
22278                Style);
22279   // Test with a different indentation width;
22280   // also proves that the result is Style.AccessModifierOffset agnostic.
22281   Style.IndentWidth = 3;
22282   verifyFormat("class C {\n"
22283                "   public:\n"
22284                "      int i;\n"
22285                "};\n",
22286                Style);
22287 }
22288 
22289 TEST_F(FormatTest, LimitlessStringsAndComments) {
22290   auto Style = getLLVMStyleWithColumns(0);
22291   constexpr StringRef Code =
22292       "/**\n"
22293       " * This is a multiline comment with quite some long lines, at least for "
22294       "the LLVM Style.\n"
22295       " * We will redo this with strings and line comments. Just to  check if "
22296       "everything is working.\n"
22297       " */\n"
22298       "bool foo() {\n"
22299       "  /* Single line multi line comment. */\n"
22300       "  const std::string String = \"This is a multiline string with quite "
22301       "some long lines, at least for the LLVM Style.\"\n"
22302       "                             \"We already did it with multi line "
22303       "comments, and we will do it with line comments. Just to check if "
22304       "everything is working.\";\n"
22305       "  // This is a line comment (block) with quite some long lines, at "
22306       "least for the LLVM Style.\n"
22307       "  // We already did this with multi line comments and strings. Just to "
22308       "check if everything is working.\n"
22309       "  const std::string SmallString = \"Hello World\";\n"
22310       "  // Small line comment\n"
22311       "  return String.size() > SmallString.size();\n"
22312       "}";
22313   EXPECT_EQ(Code, format(Code, Style));
22314 }
22315 
22316 } // namespace
22317 } // namespace format
22318 } // namespace clang
22319