1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Format/Format.h"
10 
11 #include "../Tooling/ReplacementTest.h"
12 #include "FormatTestUtils.h"
13 
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "gtest/gtest.h"
17 
18 #define DEBUG_TYPE "format-test"
19 
20 using clang::tooling::ReplacementTest;
21 using clang::tooling::toReplacements;
22 using testing::ScopedTrace;
23 
24 namespace clang {
25 namespace format {
26 namespace {
27 
28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
29 
30 class FormatTest : public ::testing::Test {
31 protected:
32   enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
33 
34   std::string format(llvm::StringRef Code,
35                      const FormatStyle &Style = getLLVMStyle(),
36                      StatusCheck CheckComplete = SC_ExpectComplete) {
37     LLVM_DEBUG(llvm::errs() << "---\n");
38     LLVM_DEBUG(llvm::errs() << Code << "\n\n");
39     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
40     FormattingAttemptStatus Status;
41     tooling::Replacements Replaces =
42         reformat(Style, Code, Ranges, "<stdin>", &Status);
43     if (CheckComplete != SC_DoNotCheck) {
44       bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
45       EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
46           << Code << "\n\n";
47     }
48     ReplacementCount = Replaces.size();
49     auto Result = applyAllReplacements(Code, Replaces);
50     EXPECT_TRUE(static_cast<bool>(Result));
51     LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
52     return *Result;
53   }
54 
55   FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) {
56     Style.ColumnLimit = ColumnLimit;
57     return Style;
58   }
59 
60   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
61     return getStyleWithColumns(getLLVMStyle(), ColumnLimit);
62   }
63 
64   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
65     return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
66   }
67 
68   void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
69                      llvm::StringRef Code,
70                      const FormatStyle &Style = getLLVMStyle()) {
71     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
72     EXPECT_EQ(Expected.str(), format(Expected, Style))
73         << "Expected code is not stable";
74     EXPECT_EQ(Expected.str(), format(Code, Style));
75     if (Style.Language == FormatStyle::LK_Cpp) {
76       // Objective-C++ is a superset of C++, so everything checked for C++
77       // needs to be checked for Objective-C++ as well.
78       FormatStyle ObjCStyle = Style;
79       ObjCStyle.Language = FormatStyle::LK_ObjC;
80       EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle));
81     }
82   }
83 
84   void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
85                      const FormatStyle &Style = getLLVMStyle()) {
86     _verifyFormat(File, Line, Code, test::messUp(Code), Style);
87   }
88 
89   void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code,
90                                const FormatStyle &Style = getLLVMStyle()) {
91     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
92     EXPECT_EQ(Code.str(),
93               format(test::messUp(Code), Style, SC_ExpectIncomplete));
94   }
95 
96   void _verifyIndependentOfContext(const char *File, int Line,
97                                    llvm::StringRef Text,
98                                    const FormatStyle &Style = getLLVMStyle()) {
99     _verifyFormat(File, Line, Text, Style);
100     _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
101                   Style);
102   }
103 
104   /// \brief Verify that clang-format does not crash on the given input.
105   void verifyNoCrash(llvm::StringRef Code,
106                      const FormatStyle &Style = getLLVMStyle()) {
107     format(Code, Style, SC_DoNotCheck);
108   }
109 
110   int ReplacementCount;
111 };
112 
113 #define verifyIndependentOfContext(...)                                        \
114   _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
115 #define verifyIncompleteFormat(...)                                            \
116   _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
119 
120 TEST_F(FormatTest, MessUp) {
121   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
122   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
123   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
124   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
125   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
126 }
127 
128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
129   EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
130 }
131 
132 TEST_F(FormatTest, LLVMStyleOverride) {
133   EXPECT_EQ(FormatStyle::LK_Proto,
134             getLLVMStyle(FormatStyle::LK_Proto).Language);
135 }
136 
137 //===----------------------------------------------------------------------===//
138 // Basic function tests.
139 //===----------------------------------------------------------------------===//
140 
141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
142   EXPECT_EQ(";", format(";"));
143 }
144 
145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
146   EXPECT_EQ("int i;", format("  int i;"));
147   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
148   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
149   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
150 }
151 
152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
153   EXPECT_EQ("int i;", format("int\ni;"));
154 }
155 
156 TEST_F(FormatTest, FormatsNestedBlockStatements) {
157   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
158 }
159 
160 TEST_F(FormatTest, FormatsNestedCall) {
161   verifyFormat("Method(f1, f2(f3));");
162   verifyFormat("Method(f1(f2, f3()));");
163   verifyFormat("Method(f1(f2, (f3())));");
164 }
165 
166 TEST_F(FormatTest, NestedNameSpecifiers) {
167   verifyFormat("vector<::Type> v;");
168   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
169   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
170   verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
171   verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
172   verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
173   verifyFormat("bool a = 2 < ::SomeFunction();");
174   verifyFormat("ALWAYS_INLINE ::std::string getName();");
175   verifyFormat("some::string getName();");
176 }
177 
178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
179   EXPECT_EQ("if (a) {\n"
180             "  f();\n"
181             "}",
182             format("if(a){f();}"));
183   EXPECT_EQ(4, ReplacementCount);
184   EXPECT_EQ("if (a) {\n"
185             "  f();\n"
186             "}",
187             format("if (a) {\n"
188                    "  f();\n"
189                    "}"));
190   EXPECT_EQ(0, ReplacementCount);
191   EXPECT_EQ("/*\r\n"
192             "\r\n"
193             "*/\r\n",
194             format("/*\r\n"
195                    "\r\n"
196                    "*/\r\n"));
197   EXPECT_EQ(0, ReplacementCount);
198 }
199 
200 TEST_F(FormatTest, RemovesEmptyLines) {
201   EXPECT_EQ("class C {\n"
202             "  int i;\n"
203             "};",
204             format("class C {\n"
205                    " int i;\n"
206                    "\n"
207                    "};"));
208 
209   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
210   EXPECT_EQ("namespace N {\n"
211             "\n"
212             "int i;\n"
213             "}",
214             format("namespace N {\n"
215                    "\n"
216                    "int    i;\n"
217                    "}",
218                    getGoogleStyle()));
219   EXPECT_EQ("/* something */ namespace N {\n"
220             "\n"
221             "int i;\n"
222             "}",
223             format("/* something */ namespace N {\n"
224                    "\n"
225                    "int    i;\n"
226                    "}",
227                    getGoogleStyle()));
228   EXPECT_EQ("inline namespace N {\n"
229             "\n"
230             "int i;\n"
231             "}",
232             format("inline namespace N {\n"
233                    "\n"
234                    "int    i;\n"
235                    "}",
236                    getGoogleStyle()));
237   EXPECT_EQ("/* something */ inline namespace N {\n"
238             "\n"
239             "int i;\n"
240             "}",
241             format("/* something */ inline namespace N {\n"
242                    "\n"
243                    "int    i;\n"
244                    "}",
245                    getGoogleStyle()));
246   EXPECT_EQ("export namespace N {\n"
247             "\n"
248             "int i;\n"
249             "}",
250             format("export namespace N {\n"
251                    "\n"
252                    "int    i;\n"
253                    "}",
254                    getGoogleStyle()));
255   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
256             "\n"
257             "int i;\n"
258             "}",
259             format("extern /**/ \"C\" /**/ {\n"
260                    "\n"
261                    "int    i;\n"
262                    "}",
263                    getGoogleStyle()));
264 
265   auto CustomStyle = getLLVMStyle();
266   CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom;
267   CustomStyle.BraceWrapping.AfterNamespace = true;
268   CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
269   EXPECT_EQ("namespace N\n"
270             "{\n"
271             "\n"
272             "int i;\n"
273             "}",
274             format("namespace N\n"
275                    "{\n"
276                    "\n"
277                    "\n"
278                    "int    i;\n"
279                    "}",
280                    CustomStyle));
281   EXPECT_EQ("/* something */ namespace N\n"
282             "{\n"
283             "\n"
284             "int i;\n"
285             "}",
286             format("/* something */ namespace N {\n"
287                    "\n"
288                    "\n"
289                    "int    i;\n"
290                    "}",
291                    CustomStyle));
292   EXPECT_EQ("inline namespace N\n"
293             "{\n"
294             "\n"
295             "int i;\n"
296             "}",
297             format("inline namespace N\n"
298                    "{\n"
299                    "\n"
300                    "\n"
301                    "int    i;\n"
302                    "}",
303                    CustomStyle));
304   EXPECT_EQ("/* something */ inline namespace N\n"
305             "{\n"
306             "\n"
307             "int i;\n"
308             "}",
309             format("/* something */ inline namespace N\n"
310                    "{\n"
311                    "\n"
312                    "int    i;\n"
313                    "}",
314                    CustomStyle));
315   EXPECT_EQ("export namespace N\n"
316             "{\n"
317             "\n"
318             "int i;\n"
319             "}",
320             format("export namespace N\n"
321                    "{\n"
322                    "\n"
323                    "int    i;\n"
324                    "}",
325                    CustomStyle));
326   EXPECT_EQ("namespace a\n"
327             "{\n"
328             "namespace b\n"
329             "{\n"
330             "\n"
331             "class AA {};\n"
332             "\n"
333             "} // namespace b\n"
334             "} // namespace a\n",
335             format("namespace a\n"
336                    "{\n"
337                    "namespace b\n"
338                    "{\n"
339                    "\n"
340                    "\n"
341                    "class AA {};\n"
342                    "\n"
343                    "\n"
344                    "}\n"
345                    "}\n",
346                    CustomStyle));
347   EXPECT_EQ("namespace A /* comment */\n"
348             "{\n"
349             "class B {}\n"
350             "} // namespace A",
351             format("namespace A /* comment */ { class B {} }", CustomStyle));
352   EXPECT_EQ("namespace A\n"
353             "{ /* comment */\n"
354             "class B {}\n"
355             "} // namespace A",
356             format("namespace A {/* comment */ class B {} }", CustomStyle));
357   EXPECT_EQ("namespace A\n"
358             "{ /* comment */\n"
359             "\n"
360             "class B {}\n"
361             "\n"
362             ""
363             "} // namespace A",
364             format("namespace A { /* comment */\n"
365                    "\n"
366                    "\n"
367                    "class B {}\n"
368                    "\n"
369                    "\n"
370                    "}",
371                    CustomStyle));
372   EXPECT_EQ("namespace A /* comment */\n"
373             "{\n"
374             "\n"
375             "class B {}\n"
376             "\n"
377             "} // namespace A",
378             format("namespace A/* comment */ {\n"
379                    "\n"
380                    "\n"
381                    "class B {}\n"
382                    "\n"
383                    "\n"
384                    "}",
385                    CustomStyle));
386 
387   // ...but do keep inlining and removing empty lines for non-block extern "C"
388   // functions.
389   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
390   EXPECT_EQ("extern \"C\" int f() {\n"
391             "  int i = 42;\n"
392             "  return i;\n"
393             "}",
394             format("extern \"C\" int f() {\n"
395                    "\n"
396                    "  int i = 42;\n"
397                    "  return i;\n"
398                    "}",
399                    getGoogleStyle()));
400 
401   // Remove empty lines at the beginning and end of blocks.
402   EXPECT_EQ("void f() {\n"
403             "\n"
404             "  if (a) {\n"
405             "\n"
406             "    f();\n"
407             "  }\n"
408             "}",
409             format("void f() {\n"
410                    "\n"
411                    "  if (a) {\n"
412                    "\n"
413                    "    f();\n"
414                    "\n"
415                    "  }\n"
416                    "\n"
417                    "}",
418                    getLLVMStyle()));
419   EXPECT_EQ("void f() {\n"
420             "  if (a) {\n"
421             "    f();\n"
422             "  }\n"
423             "}",
424             format("void f() {\n"
425                    "\n"
426                    "  if (a) {\n"
427                    "\n"
428                    "    f();\n"
429                    "\n"
430                    "  }\n"
431                    "\n"
432                    "}",
433                    getGoogleStyle()));
434 
435   // Don't remove empty lines in more complex control statements.
436   EXPECT_EQ("void f() {\n"
437             "  if (a) {\n"
438             "    f();\n"
439             "\n"
440             "  } else if (b) {\n"
441             "    f();\n"
442             "  }\n"
443             "}",
444             format("void f() {\n"
445                    "  if (a) {\n"
446                    "    f();\n"
447                    "\n"
448                    "  } else if (b) {\n"
449                    "    f();\n"
450                    "\n"
451                    "  }\n"
452                    "\n"
453                    "}"));
454 
455   // Don't remove empty lines before namespace endings.
456   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
457   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
458   EXPECT_EQ("namespace {\n"
459             "int i;\n"
460             "\n"
461             "}",
462             format("namespace {\n"
463                    "int i;\n"
464                    "\n"
465                    "}",
466                    LLVMWithNoNamespaceFix));
467   EXPECT_EQ("namespace {\n"
468             "int i;\n"
469             "}",
470             format("namespace {\n"
471                    "int i;\n"
472                    "}",
473                    LLVMWithNoNamespaceFix));
474   EXPECT_EQ("namespace {\n"
475             "int i;\n"
476             "\n"
477             "};",
478             format("namespace {\n"
479                    "int i;\n"
480                    "\n"
481                    "};",
482                    LLVMWithNoNamespaceFix));
483   EXPECT_EQ("namespace {\n"
484             "int i;\n"
485             "};",
486             format("namespace {\n"
487                    "int i;\n"
488                    "};",
489                    LLVMWithNoNamespaceFix));
490   EXPECT_EQ("namespace {\n"
491             "int i;\n"
492             "\n"
493             "}",
494             format("namespace {\n"
495                    "int i;\n"
496                    "\n"
497                    "}"));
498   EXPECT_EQ("namespace {\n"
499             "int i;\n"
500             "\n"
501             "} // namespace",
502             format("namespace {\n"
503                    "int i;\n"
504                    "\n"
505                    "}  // namespace"));
506 
507   FormatStyle Style = getLLVMStyle();
508   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
509   Style.MaxEmptyLinesToKeep = 2;
510   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
511   Style.BraceWrapping.AfterClass = true;
512   Style.BraceWrapping.AfterFunction = true;
513   Style.KeepEmptyLinesAtTheStartOfBlocks = false;
514 
515   EXPECT_EQ("class Foo\n"
516             "{\n"
517             "  Foo() {}\n"
518             "\n"
519             "  void funk() {}\n"
520             "};",
521             format("class Foo\n"
522                    "{\n"
523                    "  Foo()\n"
524                    "  {\n"
525                    "  }\n"
526                    "\n"
527                    "  void funk() {}\n"
528                    "};",
529                    Style));
530 }
531 
532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
533   verifyFormat("x = (a) and (b);");
534   verifyFormat("x = (a) or (b);");
535   verifyFormat("x = (a) bitand (b);");
536   verifyFormat("x = (a) bitor (b);");
537   verifyFormat("x = (a) not_eq (b);");
538   verifyFormat("x = (a) and_eq (b);");
539   verifyFormat("x = (a) or_eq (b);");
540   verifyFormat("x = (a) xor (b);");
541 }
542 
543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
544   verifyFormat("x = compl(a);");
545   verifyFormat("x = not(a);");
546   verifyFormat("x = bitand(a);");
547   // Unary operator must not be merged with the next identifier
548   verifyFormat("x = compl a;");
549   verifyFormat("x = not a;");
550   verifyFormat("x = bitand a;");
551 }
552 
553 //===----------------------------------------------------------------------===//
554 // Tests for control statements.
555 //===----------------------------------------------------------------------===//
556 
557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
558   verifyFormat("if (true)\n  f();\ng();");
559   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
560   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
561   verifyFormat("if constexpr (true)\n"
562                "  f();\ng();");
563   verifyFormat("if CONSTEXPR (true)\n"
564                "  f();\ng();");
565   verifyFormat("if constexpr (a)\n"
566                "  if constexpr (b)\n"
567                "    if constexpr (c)\n"
568                "      g();\n"
569                "h();");
570   verifyFormat("if CONSTEXPR (a)\n"
571                "  if CONSTEXPR (b)\n"
572                "    if CONSTEXPR (c)\n"
573                "      g();\n"
574                "h();");
575   verifyFormat("if constexpr (a)\n"
576                "  if constexpr (b) {\n"
577                "    f();\n"
578                "  }\n"
579                "g();");
580   verifyFormat("if CONSTEXPR (a)\n"
581                "  if CONSTEXPR (b) {\n"
582                "    f();\n"
583                "  }\n"
584                "g();");
585 
586   verifyFormat("if consteval {\n}");
587   verifyFormat("if !consteval {\n}");
588   verifyFormat("if not consteval {\n}");
589   verifyFormat("if consteval {\n} else {\n}");
590   verifyFormat("if !consteval {\n} else {\n}");
591   verifyFormat("if consteval {\n"
592                "  f();\n"
593                "}");
594   verifyFormat("if !consteval {\n"
595                "  f();\n"
596                "}");
597   verifyFormat("if consteval {\n"
598                "  f();\n"
599                "} else {\n"
600                "  g();\n"
601                "}");
602   verifyFormat("if CONSTEVAL {\n"
603                "  f();\n"
604                "}");
605   verifyFormat("if !CONSTEVAL {\n"
606                "  f();\n"
607                "}");
608 
609   verifyFormat("if (a)\n"
610                "  g();");
611   verifyFormat("if (a) {\n"
612                "  g()\n"
613                "};");
614   verifyFormat("if (a)\n"
615                "  g();\n"
616                "else\n"
617                "  g();");
618   verifyFormat("if (a) {\n"
619                "  g();\n"
620                "} else\n"
621                "  g();");
622   verifyFormat("if (a)\n"
623                "  g();\n"
624                "else {\n"
625                "  g();\n"
626                "}");
627   verifyFormat("if (a) {\n"
628                "  g();\n"
629                "} else {\n"
630                "  g();\n"
631                "}");
632   verifyFormat("if (a)\n"
633                "  g();\n"
634                "else if (b)\n"
635                "  g();\n"
636                "else\n"
637                "  g();");
638   verifyFormat("if (a) {\n"
639                "  g();\n"
640                "} else if (b)\n"
641                "  g();\n"
642                "else\n"
643                "  g();");
644   verifyFormat("if (a)\n"
645                "  g();\n"
646                "else if (b) {\n"
647                "  g();\n"
648                "} else\n"
649                "  g();");
650   verifyFormat("if (a)\n"
651                "  g();\n"
652                "else if (b)\n"
653                "  g();\n"
654                "else {\n"
655                "  g();\n"
656                "}");
657   verifyFormat("if (a)\n"
658                "  g();\n"
659                "else if (b) {\n"
660                "  g();\n"
661                "} else {\n"
662                "  g();\n"
663                "}");
664   verifyFormat("if (a) {\n"
665                "  g();\n"
666                "} else if (b) {\n"
667                "  g();\n"
668                "} else {\n"
669                "  g();\n"
670                "}");
671 
672   FormatStyle AllowsMergedIf = getLLVMStyle();
673   AllowsMergedIf.IfMacros.push_back("MYIF");
674   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
675   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
676       FormatStyle::SIS_WithoutElse;
677   verifyFormat("if (a)\n"
678                "  // comment\n"
679                "  f();",
680                AllowsMergedIf);
681   verifyFormat("{\n"
682                "  if (a)\n"
683                "  label:\n"
684                "    f();\n"
685                "}",
686                AllowsMergedIf);
687   verifyFormat("#define A \\\n"
688                "  if (a)  \\\n"
689                "  label:  \\\n"
690                "    f()",
691                AllowsMergedIf);
692   verifyFormat("if (a)\n"
693                "  ;",
694                AllowsMergedIf);
695   verifyFormat("if (a)\n"
696                "  if (b) return;",
697                AllowsMergedIf);
698 
699   verifyFormat("if (a) // Can't merge this\n"
700                "  f();\n",
701                AllowsMergedIf);
702   verifyFormat("if (a) /* still don't merge */\n"
703                "  f();",
704                AllowsMergedIf);
705   verifyFormat("if (a) { // Never merge this\n"
706                "  f();\n"
707                "}",
708                AllowsMergedIf);
709   verifyFormat("if (a) { /* Never merge this */\n"
710                "  f();\n"
711                "}",
712                AllowsMergedIf);
713   verifyFormat("MYIF (a)\n"
714                "  // comment\n"
715                "  f();",
716                AllowsMergedIf);
717   verifyFormat("{\n"
718                "  MYIF (a)\n"
719                "  label:\n"
720                "    f();\n"
721                "}",
722                AllowsMergedIf);
723   verifyFormat("#define A  \\\n"
724                "  MYIF (a) \\\n"
725                "  label:   \\\n"
726                "    f()",
727                AllowsMergedIf);
728   verifyFormat("MYIF (a)\n"
729                "  ;",
730                AllowsMergedIf);
731   verifyFormat("MYIF (a)\n"
732                "  MYIF (b) return;",
733                AllowsMergedIf);
734 
735   verifyFormat("MYIF (a) // Can't merge this\n"
736                "  f();\n",
737                AllowsMergedIf);
738   verifyFormat("MYIF (a) /* still don't merge */\n"
739                "  f();",
740                AllowsMergedIf);
741   verifyFormat("MYIF (a) { // Never merge this\n"
742                "  f();\n"
743                "}",
744                AllowsMergedIf);
745   verifyFormat("MYIF (a) { /* Never merge this */\n"
746                "  f();\n"
747                "}",
748                AllowsMergedIf);
749 
750   AllowsMergedIf.ColumnLimit = 14;
751   // Where line-lengths matter, a 2-letter synonym that maintains line length.
752   // Not IF to avoid any confusion that IF is somehow special.
753   AllowsMergedIf.IfMacros.push_back("FI");
754   verifyFormat("if (a) return;", AllowsMergedIf);
755   verifyFormat("if (aaaaaaaaa)\n"
756                "  return;",
757                AllowsMergedIf);
758   verifyFormat("FI (a) return;", AllowsMergedIf);
759   verifyFormat("FI (aaaaaaaaa)\n"
760                "  return;",
761                AllowsMergedIf);
762 
763   AllowsMergedIf.ColumnLimit = 13;
764   verifyFormat("if (a)\n  return;", AllowsMergedIf);
765   verifyFormat("FI (a)\n  return;", AllowsMergedIf);
766 
767   FormatStyle AllowsMergedIfElse = getLLVMStyle();
768   AllowsMergedIfElse.IfMacros.push_back("MYIF");
769   AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
770       FormatStyle::SIS_AllIfsAndElse;
771   verifyFormat("if (a)\n"
772                "  // comment\n"
773                "  f();\n"
774                "else\n"
775                "  // comment\n"
776                "  f();",
777                AllowsMergedIfElse);
778   verifyFormat("{\n"
779                "  if (a)\n"
780                "  label:\n"
781                "    f();\n"
782                "  else\n"
783                "  label:\n"
784                "    f();\n"
785                "}",
786                AllowsMergedIfElse);
787   verifyFormat("if (a)\n"
788                "  ;\n"
789                "else\n"
790                "  ;",
791                AllowsMergedIfElse);
792   verifyFormat("if (a) {\n"
793                "} else {\n"
794                "}",
795                AllowsMergedIfElse);
796   verifyFormat("if (a) return;\n"
797                "else if (b) return;\n"
798                "else return;",
799                AllowsMergedIfElse);
800   verifyFormat("if (a) {\n"
801                "} else return;",
802                AllowsMergedIfElse);
803   verifyFormat("if (a) {\n"
804                "} else if (b) return;\n"
805                "else return;",
806                AllowsMergedIfElse);
807   verifyFormat("if (a) return;\n"
808                "else if (b) {\n"
809                "} else return;",
810                AllowsMergedIfElse);
811   verifyFormat("if (a)\n"
812                "  if (b) return;\n"
813                "  else return;",
814                AllowsMergedIfElse);
815   verifyFormat("if constexpr (a)\n"
816                "  if constexpr (b) return;\n"
817                "  else if constexpr (c) return;\n"
818                "  else return;",
819                AllowsMergedIfElse);
820   verifyFormat("MYIF (a)\n"
821                "  // comment\n"
822                "  f();\n"
823                "else\n"
824                "  // comment\n"
825                "  f();",
826                AllowsMergedIfElse);
827   verifyFormat("{\n"
828                "  MYIF (a)\n"
829                "  label:\n"
830                "    f();\n"
831                "  else\n"
832                "  label:\n"
833                "    f();\n"
834                "}",
835                AllowsMergedIfElse);
836   verifyFormat("MYIF (a)\n"
837                "  ;\n"
838                "else\n"
839                "  ;",
840                AllowsMergedIfElse);
841   verifyFormat("MYIF (a) {\n"
842                "} else {\n"
843                "}",
844                AllowsMergedIfElse);
845   verifyFormat("MYIF (a) return;\n"
846                "else MYIF (b) return;\n"
847                "else return;",
848                AllowsMergedIfElse);
849   verifyFormat("MYIF (a) {\n"
850                "} else return;",
851                AllowsMergedIfElse);
852   verifyFormat("MYIF (a) {\n"
853                "} else MYIF (b) return;\n"
854                "else return;",
855                AllowsMergedIfElse);
856   verifyFormat("MYIF (a) return;\n"
857                "else MYIF (b) {\n"
858                "} else return;",
859                AllowsMergedIfElse);
860   verifyFormat("MYIF (a)\n"
861                "  MYIF (b) return;\n"
862                "  else return;",
863                AllowsMergedIfElse);
864   verifyFormat("MYIF constexpr (a)\n"
865                "  MYIF constexpr (b) return;\n"
866                "  else MYIF constexpr (c) return;\n"
867                "  else return;",
868                AllowsMergedIfElse);
869 }
870 
871 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
872   FormatStyle AllowsMergedIf = getLLVMStyle();
873   AllowsMergedIf.IfMacros.push_back("MYIF");
874   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
875   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
876       FormatStyle::SIS_WithoutElse;
877   verifyFormat("if (a)\n"
878                "  f();\n"
879                "else {\n"
880                "  g();\n"
881                "}",
882                AllowsMergedIf);
883   verifyFormat("if (a)\n"
884                "  f();\n"
885                "else\n"
886                "  g();\n",
887                AllowsMergedIf);
888 
889   verifyFormat("if (a) g();", AllowsMergedIf);
890   verifyFormat("if (a) {\n"
891                "  g()\n"
892                "};",
893                AllowsMergedIf);
894   verifyFormat("if (a)\n"
895                "  g();\n"
896                "else\n"
897                "  g();",
898                AllowsMergedIf);
899   verifyFormat("if (a) {\n"
900                "  g();\n"
901                "} else\n"
902                "  g();",
903                AllowsMergedIf);
904   verifyFormat("if (a)\n"
905                "  g();\n"
906                "else {\n"
907                "  g();\n"
908                "}",
909                AllowsMergedIf);
910   verifyFormat("if (a) {\n"
911                "  g();\n"
912                "} else {\n"
913                "  g();\n"
914                "}",
915                AllowsMergedIf);
916   verifyFormat("if (a)\n"
917                "  g();\n"
918                "else if (b)\n"
919                "  g();\n"
920                "else\n"
921                "  g();",
922                AllowsMergedIf);
923   verifyFormat("if (a) {\n"
924                "  g();\n"
925                "} else if (b)\n"
926                "  g();\n"
927                "else\n"
928                "  g();",
929                AllowsMergedIf);
930   verifyFormat("if (a)\n"
931                "  g();\n"
932                "else if (b) {\n"
933                "  g();\n"
934                "} else\n"
935                "  g();",
936                AllowsMergedIf);
937   verifyFormat("if (a)\n"
938                "  g();\n"
939                "else if (b)\n"
940                "  g();\n"
941                "else {\n"
942                "  g();\n"
943                "}",
944                AllowsMergedIf);
945   verifyFormat("if (a)\n"
946                "  g();\n"
947                "else if (b) {\n"
948                "  g();\n"
949                "} else {\n"
950                "  g();\n"
951                "}",
952                AllowsMergedIf);
953   verifyFormat("if (a) {\n"
954                "  g();\n"
955                "} else if (b) {\n"
956                "  g();\n"
957                "} else {\n"
958                "  g();\n"
959                "}",
960                AllowsMergedIf);
961   verifyFormat("MYIF (a)\n"
962                "  f();\n"
963                "else {\n"
964                "  g();\n"
965                "}",
966                AllowsMergedIf);
967   verifyFormat("MYIF (a)\n"
968                "  f();\n"
969                "else\n"
970                "  g();\n",
971                AllowsMergedIf);
972 
973   verifyFormat("MYIF (a) g();", AllowsMergedIf);
974   verifyFormat("MYIF (a) {\n"
975                "  g()\n"
976                "};",
977                AllowsMergedIf);
978   verifyFormat("MYIF (a)\n"
979                "  g();\n"
980                "else\n"
981                "  g();",
982                AllowsMergedIf);
983   verifyFormat("MYIF (a) {\n"
984                "  g();\n"
985                "} else\n"
986                "  g();",
987                AllowsMergedIf);
988   verifyFormat("MYIF (a)\n"
989                "  g();\n"
990                "else {\n"
991                "  g();\n"
992                "}",
993                AllowsMergedIf);
994   verifyFormat("MYIF (a) {\n"
995                "  g();\n"
996                "} else {\n"
997                "  g();\n"
998                "}",
999                AllowsMergedIf);
1000   verifyFormat("MYIF (a)\n"
1001                "  g();\n"
1002                "else MYIF (b)\n"
1003                "  g();\n"
1004                "else\n"
1005                "  g();",
1006                AllowsMergedIf);
1007   verifyFormat("MYIF (a)\n"
1008                "  g();\n"
1009                "else if (b)\n"
1010                "  g();\n"
1011                "else\n"
1012                "  g();",
1013                AllowsMergedIf);
1014   verifyFormat("MYIF (a) {\n"
1015                "  g();\n"
1016                "} else MYIF (b)\n"
1017                "  g();\n"
1018                "else\n"
1019                "  g();",
1020                AllowsMergedIf);
1021   verifyFormat("MYIF (a) {\n"
1022                "  g();\n"
1023                "} else if (b)\n"
1024                "  g();\n"
1025                "else\n"
1026                "  g();",
1027                AllowsMergedIf);
1028   verifyFormat("MYIF (a)\n"
1029                "  g();\n"
1030                "else MYIF (b) {\n"
1031                "  g();\n"
1032                "} else\n"
1033                "  g();",
1034                AllowsMergedIf);
1035   verifyFormat("MYIF (a)\n"
1036                "  g();\n"
1037                "else if (b) {\n"
1038                "  g();\n"
1039                "} else\n"
1040                "  g();",
1041                AllowsMergedIf);
1042   verifyFormat("MYIF (a)\n"
1043                "  g();\n"
1044                "else MYIF (b)\n"
1045                "  g();\n"
1046                "else {\n"
1047                "  g();\n"
1048                "}",
1049                AllowsMergedIf);
1050   verifyFormat("MYIF (a)\n"
1051                "  g();\n"
1052                "else if (b)\n"
1053                "  g();\n"
1054                "else {\n"
1055                "  g();\n"
1056                "}",
1057                AllowsMergedIf);
1058   verifyFormat("MYIF (a)\n"
1059                "  g();\n"
1060                "else MYIF (b) {\n"
1061                "  g();\n"
1062                "} else {\n"
1063                "  g();\n"
1064                "}",
1065                AllowsMergedIf);
1066   verifyFormat("MYIF (a)\n"
1067                "  g();\n"
1068                "else if (b) {\n"
1069                "  g();\n"
1070                "} else {\n"
1071                "  g();\n"
1072                "}",
1073                AllowsMergedIf);
1074   verifyFormat("MYIF (a) {\n"
1075                "  g();\n"
1076                "} else MYIF (b) {\n"
1077                "  g();\n"
1078                "} else {\n"
1079                "  g();\n"
1080                "}",
1081                AllowsMergedIf);
1082   verifyFormat("MYIF (a) {\n"
1083                "  g();\n"
1084                "} else if (b) {\n"
1085                "  g();\n"
1086                "} else {\n"
1087                "  g();\n"
1088                "}",
1089                AllowsMergedIf);
1090 
1091   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1092       FormatStyle::SIS_OnlyFirstIf;
1093 
1094   verifyFormat("if (a) f();\n"
1095                "else {\n"
1096                "  g();\n"
1097                "}",
1098                AllowsMergedIf);
1099   verifyFormat("if (a) f();\n"
1100                "else {\n"
1101                "  if (a) f();\n"
1102                "  else {\n"
1103                "    g();\n"
1104                "  }\n"
1105                "  g();\n"
1106                "}",
1107                AllowsMergedIf);
1108 
1109   verifyFormat("if (a) g();", AllowsMergedIf);
1110   verifyFormat("if (a) {\n"
1111                "  g()\n"
1112                "};",
1113                AllowsMergedIf);
1114   verifyFormat("if (a) g();\n"
1115                "else\n"
1116                "  g();",
1117                AllowsMergedIf);
1118   verifyFormat("if (a) {\n"
1119                "  g();\n"
1120                "} else\n"
1121                "  g();",
1122                AllowsMergedIf);
1123   verifyFormat("if (a) g();\n"
1124                "else {\n"
1125                "  g();\n"
1126                "}",
1127                AllowsMergedIf);
1128   verifyFormat("if (a) {\n"
1129                "  g();\n"
1130                "} else {\n"
1131                "  g();\n"
1132                "}",
1133                AllowsMergedIf);
1134   verifyFormat("if (a) g();\n"
1135                "else if (b)\n"
1136                "  g();\n"
1137                "else\n"
1138                "  g();",
1139                AllowsMergedIf);
1140   verifyFormat("if (a) {\n"
1141                "  g();\n"
1142                "} else if (b)\n"
1143                "  g();\n"
1144                "else\n"
1145                "  g();",
1146                AllowsMergedIf);
1147   verifyFormat("if (a) g();\n"
1148                "else if (b) {\n"
1149                "  g();\n"
1150                "} else\n"
1151                "  g();",
1152                AllowsMergedIf);
1153   verifyFormat("if (a) g();\n"
1154                "else if (b)\n"
1155                "  g();\n"
1156                "else {\n"
1157                "  g();\n"
1158                "}",
1159                AllowsMergedIf);
1160   verifyFormat("if (a) g();\n"
1161                "else if (b) {\n"
1162                "  g();\n"
1163                "} else {\n"
1164                "  g();\n"
1165                "}",
1166                AllowsMergedIf);
1167   verifyFormat("if (a) {\n"
1168                "  g();\n"
1169                "} else if (b) {\n"
1170                "  g();\n"
1171                "} else {\n"
1172                "  g();\n"
1173                "}",
1174                AllowsMergedIf);
1175   verifyFormat("MYIF (a) f();\n"
1176                "else {\n"
1177                "  g();\n"
1178                "}",
1179                AllowsMergedIf);
1180   verifyFormat("MYIF (a) f();\n"
1181                "else {\n"
1182                "  if (a) f();\n"
1183                "  else {\n"
1184                "    g();\n"
1185                "  }\n"
1186                "  g();\n"
1187                "}",
1188                AllowsMergedIf);
1189 
1190   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1191   verifyFormat("MYIF (a) {\n"
1192                "  g()\n"
1193                "};",
1194                AllowsMergedIf);
1195   verifyFormat("MYIF (a) g();\n"
1196                "else\n"
1197                "  g();",
1198                AllowsMergedIf);
1199   verifyFormat("MYIF (a) {\n"
1200                "  g();\n"
1201                "} else\n"
1202                "  g();",
1203                AllowsMergedIf);
1204   verifyFormat("MYIF (a) g();\n"
1205                "else {\n"
1206                "  g();\n"
1207                "}",
1208                AllowsMergedIf);
1209   verifyFormat("MYIF (a) {\n"
1210                "  g();\n"
1211                "} else {\n"
1212                "  g();\n"
1213                "}",
1214                AllowsMergedIf);
1215   verifyFormat("MYIF (a) g();\n"
1216                "else MYIF (b)\n"
1217                "  g();\n"
1218                "else\n"
1219                "  g();",
1220                AllowsMergedIf);
1221   verifyFormat("MYIF (a) g();\n"
1222                "else if (b)\n"
1223                "  g();\n"
1224                "else\n"
1225                "  g();",
1226                AllowsMergedIf);
1227   verifyFormat("MYIF (a) {\n"
1228                "  g();\n"
1229                "} else MYIF (b)\n"
1230                "  g();\n"
1231                "else\n"
1232                "  g();",
1233                AllowsMergedIf);
1234   verifyFormat("MYIF (a) {\n"
1235                "  g();\n"
1236                "} else if (b)\n"
1237                "  g();\n"
1238                "else\n"
1239                "  g();",
1240                AllowsMergedIf);
1241   verifyFormat("MYIF (a) g();\n"
1242                "else MYIF (b) {\n"
1243                "  g();\n"
1244                "} else\n"
1245                "  g();",
1246                AllowsMergedIf);
1247   verifyFormat("MYIF (a) g();\n"
1248                "else if (b) {\n"
1249                "  g();\n"
1250                "} else\n"
1251                "  g();",
1252                AllowsMergedIf);
1253   verifyFormat("MYIF (a) g();\n"
1254                "else MYIF (b)\n"
1255                "  g();\n"
1256                "else {\n"
1257                "  g();\n"
1258                "}",
1259                AllowsMergedIf);
1260   verifyFormat("MYIF (a) g();\n"
1261                "else if (b)\n"
1262                "  g();\n"
1263                "else {\n"
1264                "  g();\n"
1265                "}",
1266                AllowsMergedIf);
1267   verifyFormat("MYIF (a) g();\n"
1268                "else MYIF (b) {\n"
1269                "  g();\n"
1270                "} else {\n"
1271                "  g();\n"
1272                "}",
1273                AllowsMergedIf);
1274   verifyFormat("MYIF (a) g();\n"
1275                "else if (b) {\n"
1276                "  g();\n"
1277                "} else {\n"
1278                "  g();\n"
1279                "}",
1280                AllowsMergedIf);
1281   verifyFormat("MYIF (a) {\n"
1282                "  g();\n"
1283                "} else MYIF (b) {\n"
1284                "  g();\n"
1285                "} else {\n"
1286                "  g();\n"
1287                "}",
1288                AllowsMergedIf);
1289   verifyFormat("MYIF (a) {\n"
1290                "  g();\n"
1291                "} else if (b) {\n"
1292                "  g();\n"
1293                "} else {\n"
1294                "  g();\n"
1295                "}",
1296                AllowsMergedIf);
1297 
1298   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1299       FormatStyle::SIS_AllIfsAndElse;
1300 
1301   verifyFormat("if (a) f();\n"
1302                "else {\n"
1303                "  g();\n"
1304                "}",
1305                AllowsMergedIf);
1306   verifyFormat("if (a) f();\n"
1307                "else {\n"
1308                "  if (a) f();\n"
1309                "  else {\n"
1310                "    g();\n"
1311                "  }\n"
1312                "  g();\n"
1313                "}",
1314                AllowsMergedIf);
1315 
1316   verifyFormat("if (a) g();", AllowsMergedIf);
1317   verifyFormat("if (a) {\n"
1318                "  g()\n"
1319                "};",
1320                AllowsMergedIf);
1321   verifyFormat("if (a) g();\n"
1322                "else g();",
1323                AllowsMergedIf);
1324   verifyFormat("if (a) {\n"
1325                "  g();\n"
1326                "} else g();",
1327                AllowsMergedIf);
1328   verifyFormat("if (a) g();\n"
1329                "else {\n"
1330                "  g();\n"
1331                "}",
1332                AllowsMergedIf);
1333   verifyFormat("if (a) {\n"
1334                "  g();\n"
1335                "} else {\n"
1336                "  g();\n"
1337                "}",
1338                AllowsMergedIf);
1339   verifyFormat("if (a) g();\n"
1340                "else if (b) g();\n"
1341                "else g();",
1342                AllowsMergedIf);
1343   verifyFormat("if (a) {\n"
1344                "  g();\n"
1345                "} else if (b) g();\n"
1346                "else g();",
1347                AllowsMergedIf);
1348   verifyFormat("if (a) g();\n"
1349                "else if (b) {\n"
1350                "  g();\n"
1351                "} else g();",
1352                AllowsMergedIf);
1353   verifyFormat("if (a) g();\n"
1354                "else if (b) g();\n"
1355                "else {\n"
1356                "  g();\n"
1357                "}",
1358                AllowsMergedIf);
1359   verifyFormat("if (a) g();\n"
1360                "else if (b) {\n"
1361                "  g();\n"
1362                "} else {\n"
1363                "  g();\n"
1364                "}",
1365                AllowsMergedIf);
1366   verifyFormat("if (a) {\n"
1367                "  g();\n"
1368                "} else if (b) {\n"
1369                "  g();\n"
1370                "} else {\n"
1371                "  g();\n"
1372                "}",
1373                AllowsMergedIf);
1374   verifyFormat("MYIF (a) f();\n"
1375                "else {\n"
1376                "  g();\n"
1377                "}",
1378                AllowsMergedIf);
1379   verifyFormat("MYIF (a) f();\n"
1380                "else {\n"
1381                "  if (a) f();\n"
1382                "  else {\n"
1383                "    g();\n"
1384                "  }\n"
1385                "  g();\n"
1386                "}",
1387                AllowsMergedIf);
1388 
1389   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1390   verifyFormat("MYIF (a) {\n"
1391                "  g()\n"
1392                "};",
1393                AllowsMergedIf);
1394   verifyFormat("MYIF (a) g();\n"
1395                "else g();",
1396                AllowsMergedIf);
1397   verifyFormat("MYIF (a) {\n"
1398                "  g();\n"
1399                "} else g();",
1400                AllowsMergedIf);
1401   verifyFormat("MYIF (a) g();\n"
1402                "else {\n"
1403                "  g();\n"
1404                "}",
1405                AllowsMergedIf);
1406   verifyFormat("MYIF (a) {\n"
1407                "  g();\n"
1408                "} else {\n"
1409                "  g();\n"
1410                "}",
1411                AllowsMergedIf);
1412   verifyFormat("MYIF (a) g();\n"
1413                "else MYIF (b) g();\n"
1414                "else g();",
1415                AllowsMergedIf);
1416   verifyFormat("MYIF (a) g();\n"
1417                "else if (b) g();\n"
1418                "else g();",
1419                AllowsMergedIf);
1420   verifyFormat("MYIF (a) {\n"
1421                "  g();\n"
1422                "} else MYIF (b) g();\n"
1423                "else g();",
1424                AllowsMergedIf);
1425   verifyFormat("MYIF (a) {\n"
1426                "  g();\n"
1427                "} else if (b) g();\n"
1428                "else g();",
1429                AllowsMergedIf);
1430   verifyFormat("MYIF (a) g();\n"
1431                "else MYIF (b) {\n"
1432                "  g();\n"
1433                "} else g();",
1434                AllowsMergedIf);
1435   verifyFormat("MYIF (a) g();\n"
1436                "else if (b) {\n"
1437                "  g();\n"
1438                "} else g();",
1439                AllowsMergedIf);
1440   verifyFormat("MYIF (a) g();\n"
1441                "else MYIF (b) g();\n"
1442                "else {\n"
1443                "  g();\n"
1444                "}",
1445                AllowsMergedIf);
1446   verifyFormat("MYIF (a) g();\n"
1447                "else if (b) g();\n"
1448                "else {\n"
1449                "  g();\n"
1450                "}",
1451                AllowsMergedIf);
1452   verifyFormat("MYIF (a) g();\n"
1453                "else MYIF (b) {\n"
1454                "  g();\n"
1455                "} else {\n"
1456                "  g();\n"
1457                "}",
1458                AllowsMergedIf);
1459   verifyFormat("MYIF (a) g();\n"
1460                "else if (b) {\n"
1461                "  g();\n"
1462                "} else {\n"
1463                "  g();\n"
1464                "}",
1465                AllowsMergedIf);
1466   verifyFormat("MYIF (a) {\n"
1467                "  g();\n"
1468                "} else MYIF (b) {\n"
1469                "  g();\n"
1470                "} else {\n"
1471                "  g();\n"
1472                "}",
1473                AllowsMergedIf);
1474   verifyFormat("MYIF (a) {\n"
1475                "  g();\n"
1476                "} else if (b) {\n"
1477                "  g();\n"
1478                "} else {\n"
1479                "  g();\n"
1480                "}",
1481                AllowsMergedIf);
1482 }
1483 
1484 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
1485   FormatStyle AllowsMergedLoops = getLLVMStyle();
1486   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
1487   verifyFormat("while (true) continue;", AllowsMergedLoops);
1488   verifyFormat("for (;;) continue;", AllowsMergedLoops);
1489   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
1490   verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
1491   verifyFormat("while (true)\n"
1492                "  ;",
1493                AllowsMergedLoops);
1494   verifyFormat("for (;;)\n"
1495                "  ;",
1496                AllowsMergedLoops);
1497   verifyFormat("for (;;)\n"
1498                "  for (;;) continue;",
1499                AllowsMergedLoops);
1500   verifyFormat("for (;;)\n"
1501                "  while (true) continue;",
1502                AllowsMergedLoops);
1503   verifyFormat("while (true)\n"
1504                "  for (;;) continue;",
1505                AllowsMergedLoops);
1506   verifyFormat("BOOST_FOREACH (int &v, vec)\n"
1507                "  for (;;) continue;",
1508                AllowsMergedLoops);
1509   verifyFormat("for (;;)\n"
1510                "  BOOST_FOREACH (int &v, vec) continue;",
1511                AllowsMergedLoops);
1512   verifyFormat("for (;;) // Can't merge this\n"
1513                "  continue;",
1514                AllowsMergedLoops);
1515   verifyFormat("for (;;) /* still don't merge */\n"
1516                "  continue;",
1517                AllowsMergedLoops);
1518   verifyFormat("do a++;\n"
1519                "while (true);",
1520                AllowsMergedLoops);
1521   verifyFormat("do /* Don't merge */\n"
1522                "  a++;\n"
1523                "while (true);",
1524                AllowsMergedLoops);
1525   verifyFormat("do // Don't merge\n"
1526                "  a++;\n"
1527                "while (true);",
1528                AllowsMergedLoops);
1529   verifyFormat("do\n"
1530                "  // Don't merge\n"
1531                "  a++;\n"
1532                "while (true);",
1533                AllowsMergedLoops);
1534   // Without braces labels are interpreted differently.
1535   verifyFormat("{\n"
1536                "  do\n"
1537                "  label:\n"
1538                "    a++;\n"
1539                "  while (true);\n"
1540                "}",
1541                AllowsMergedLoops);
1542 }
1543 
1544 TEST_F(FormatTest, FormatShortBracedStatements) {
1545   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
1546   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false);
1547   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine,
1548             FormatStyle::SIS_Never);
1549   EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false);
1550   EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false);
1551   verifyFormat("for (;;) {\n"
1552                "  f();\n"
1553                "}");
1554   verifyFormat("/*comment*/ for (;;) {\n"
1555                "  f();\n"
1556                "}");
1557   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1558                "  f();\n"
1559                "}");
1560   verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n"
1561                "  f();\n"
1562                "}");
1563   verifyFormat("while (true) {\n"
1564                "  f();\n"
1565                "}");
1566   verifyFormat("/*comment*/ while (true) {\n"
1567                "  f();\n"
1568                "}");
1569   verifyFormat("if (true) {\n"
1570                "  f();\n"
1571                "}");
1572   verifyFormat("/*comment*/ if (true) {\n"
1573                "  f();\n"
1574                "}");
1575 
1576   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1577       FormatStyle::SBS_Empty;
1578   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1579       FormatStyle::SIS_WithoutElse;
1580   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1581   verifyFormat("if (i) break;", AllowSimpleBracedStatements);
1582   verifyFormat("if (i > 0) {\n"
1583                "  return i;\n"
1584                "}",
1585                AllowSimpleBracedStatements);
1586 
1587   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1588   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1589   // Not IF to avoid any confusion that IF is somehow special.
1590   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1591   AllowSimpleBracedStatements.ColumnLimit = 40;
1592   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1593       FormatStyle::SBS_Always;
1594   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1595   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1596   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1597   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1598 
1599   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1600   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1601   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1602   verifyFormat("if consteval {}", AllowSimpleBracedStatements);
1603   verifyFormat("if !consteval {}", AllowSimpleBracedStatements);
1604   verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements);
1605   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1606   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1607   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1608   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1609   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1610   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1611   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1612   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1613   verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements);
1614   verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements);
1615   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1616   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1617   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1618   verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements);
1619   verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements);
1620   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1621   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1622   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1623                AllowSimpleBracedStatements);
1624   verifyFormat("if (true) {\n"
1625                "  ffffffffffffffffffffffff();\n"
1626                "}",
1627                AllowSimpleBracedStatements);
1628   verifyFormat("if (true) {\n"
1629                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1630                "}",
1631                AllowSimpleBracedStatements);
1632   verifyFormat("if (true) { //\n"
1633                "  f();\n"
1634                "}",
1635                AllowSimpleBracedStatements);
1636   verifyFormat("if (true) {\n"
1637                "  f();\n"
1638                "  f();\n"
1639                "}",
1640                AllowSimpleBracedStatements);
1641   verifyFormat("if (true) {\n"
1642                "  f();\n"
1643                "} else {\n"
1644                "  f();\n"
1645                "}",
1646                AllowSimpleBracedStatements);
1647   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1648                AllowSimpleBracedStatements);
1649   verifyFormat("MYIF (true) {\n"
1650                "  ffffffffffffffffffffffff();\n"
1651                "}",
1652                AllowSimpleBracedStatements);
1653   verifyFormat("MYIF (true) {\n"
1654                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1655                "}",
1656                AllowSimpleBracedStatements);
1657   verifyFormat("MYIF (true) { //\n"
1658                "  f();\n"
1659                "}",
1660                AllowSimpleBracedStatements);
1661   verifyFormat("MYIF (true) {\n"
1662                "  f();\n"
1663                "  f();\n"
1664                "}",
1665                AllowSimpleBracedStatements);
1666   verifyFormat("MYIF (true) {\n"
1667                "  f();\n"
1668                "} else {\n"
1669                "  f();\n"
1670                "}",
1671                AllowSimpleBracedStatements);
1672 
1673   verifyFormat("struct A2 {\n"
1674                "  int X;\n"
1675                "};",
1676                AllowSimpleBracedStatements);
1677   verifyFormat("typedef struct A2 {\n"
1678                "  int X;\n"
1679                "} A2_t;",
1680                AllowSimpleBracedStatements);
1681   verifyFormat("template <int> struct A2 {\n"
1682                "  struct B {};\n"
1683                "};",
1684                AllowSimpleBracedStatements);
1685 
1686   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1687       FormatStyle::SIS_Never;
1688   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1689   verifyFormat("if (true) {\n"
1690                "  f();\n"
1691                "}",
1692                AllowSimpleBracedStatements);
1693   verifyFormat("if (true) {\n"
1694                "  f();\n"
1695                "} else {\n"
1696                "  f();\n"
1697                "}",
1698                AllowSimpleBracedStatements);
1699   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1700   verifyFormat("MYIF (true) {\n"
1701                "  f();\n"
1702                "}",
1703                AllowSimpleBracedStatements);
1704   verifyFormat("MYIF (true) {\n"
1705                "  f();\n"
1706                "} else {\n"
1707                "  f();\n"
1708                "}",
1709                AllowSimpleBracedStatements);
1710 
1711   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1712   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1713   verifyFormat("while (true) {\n"
1714                "  f();\n"
1715                "}",
1716                AllowSimpleBracedStatements);
1717   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1718   verifyFormat("for (;;) {\n"
1719                "  f();\n"
1720                "}",
1721                AllowSimpleBracedStatements);
1722   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1723   verifyFormat("BOOST_FOREACH (int v, vec) {\n"
1724                "  f();\n"
1725                "}",
1726                AllowSimpleBracedStatements);
1727 
1728   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1729       FormatStyle::SIS_WithoutElse;
1730   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1731   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1732       FormatStyle::BWACS_Always;
1733 
1734   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1735   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1736   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1737   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1738   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1739   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1740   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1741   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1742   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1743   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1744   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1745   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1746   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1747   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1748   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1749   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1750   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1751                AllowSimpleBracedStatements);
1752   verifyFormat("if (true)\n"
1753                "{\n"
1754                "  ffffffffffffffffffffffff();\n"
1755                "}",
1756                AllowSimpleBracedStatements);
1757   verifyFormat("if (true)\n"
1758                "{\n"
1759                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1760                "}",
1761                AllowSimpleBracedStatements);
1762   verifyFormat("if (true)\n"
1763                "{ //\n"
1764                "  f();\n"
1765                "}",
1766                AllowSimpleBracedStatements);
1767   verifyFormat("if (true)\n"
1768                "{\n"
1769                "  f();\n"
1770                "  f();\n"
1771                "}",
1772                AllowSimpleBracedStatements);
1773   verifyFormat("if (true)\n"
1774                "{\n"
1775                "  f();\n"
1776                "} else\n"
1777                "{\n"
1778                "  f();\n"
1779                "}",
1780                AllowSimpleBracedStatements);
1781   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1782                AllowSimpleBracedStatements);
1783   verifyFormat("MYIF (true)\n"
1784                "{\n"
1785                "  ffffffffffffffffffffffff();\n"
1786                "}",
1787                AllowSimpleBracedStatements);
1788   verifyFormat("MYIF (true)\n"
1789                "{\n"
1790                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1791                "}",
1792                AllowSimpleBracedStatements);
1793   verifyFormat("MYIF (true)\n"
1794                "{ //\n"
1795                "  f();\n"
1796                "}",
1797                AllowSimpleBracedStatements);
1798   verifyFormat("MYIF (true)\n"
1799                "{\n"
1800                "  f();\n"
1801                "  f();\n"
1802                "}",
1803                AllowSimpleBracedStatements);
1804   verifyFormat("MYIF (true)\n"
1805                "{\n"
1806                "  f();\n"
1807                "} else\n"
1808                "{\n"
1809                "  f();\n"
1810                "}",
1811                AllowSimpleBracedStatements);
1812 
1813   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1814       FormatStyle::SIS_Never;
1815   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1816   verifyFormat("if (true)\n"
1817                "{\n"
1818                "  f();\n"
1819                "}",
1820                AllowSimpleBracedStatements);
1821   verifyFormat("if (true)\n"
1822                "{\n"
1823                "  f();\n"
1824                "} else\n"
1825                "{\n"
1826                "  f();\n"
1827                "}",
1828                AllowSimpleBracedStatements);
1829   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1830   verifyFormat("MYIF (true)\n"
1831                "{\n"
1832                "  f();\n"
1833                "}",
1834                AllowSimpleBracedStatements);
1835   verifyFormat("MYIF (true)\n"
1836                "{\n"
1837                "  f();\n"
1838                "} else\n"
1839                "{\n"
1840                "  f();\n"
1841                "}",
1842                AllowSimpleBracedStatements);
1843 
1844   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1845   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1846   verifyFormat("while (true)\n"
1847                "{\n"
1848                "  f();\n"
1849                "}",
1850                AllowSimpleBracedStatements);
1851   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1852   verifyFormat("for (;;)\n"
1853                "{\n"
1854                "  f();\n"
1855                "}",
1856                AllowSimpleBracedStatements);
1857   verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
1858   verifyFormat("BOOST_FOREACH (int v, vec)\n"
1859                "{\n"
1860                "  f();\n"
1861                "}",
1862                AllowSimpleBracedStatements);
1863 }
1864 
1865 TEST_F(FormatTest, UnderstandsMacros) {
1866   verifyFormat("#define A (parentheses)");
1867   verifyFormat("/* comment */ #define A (parentheses)");
1868   verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
1869   // Even the partial code should never be merged.
1870   EXPECT_EQ("/* comment */ #define A (parentheses)\n"
1871             "#",
1872             format("/* comment */ #define A (parentheses)\n"
1873                    "#"));
1874   verifyFormat("/* comment */ #define A (parentheses)\n"
1875                "#\n");
1876   verifyFormat("/* comment */ #define A (parentheses)\n"
1877                "#define B (parentheses)");
1878   verifyFormat("#define true ((int)1)");
1879   verifyFormat("#define and(x)");
1880   verifyFormat("#define if(x) x");
1881   verifyFormat("#define return(x) (x)");
1882   verifyFormat("#define while(x) for (; x;)");
1883   verifyFormat("#define xor(x) (^(x))");
1884   verifyFormat("#define __except(x)");
1885   verifyFormat("#define __try(x)");
1886 
1887   // https://llvm.org/PR54348.
1888   verifyFormat(
1889       "#define A"
1890       "                                                                      "
1891       "\\\n"
1892       "  class & {}");
1893 
1894   FormatStyle Style = getLLVMStyle();
1895   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1896   Style.BraceWrapping.AfterFunction = true;
1897   // Test that a macro definition never gets merged with the following
1898   // definition.
1899   // FIXME: The AAA macro definition probably should not be split into 3 lines.
1900   verifyFormat("#define AAA                                                    "
1901                "                \\\n"
1902                "  N                                                            "
1903                "                \\\n"
1904                "  {\n"
1905                "#define BBB }\n",
1906                Style);
1907   // verifyFormat("#define AAA N { //\n", Style);
1908 
1909   verifyFormat("MACRO(return)");
1910   verifyFormat("MACRO(co_await)");
1911   verifyFormat("MACRO(co_return)");
1912   verifyFormat("MACRO(co_yield)");
1913   verifyFormat("MACRO(return, something)");
1914   verifyFormat("MACRO(co_return, something)");
1915   verifyFormat("MACRO(something##something)");
1916   verifyFormat("MACRO(return##something)");
1917   verifyFormat("MACRO(co_return##something)");
1918 }
1919 
1920 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1921   FormatStyle Style = getLLVMStyleWithColumns(60);
1922   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1923   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1924   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1925   EXPECT_EQ("#define A                                                  \\\n"
1926             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1927             "  {                                                        \\\n"
1928             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1929             "  }\n"
1930             "X;",
1931             format("#define A \\\n"
1932                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1933                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1934                    "   }\n"
1935                    "X;",
1936                    Style));
1937 }
1938 
1939 TEST_F(FormatTest, ParseIfElse) {
1940   verifyFormat("if (true)\n"
1941                "  if (true)\n"
1942                "    if (true)\n"
1943                "      f();\n"
1944                "    else\n"
1945                "      g();\n"
1946                "  else\n"
1947                "    h();\n"
1948                "else\n"
1949                "  i();");
1950   verifyFormat("if (true)\n"
1951                "  if (true)\n"
1952                "    if (true) {\n"
1953                "      if (true)\n"
1954                "        f();\n"
1955                "    } else {\n"
1956                "      g();\n"
1957                "    }\n"
1958                "  else\n"
1959                "    h();\n"
1960                "else {\n"
1961                "  i();\n"
1962                "}");
1963   verifyFormat("if (true)\n"
1964                "  if constexpr (true)\n"
1965                "    if (true) {\n"
1966                "      if constexpr (true)\n"
1967                "        f();\n"
1968                "    } else {\n"
1969                "      g();\n"
1970                "    }\n"
1971                "  else\n"
1972                "    h();\n"
1973                "else {\n"
1974                "  i();\n"
1975                "}");
1976   verifyFormat("if (true)\n"
1977                "  if CONSTEXPR (true)\n"
1978                "    if (true) {\n"
1979                "      if CONSTEXPR (true)\n"
1980                "        f();\n"
1981                "    } else {\n"
1982                "      g();\n"
1983                "    }\n"
1984                "  else\n"
1985                "    h();\n"
1986                "else {\n"
1987                "  i();\n"
1988                "}");
1989   verifyFormat("void f() {\n"
1990                "  if (a) {\n"
1991                "  } else {\n"
1992                "  }\n"
1993                "}");
1994 }
1995 
1996 TEST_F(FormatTest, ElseIf) {
1997   verifyFormat("if (a) {\n} else if (b) {\n}");
1998   verifyFormat("if (a)\n"
1999                "  f();\n"
2000                "else if (b)\n"
2001                "  g();\n"
2002                "else\n"
2003                "  h();");
2004   verifyFormat("if (a)\n"
2005                "  f();\n"
2006                "else // comment\n"
2007                "  if (b) {\n"
2008                "    g();\n"
2009                "    h();\n"
2010                "  }");
2011   verifyFormat("if constexpr (a)\n"
2012                "  f();\n"
2013                "else if constexpr (b)\n"
2014                "  g();\n"
2015                "else\n"
2016                "  h();");
2017   verifyFormat("if CONSTEXPR (a)\n"
2018                "  f();\n"
2019                "else if CONSTEXPR (b)\n"
2020                "  g();\n"
2021                "else\n"
2022                "  h();");
2023   verifyFormat("if (a) {\n"
2024                "  f();\n"
2025                "}\n"
2026                "// or else ..\n"
2027                "else {\n"
2028                "  g()\n"
2029                "}");
2030 
2031   verifyFormat("if (a) {\n"
2032                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2033                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2034                "}");
2035   verifyFormat("if (a) {\n"
2036                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2037                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2038                "}");
2039   verifyFormat("if (a) {\n"
2040                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2041                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2042                "}");
2043   verifyFormat("if (a) {\n"
2044                "} else if (\n"
2045                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2046                "}",
2047                getLLVMStyleWithColumns(62));
2048   verifyFormat("if (a) {\n"
2049                "} else if constexpr (\n"
2050                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2051                "}",
2052                getLLVMStyleWithColumns(62));
2053   verifyFormat("if (a) {\n"
2054                "} else if CONSTEXPR (\n"
2055                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2056                "}",
2057                getLLVMStyleWithColumns(62));
2058 }
2059 
2060 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
2061   FormatStyle Style = getLLVMStyle();
2062   EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
2063   EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer);
2064   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
2065   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
2066   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
2067   verifyFormat("int *f1(int &a) const &;", Style);
2068   verifyFormat("int *f1(int &a) const & = 0;", Style);
2069   verifyFormat("int *a = f1();", Style);
2070   verifyFormat("int &b = f2();", Style);
2071   verifyFormat("int &&c = f3();", Style);
2072   verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2073   verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2074   verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2075   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2076   verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style);
2077   verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style);
2078   verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style);
2079   verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style);
2080   verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style);
2081   verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style);
2082   verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style);
2083   verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style);
2084   verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style);
2085   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
2086   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
2087   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
2088   verifyFormat(
2089       "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n"
2090       "                     res2 = [](int &a) { return 0000000000000; };",
2091       Style);
2092 
2093   Style.AlignConsecutiveDeclarations.Enabled = true;
2094   verifyFormat("Const unsigned int *c;\n"
2095                "const unsigned int *d;\n"
2096                "Const unsigned int &e;\n"
2097                "const unsigned int &f;\n"
2098                "const unsigned    &&g;\n"
2099                "Const unsigned      h;",
2100                Style);
2101 
2102   Style.PointerAlignment = FormatStyle::PAS_Left;
2103   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
2104   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
2105   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
2106   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
2107   verifyFormat("int* f1(int& a) const& = 0;", Style);
2108   verifyFormat("int* a = f1();", Style);
2109   verifyFormat("int& b = f2();", Style);
2110   verifyFormat("int&& c = f3();", Style);
2111   verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2112   verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2113   verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2114   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2115   verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style);
2116   verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style);
2117   verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style);
2118   verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2119   verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style);
2120   verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style);
2121   verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style);
2122   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2123   verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style);
2124   verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style);
2125   verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style);
2126   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
2127   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
2128   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
2129   verifyFormat(
2130       "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n"
2131       "                    res2 = [](int& a) { return 0000000000000; };",
2132       Style);
2133 
2134   Style.AlignConsecutiveDeclarations.Enabled = true;
2135   verifyFormat("Const unsigned int* c;\n"
2136                "const unsigned int* d;\n"
2137                "Const unsigned int& e;\n"
2138                "const unsigned int& f;\n"
2139                "const unsigned&&    g;\n"
2140                "Const unsigned      h;",
2141                Style);
2142 
2143   Style.PointerAlignment = FormatStyle::PAS_Right;
2144   Style.ReferenceAlignment = FormatStyle::RAS_Left;
2145   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
2146   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
2147   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
2148   verifyFormat("int *a = f1();", Style);
2149   verifyFormat("int& b = f2();", Style);
2150   verifyFormat("int&& c = f3();", Style);
2151   verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2152   verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
2153   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
2154 
2155   Style.AlignConsecutiveDeclarations.Enabled = true;
2156   verifyFormat("Const unsigned int *c;\n"
2157                "const unsigned int *d;\n"
2158                "Const unsigned int& e;\n"
2159                "const unsigned int& f;\n"
2160                "const unsigned      g;\n"
2161                "Const unsigned      h;",
2162                Style);
2163 
2164   Style.PointerAlignment = FormatStyle::PAS_Left;
2165   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
2166   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
2167   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
2168   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
2169   verifyFormat("int* a = f1();", Style);
2170   verifyFormat("int & b = f2();", Style);
2171   verifyFormat("int && c = f3();", Style);
2172   verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style);
2173   verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style);
2174   verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style);
2175   verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style);
2176   verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style);
2177   verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style);
2178   verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style);
2179   verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style);
2180   verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style);
2181   verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style);
2182   verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style);
2183   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
2184   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
2185   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
2186   verifyFormat(
2187       "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n"
2188       "                     res2 = [](int & a) { return 0000000000000; };",
2189       Style);
2190 
2191   Style.AlignConsecutiveDeclarations.Enabled = true;
2192   verifyFormat("Const unsigned int*  c;\n"
2193                "const unsigned int*  d;\n"
2194                "Const unsigned int & e;\n"
2195                "const unsigned int & f;\n"
2196                "const unsigned &&    g;\n"
2197                "Const unsigned       h;",
2198                Style);
2199 
2200   Style.PointerAlignment = FormatStyle::PAS_Middle;
2201   Style.ReferenceAlignment = FormatStyle::RAS_Right;
2202   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
2203   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
2204   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
2205   verifyFormat("int * a = f1();", Style);
2206   verifyFormat("int &b = f2();", Style);
2207   verifyFormat("int &&c = f3();", Style);
2208   verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2209   verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style);
2210   verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style);
2211 
2212   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2213   // specifically handled
2214   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2215 }
2216 
2217 TEST_F(FormatTest, FormatsForLoop) {
2218   verifyFormat(
2219       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2220       "     ++VeryVeryLongLoopVariable)\n"
2221       "  ;");
2222   verifyFormat("for (;;)\n"
2223                "  f();");
2224   verifyFormat("for (;;) {\n}");
2225   verifyFormat("for (;;) {\n"
2226                "  f();\n"
2227                "}");
2228   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2229 
2230   verifyFormat(
2231       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2232       "                                          E = UnwrappedLines.end();\n"
2233       "     I != E; ++I) {\n}");
2234 
2235   verifyFormat(
2236       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2237       "     ++IIIII) {\n}");
2238   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2239                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2240                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2241   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2242                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2243                "         E = FD->getDeclsInPrototypeScope().end();\n"
2244                "     I != E; ++I) {\n}");
2245   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2246                "         I = Container.begin(),\n"
2247                "         E = Container.end();\n"
2248                "     I != E; ++I) {\n}",
2249                getLLVMStyleWithColumns(76));
2250 
2251   verifyFormat(
2252       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2253       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2254       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2255       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2256       "     ++aaaaaaaaaaa) {\n}");
2257   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2258                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2259                "     ++i) {\n}");
2260   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2261                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2262                "}");
2263   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2264                "         aaaaaaaaaa);\n"
2265                "     iter; ++iter) {\n"
2266                "}");
2267   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2268                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2269                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2270                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2271 
2272   // These should not be formatted as Objective-C for-in loops.
2273   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2274   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2275   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2276   verifyFormat(
2277       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2278 
2279   FormatStyle NoBinPacking = getLLVMStyle();
2280   NoBinPacking.BinPackParameters = false;
2281   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2282                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2283                "                                           aaaaaaaaaaaaaaaa,\n"
2284                "                                           aaaaaaaaaaaaaaaa,\n"
2285                "                                           aaaaaaaaaaaaaaaa);\n"
2286                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2287                "}",
2288                NoBinPacking);
2289   verifyFormat(
2290       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2291       "                                          E = UnwrappedLines.end();\n"
2292       "     I != E;\n"
2293       "     ++I) {\n}",
2294       NoBinPacking);
2295 
2296   FormatStyle AlignLeft = getLLVMStyle();
2297   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2298   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2299 }
2300 
2301 TEST_F(FormatTest, RangeBasedForLoops) {
2302   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2303                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2304   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2305                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2306   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2307                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2308   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2309                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2310 }
2311 
2312 TEST_F(FormatTest, ForEachLoops) {
2313   FormatStyle Style = getLLVMStyle();
2314   EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2315   EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
2316   verifyFormat("void f() {\n"
2317                "  for (;;) {\n"
2318                "  }\n"
2319                "  foreach (Item *item, itemlist) {\n"
2320                "  }\n"
2321                "  Q_FOREACH (Item *item, itemlist) {\n"
2322                "  }\n"
2323                "  BOOST_FOREACH (Item *item, itemlist) {\n"
2324                "  }\n"
2325                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2326                "}",
2327                Style);
2328   verifyFormat("void f() {\n"
2329                "  for (;;)\n"
2330                "    int j = 1;\n"
2331                "  Q_FOREACH (int v, vec)\n"
2332                "    v *= 2;\n"
2333                "  for (;;) {\n"
2334                "    int j = 1;\n"
2335                "  }\n"
2336                "  Q_FOREACH (int v, vec) {\n"
2337                "    v *= 2;\n"
2338                "  }\n"
2339                "}",
2340                Style);
2341 
2342   FormatStyle ShortBlocks = getLLVMStyle();
2343   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2344   EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
2345   verifyFormat("void f() {\n"
2346                "  for (;;)\n"
2347                "    int j = 1;\n"
2348                "  Q_FOREACH (int &v, vec)\n"
2349                "    v *= 2;\n"
2350                "  for (;;) {\n"
2351                "    int j = 1;\n"
2352                "  }\n"
2353                "  Q_FOREACH (int &v, vec) {\n"
2354                "    int j = 1;\n"
2355                "  }\n"
2356                "}",
2357                ShortBlocks);
2358 
2359   FormatStyle ShortLoops = getLLVMStyle();
2360   ShortLoops.AllowShortLoopsOnASingleLine = true;
2361   EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
2362   verifyFormat("void f() {\n"
2363                "  for (;;) int j = 1;\n"
2364                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2365                "  for (;;) {\n"
2366                "    int j = 1;\n"
2367                "  }\n"
2368                "  Q_FOREACH (int &v, vec) {\n"
2369                "    int j = 1;\n"
2370                "  }\n"
2371                "}",
2372                ShortLoops);
2373 
2374   FormatStyle ShortBlocksAndLoops = getLLVMStyle();
2375   ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
2376   ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true;
2377   verifyFormat("void f() {\n"
2378                "  for (;;) int j = 1;\n"
2379                "  Q_FOREACH (int &v, vec) int j = 1;\n"
2380                "  for (;;) { int j = 1; }\n"
2381                "  Q_FOREACH (int &v, vec) { int j = 1; }\n"
2382                "}",
2383                ShortBlocksAndLoops);
2384 
2385   Style.SpaceBeforeParens =
2386       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2387   verifyFormat("void f() {\n"
2388                "  for (;;) {\n"
2389                "  }\n"
2390                "  foreach(Item *item, itemlist) {\n"
2391                "  }\n"
2392                "  Q_FOREACH(Item *item, itemlist) {\n"
2393                "  }\n"
2394                "  BOOST_FOREACH(Item *item, itemlist) {\n"
2395                "  }\n"
2396                "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
2397                "}",
2398                Style);
2399 
2400   // As function-like macros.
2401   verifyFormat("#define foreach(x, y)\n"
2402                "#define Q_FOREACH(x, y)\n"
2403                "#define BOOST_FOREACH(x, y)\n"
2404                "#define UNKNOWN_FOREACH(x, y)\n");
2405 
2406   // Not as function-like macros.
2407   verifyFormat("#define foreach (x, y)\n"
2408                "#define Q_FOREACH (x, y)\n"
2409                "#define BOOST_FOREACH (x, y)\n"
2410                "#define UNKNOWN_FOREACH (x, y)\n");
2411 
2412   // handle microsoft non standard extension
2413   verifyFormat("for each (char c in x->MyStringProperty)");
2414 }
2415 
2416 TEST_F(FormatTest, FormatsWhileLoop) {
2417   verifyFormat("while (true) {\n}");
2418   verifyFormat("while (true)\n"
2419                "  f();");
2420   verifyFormat("while () {\n}");
2421   verifyFormat("while () {\n"
2422                "  f();\n"
2423                "}");
2424 }
2425 
2426 TEST_F(FormatTest, FormatsDoWhile) {
2427   verifyFormat("do {\n"
2428                "  do_something();\n"
2429                "} while (something());");
2430   verifyFormat("do\n"
2431                "  do_something();\n"
2432                "while (something());");
2433 }
2434 
2435 TEST_F(FormatTest, FormatsSwitchStatement) {
2436   verifyFormat("switch (x) {\n"
2437                "case 1:\n"
2438                "  f();\n"
2439                "  break;\n"
2440                "case kFoo:\n"
2441                "case ns::kBar:\n"
2442                "case kBaz:\n"
2443                "  break;\n"
2444                "default:\n"
2445                "  g();\n"
2446                "  break;\n"
2447                "}");
2448   verifyFormat("switch (x) {\n"
2449                "case 1: {\n"
2450                "  f();\n"
2451                "  break;\n"
2452                "}\n"
2453                "case 2: {\n"
2454                "  break;\n"
2455                "}\n"
2456                "}");
2457   verifyFormat("switch (x) {\n"
2458                "case 1: {\n"
2459                "  f();\n"
2460                "  {\n"
2461                "    g();\n"
2462                "    h();\n"
2463                "  }\n"
2464                "  break;\n"
2465                "}\n"
2466                "}");
2467   verifyFormat("switch (x) {\n"
2468                "case 1: {\n"
2469                "  f();\n"
2470                "  if (foo) {\n"
2471                "    g();\n"
2472                "    h();\n"
2473                "  }\n"
2474                "  break;\n"
2475                "}\n"
2476                "}");
2477   verifyFormat("switch (x) {\n"
2478                "case 1: {\n"
2479                "  f();\n"
2480                "  g();\n"
2481                "} break;\n"
2482                "}");
2483   verifyFormat("switch (test)\n"
2484                "  ;");
2485   verifyFormat("switch (x) {\n"
2486                "default: {\n"
2487                "  // Do nothing.\n"
2488                "}\n"
2489                "}");
2490   verifyFormat("switch (x) {\n"
2491                "// comment\n"
2492                "// if 1, do f()\n"
2493                "case 1:\n"
2494                "  f();\n"
2495                "}");
2496   verifyFormat("switch (x) {\n"
2497                "case 1:\n"
2498                "  // Do amazing stuff\n"
2499                "  {\n"
2500                "    f();\n"
2501                "    g();\n"
2502                "  }\n"
2503                "  break;\n"
2504                "}");
2505   verifyFormat("#define A          \\\n"
2506                "  switch (x) {     \\\n"
2507                "  case a:          \\\n"
2508                "    foo = b;       \\\n"
2509                "  }",
2510                getLLVMStyleWithColumns(20));
2511   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2512                "  case OP_name:                        \\\n"
2513                "    return operations::Operation##name\n",
2514                getLLVMStyleWithColumns(40));
2515   verifyFormat("switch (x) {\n"
2516                "case 1:;\n"
2517                "default:;\n"
2518                "  int i;\n"
2519                "}");
2520 
2521   verifyGoogleFormat("switch (x) {\n"
2522                      "  case 1:\n"
2523                      "    f();\n"
2524                      "    break;\n"
2525                      "  case kFoo:\n"
2526                      "  case ns::kBar:\n"
2527                      "  case kBaz:\n"
2528                      "    break;\n"
2529                      "  default:\n"
2530                      "    g();\n"
2531                      "    break;\n"
2532                      "}");
2533   verifyGoogleFormat("switch (x) {\n"
2534                      "  case 1: {\n"
2535                      "    f();\n"
2536                      "    break;\n"
2537                      "  }\n"
2538                      "}");
2539   verifyGoogleFormat("switch (test)\n"
2540                      "  ;");
2541 
2542   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2543                      "  case OP_name:              \\\n"
2544                      "    return operations::Operation##name\n");
2545   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2546                      "  // Get the correction operation class.\n"
2547                      "  switch (OpCode) {\n"
2548                      "    CASE(Add);\n"
2549                      "    CASE(Subtract);\n"
2550                      "    default:\n"
2551                      "      return operations::Unknown;\n"
2552                      "  }\n"
2553                      "#undef OPERATION_CASE\n"
2554                      "}");
2555   verifyFormat("DEBUG({\n"
2556                "  switch (x) {\n"
2557                "  case A:\n"
2558                "    f();\n"
2559                "    break;\n"
2560                "    // fallthrough\n"
2561                "  case B:\n"
2562                "    g();\n"
2563                "    break;\n"
2564                "  }\n"
2565                "});");
2566   EXPECT_EQ("DEBUG({\n"
2567             "  switch (x) {\n"
2568             "  case A:\n"
2569             "    f();\n"
2570             "    break;\n"
2571             "  // On B:\n"
2572             "  case B:\n"
2573             "    g();\n"
2574             "    break;\n"
2575             "  }\n"
2576             "});",
2577             format("DEBUG({\n"
2578                    "  switch (x) {\n"
2579                    "  case A:\n"
2580                    "    f();\n"
2581                    "    break;\n"
2582                    "  // On B:\n"
2583                    "  case B:\n"
2584                    "    g();\n"
2585                    "    break;\n"
2586                    "  }\n"
2587                    "});",
2588                    getLLVMStyle()));
2589   EXPECT_EQ("switch (n) {\n"
2590             "case 0: {\n"
2591             "  return false;\n"
2592             "}\n"
2593             "default: {\n"
2594             "  return true;\n"
2595             "}\n"
2596             "}",
2597             format("switch (n)\n"
2598                    "{\n"
2599                    "case 0: {\n"
2600                    "  return false;\n"
2601                    "}\n"
2602                    "default: {\n"
2603                    "  return true;\n"
2604                    "}\n"
2605                    "}",
2606                    getLLVMStyle()));
2607   verifyFormat("switch (a) {\n"
2608                "case (b):\n"
2609                "  return;\n"
2610                "}");
2611 
2612   verifyFormat("switch (a) {\n"
2613                "case some_namespace::\n"
2614                "    some_constant:\n"
2615                "  return;\n"
2616                "}",
2617                getLLVMStyleWithColumns(34));
2618 
2619   verifyFormat("switch (a) {\n"
2620                "[[likely]] case 1:\n"
2621                "  return;\n"
2622                "}");
2623   verifyFormat("switch (a) {\n"
2624                "[[likely]] [[other::likely]] case 1:\n"
2625                "  return;\n"
2626                "}");
2627   verifyFormat("switch (x) {\n"
2628                "case 1:\n"
2629                "  return;\n"
2630                "[[likely]] case 2:\n"
2631                "  return;\n"
2632                "}");
2633   verifyFormat("switch (a) {\n"
2634                "case 1:\n"
2635                "[[likely]] case 2:\n"
2636                "  return;\n"
2637                "}");
2638   FormatStyle Attributes = getLLVMStyle();
2639   Attributes.AttributeMacros.push_back("LIKELY");
2640   Attributes.AttributeMacros.push_back("OTHER_LIKELY");
2641   verifyFormat("switch (a) {\n"
2642                "LIKELY case b:\n"
2643                "  return;\n"
2644                "}",
2645                Attributes);
2646   verifyFormat("switch (a) {\n"
2647                "LIKELY OTHER_LIKELY() case b:\n"
2648                "  return;\n"
2649                "}",
2650                Attributes);
2651   verifyFormat("switch (a) {\n"
2652                "case 1:\n"
2653                "  return;\n"
2654                "LIKELY case 2:\n"
2655                "  return;\n"
2656                "}",
2657                Attributes);
2658   verifyFormat("switch (a) {\n"
2659                "case 1:\n"
2660                "LIKELY case 2:\n"
2661                "  return;\n"
2662                "}",
2663                Attributes);
2664 
2665   FormatStyle Style = getLLVMStyle();
2666   Style.IndentCaseLabels = true;
2667   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2668   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2669   Style.BraceWrapping.AfterCaseLabel = true;
2670   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2671   EXPECT_EQ("switch (n)\n"
2672             "{\n"
2673             "  case 0:\n"
2674             "  {\n"
2675             "    return false;\n"
2676             "  }\n"
2677             "  default:\n"
2678             "  {\n"
2679             "    return true;\n"
2680             "  }\n"
2681             "}",
2682             format("switch (n) {\n"
2683                    "  case 0: {\n"
2684                    "    return false;\n"
2685                    "  }\n"
2686                    "  default: {\n"
2687                    "    return true;\n"
2688                    "  }\n"
2689                    "}",
2690                    Style));
2691   Style.BraceWrapping.AfterCaseLabel = false;
2692   EXPECT_EQ("switch (n)\n"
2693             "{\n"
2694             "  case 0: {\n"
2695             "    return false;\n"
2696             "  }\n"
2697             "  default: {\n"
2698             "    return true;\n"
2699             "  }\n"
2700             "}",
2701             format("switch (n) {\n"
2702                    "  case 0:\n"
2703                    "  {\n"
2704                    "    return false;\n"
2705                    "  }\n"
2706                    "  default:\n"
2707                    "  {\n"
2708                    "    return true;\n"
2709                    "  }\n"
2710                    "}",
2711                    Style));
2712   Style.IndentCaseLabels = false;
2713   Style.IndentCaseBlocks = true;
2714   EXPECT_EQ("switch (n)\n"
2715             "{\n"
2716             "case 0:\n"
2717             "  {\n"
2718             "    return false;\n"
2719             "  }\n"
2720             "case 1:\n"
2721             "  break;\n"
2722             "default:\n"
2723             "  {\n"
2724             "    return true;\n"
2725             "  }\n"
2726             "}",
2727             format("switch (n) {\n"
2728                    "case 0: {\n"
2729                    "  return false;\n"
2730                    "}\n"
2731                    "case 1:\n"
2732                    "  break;\n"
2733                    "default: {\n"
2734                    "  return true;\n"
2735                    "}\n"
2736                    "}",
2737                    Style));
2738   Style.IndentCaseLabels = true;
2739   Style.IndentCaseBlocks = true;
2740   EXPECT_EQ("switch (n)\n"
2741             "{\n"
2742             "  case 0:\n"
2743             "    {\n"
2744             "      return false;\n"
2745             "    }\n"
2746             "  case 1:\n"
2747             "    break;\n"
2748             "  default:\n"
2749             "    {\n"
2750             "      return true;\n"
2751             "    }\n"
2752             "}",
2753             format("switch (n) {\n"
2754                    "case 0: {\n"
2755                    "  return false;\n"
2756                    "}\n"
2757                    "case 1:\n"
2758                    "  break;\n"
2759                    "default: {\n"
2760                    "  return true;\n"
2761                    "}\n"
2762                    "}",
2763                    Style));
2764 }
2765 
2766 TEST_F(FormatTest, CaseRanges) {
2767   verifyFormat("switch (x) {\n"
2768                "case 'A' ... 'Z':\n"
2769                "case 1 ... 5:\n"
2770                "case a ... b:\n"
2771                "  break;\n"
2772                "}");
2773 }
2774 
2775 TEST_F(FormatTest, ShortEnums) {
2776   FormatStyle Style = getLLVMStyle();
2777   EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine);
2778   EXPECT_FALSE(Style.BraceWrapping.AfterEnum);
2779   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2780   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2781   Style.AllowShortEnumsOnASingleLine = false;
2782   verifyFormat("enum {\n"
2783                "  A,\n"
2784                "  B,\n"
2785                "  C\n"
2786                "} ShortEnum1, ShortEnum2;",
2787                Style);
2788   verifyFormat("typedef enum {\n"
2789                "  A,\n"
2790                "  B,\n"
2791                "  C\n"
2792                "} ShortEnum1, ShortEnum2;",
2793                Style);
2794   verifyFormat("enum {\n"
2795                "  A,\n"
2796                "} ShortEnum1, ShortEnum2;",
2797                Style);
2798   verifyFormat("typedef enum {\n"
2799                "  A,\n"
2800                "} ShortEnum1, ShortEnum2;",
2801                Style);
2802   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2803   Style.BraceWrapping.AfterEnum = true;
2804   verifyFormat("enum\n"
2805                "{\n"
2806                "  A,\n"
2807                "  B,\n"
2808                "  C\n"
2809                "} ShortEnum1, ShortEnum2;",
2810                Style);
2811   verifyFormat("typedef enum\n"
2812                "{\n"
2813                "  A,\n"
2814                "  B,\n"
2815                "  C\n"
2816                "} ShortEnum1, ShortEnum2;",
2817                Style);
2818 }
2819 
2820 TEST_F(FormatTest, ShortCaseLabels) {
2821   FormatStyle Style = getLLVMStyle();
2822   Style.AllowShortCaseLabelsOnASingleLine = true;
2823   verifyFormat("switch (a) {\n"
2824                "case 1: x = 1; break;\n"
2825                "case 2: return;\n"
2826                "case 3:\n"
2827                "case 4:\n"
2828                "case 5: return;\n"
2829                "case 6: // comment\n"
2830                "  return;\n"
2831                "case 7:\n"
2832                "  // comment\n"
2833                "  return;\n"
2834                "case 8:\n"
2835                "  x = 8; // comment\n"
2836                "  break;\n"
2837                "default: y = 1; break;\n"
2838                "}",
2839                Style);
2840   verifyFormat("switch (a) {\n"
2841                "case 0: return; // comment\n"
2842                "case 1: break;  // comment\n"
2843                "case 2: return;\n"
2844                "// comment\n"
2845                "case 3: return;\n"
2846                "// comment 1\n"
2847                "// comment 2\n"
2848                "// comment 3\n"
2849                "case 4: break; /* comment */\n"
2850                "case 5:\n"
2851                "  // comment\n"
2852                "  break;\n"
2853                "case 6: /* comment */ x = 1; break;\n"
2854                "case 7: x = /* comment */ 1; break;\n"
2855                "case 8:\n"
2856                "  x = 1; /* comment */\n"
2857                "  break;\n"
2858                "case 9:\n"
2859                "  break; // comment line 1\n"
2860                "         // comment line 2\n"
2861                "}",
2862                Style);
2863   EXPECT_EQ("switch (a) {\n"
2864             "case 1:\n"
2865             "  x = 8;\n"
2866             "  // fall through\n"
2867             "case 2: x = 8;\n"
2868             "// comment\n"
2869             "case 3:\n"
2870             "  return; /* comment line 1\n"
2871             "           * comment line 2 */\n"
2872             "case 4: i = 8;\n"
2873             "// something else\n"
2874             "#if FOO\n"
2875             "case 5: break;\n"
2876             "#endif\n"
2877             "}",
2878             format("switch (a) {\n"
2879                    "case 1: x = 8;\n"
2880                    "  // fall through\n"
2881                    "case 2:\n"
2882                    "  x = 8;\n"
2883                    "// comment\n"
2884                    "case 3:\n"
2885                    "  return; /* comment line 1\n"
2886                    "           * comment line 2 */\n"
2887                    "case 4:\n"
2888                    "  i = 8;\n"
2889                    "// something else\n"
2890                    "#if FOO\n"
2891                    "case 5: break;\n"
2892                    "#endif\n"
2893                    "}",
2894                    Style));
2895   EXPECT_EQ("switch (a) {\n"
2896             "case 0:\n"
2897             "  return; // long long long long long long long long long long "
2898             "long long comment\n"
2899             "          // line\n"
2900             "}",
2901             format("switch (a) {\n"
2902                    "case 0: return; // long long long long long long long long "
2903                    "long long long long comment line\n"
2904                    "}",
2905                    Style));
2906   EXPECT_EQ("switch (a) {\n"
2907             "case 0:\n"
2908             "  return; /* long long long long long long long long long long "
2909             "long long comment\n"
2910             "             line */\n"
2911             "}",
2912             format("switch (a) {\n"
2913                    "case 0: return; /* long long long long long long long long "
2914                    "long long long long comment line */\n"
2915                    "}",
2916                    Style));
2917   verifyFormat("switch (a) {\n"
2918                "#if FOO\n"
2919                "case 0: return 0;\n"
2920                "#endif\n"
2921                "}",
2922                Style);
2923   verifyFormat("switch (a) {\n"
2924                "case 1: {\n"
2925                "}\n"
2926                "case 2: {\n"
2927                "  return;\n"
2928                "}\n"
2929                "case 3: {\n"
2930                "  x = 1;\n"
2931                "  return;\n"
2932                "}\n"
2933                "case 4:\n"
2934                "  if (x)\n"
2935                "    return;\n"
2936                "}",
2937                Style);
2938   Style.ColumnLimit = 21;
2939   verifyFormat("switch (a) {\n"
2940                "case 1: x = 1; break;\n"
2941                "case 2: return;\n"
2942                "case 3:\n"
2943                "case 4:\n"
2944                "case 5: return;\n"
2945                "default:\n"
2946                "  y = 1;\n"
2947                "  break;\n"
2948                "}",
2949                Style);
2950   Style.ColumnLimit = 80;
2951   Style.AllowShortCaseLabelsOnASingleLine = false;
2952   Style.IndentCaseLabels = true;
2953   EXPECT_EQ("switch (n) {\n"
2954             "  default /*comments*/:\n"
2955             "    return true;\n"
2956             "  case 0:\n"
2957             "    return false;\n"
2958             "}",
2959             format("switch (n) {\n"
2960                    "default/*comments*/:\n"
2961                    "  return true;\n"
2962                    "case 0:\n"
2963                    "  return false;\n"
2964                    "}",
2965                    Style));
2966   Style.AllowShortCaseLabelsOnASingleLine = true;
2967   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2968   Style.BraceWrapping.AfterCaseLabel = true;
2969   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2970   EXPECT_EQ("switch (n)\n"
2971             "{\n"
2972             "  case 0:\n"
2973             "  {\n"
2974             "    return false;\n"
2975             "  }\n"
2976             "  default:\n"
2977             "  {\n"
2978             "    return true;\n"
2979             "  }\n"
2980             "}",
2981             format("switch (n) {\n"
2982                    "  case 0: {\n"
2983                    "    return false;\n"
2984                    "  }\n"
2985                    "  default:\n"
2986                    "  {\n"
2987                    "    return true;\n"
2988                    "  }\n"
2989                    "}",
2990                    Style));
2991 }
2992 
2993 TEST_F(FormatTest, FormatsLabels) {
2994   verifyFormat("void f() {\n"
2995                "  some_code();\n"
2996                "test_label:\n"
2997                "  some_other_code();\n"
2998                "  {\n"
2999                "    some_more_code();\n"
3000                "  another_label:\n"
3001                "    some_more_code();\n"
3002                "  }\n"
3003                "}");
3004   verifyFormat("{\n"
3005                "  some_code();\n"
3006                "test_label:\n"
3007                "  some_other_code();\n"
3008                "}");
3009   verifyFormat("{\n"
3010                "  some_code();\n"
3011                "test_label:;\n"
3012                "  int i = 0;\n"
3013                "}");
3014   FormatStyle Style = getLLVMStyle();
3015   Style.IndentGotoLabels = false;
3016   verifyFormat("void f() {\n"
3017                "  some_code();\n"
3018                "test_label:\n"
3019                "  some_other_code();\n"
3020                "  {\n"
3021                "    some_more_code();\n"
3022                "another_label:\n"
3023                "    some_more_code();\n"
3024                "  }\n"
3025                "}",
3026                Style);
3027   verifyFormat("{\n"
3028                "  some_code();\n"
3029                "test_label:\n"
3030                "  some_other_code();\n"
3031                "}",
3032                Style);
3033   verifyFormat("{\n"
3034                "  some_code();\n"
3035                "test_label:;\n"
3036                "  int i = 0;\n"
3037                "}");
3038 }
3039 
3040 TEST_F(FormatTest, MultiLineControlStatements) {
3041   FormatStyle Style = getLLVMStyleWithColumns(20);
3042   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3043   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3044   // Short lines should keep opening brace on same line.
3045   EXPECT_EQ("if (foo) {\n"
3046             "  bar();\n"
3047             "}",
3048             format("if(foo){bar();}", Style));
3049   EXPECT_EQ("if (foo) {\n"
3050             "  bar();\n"
3051             "} else {\n"
3052             "  baz();\n"
3053             "}",
3054             format("if(foo){bar();}else{baz();}", Style));
3055   EXPECT_EQ("if (foo && bar) {\n"
3056             "  baz();\n"
3057             "}",
3058             format("if(foo&&bar){baz();}", Style));
3059   EXPECT_EQ("if (foo) {\n"
3060             "  bar();\n"
3061             "} else if (baz) {\n"
3062             "  quux();\n"
3063             "}",
3064             format("if(foo){bar();}else if(baz){quux();}", Style));
3065   EXPECT_EQ(
3066       "if (foo) {\n"
3067       "  bar();\n"
3068       "} else if (baz) {\n"
3069       "  quux();\n"
3070       "} else {\n"
3071       "  foobar();\n"
3072       "}",
3073       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
3074   EXPECT_EQ("for (;;) {\n"
3075             "  foo();\n"
3076             "}",
3077             format("for(;;){foo();}"));
3078   EXPECT_EQ("while (1) {\n"
3079             "  foo();\n"
3080             "}",
3081             format("while(1){foo();}", Style));
3082   EXPECT_EQ("switch (foo) {\n"
3083             "case bar:\n"
3084             "  return;\n"
3085             "}",
3086             format("switch(foo){case bar:return;}", Style));
3087   EXPECT_EQ("try {\n"
3088             "  foo();\n"
3089             "} catch (...) {\n"
3090             "  bar();\n"
3091             "}",
3092             format("try{foo();}catch(...){bar();}", Style));
3093   EXPECT_EQ("do {\n"
3094             "  foo();\n"
3095             "} while (bar &&\n"
3096             "         baz);",
3097             format("do{foo();}while(bar&&baz);", Style));
3098   // Long lines should put opening brace on new line.
3099   verifyFormat("void f() {\n"
3100                "  if (a1 && a2 &&\n"
3101                "      a3)\n"
3102                "  {\n"
3103                "    quux();\n"
3104                "  }\n"
3105                "}",
3106                "void f(){if(a1&&a2&&a3){quux();}}", Style);
3107   EXPECT_EQ("if (foo && bar &&\n"
3108             "    baz)\n"
3109             "{\n"
3110             "  quux();\n"
3111             "}",
3112             format("if(foo&&bar&&baz){quux();}", Style));
3113   EXPECT_EQ("if (foo && bar &&\n"
3114             "    baz)\n"
3115             "{\n"
3116             "  quux();\n"
3117             "}",
3118             format("if (foo && bar &&\n"
3119                    "    baz) {\n"
3120                    "  quux();\n"
3121                    "}",
3122                    Style));
3123   EXPECT_EQ("if (foo) {\n"
3124             "  bar();\n"
3125             "} else if (baz ||\n"
3126             "           quux)\n"
3127             "{\n"
3128             "  foobar();\n"
3129             "}",
3130             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
3131   EXPECT_EQ(
3132       "if (foo) {\n"
3133       "  bar();\n"
3134       "} else if (baz ||\n"
3135       "           quux)\n"
3136       "{\n"
3137       "  foobar();\n"
3138       "} else {\n"
3139       "  barbaz();\n"
3140       "}",
3141       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3142              Style));
3143   EXPECT_EQ("for (int i = 0;\n"
3144             "     i < 10; ++i)\n"
3145             "{\n"
3146             "  foo();\n"
3147             "}",
3148             format("for(int i=0;i<10;++i){foo();}", Style));
3149   EXPECT_EQ("foreach (int i,\n"
3150             "         list)\n"
3151             "{\n"
3152             "  foo();\n"
3153             "}",
3154             format("foreach(int i, list){foo();}", Style));
3155   Style.ColumnLimit =
3156       40; // to concentrate at brace wrapping, not line wrap due to column limit
3157   EXPECT_EQ("foreach (int i, list) {\n"
3158             "  foo();\n"
3159             "}",
3160             format("foreach(int i, list){foo();}", Style));
3161   Style.ColumnLimit =
3162       20; // to concentrate at brace wrapping, not line wrap due to column limit
3163   EXPECT_EQ("while (foo || bar ||\n"
3164             "       baz)\n"
3165             "{\n"
3166             "  quux();\n"
3167             "}",
3168             format("while(foo||bar||baz){quux();}", Style));
3169   EXPECT_EQ("switch (\n"
3170             "    foo = barbaz)\n"
3171             "{\n"
3172             "case quux:\n"
3173             "  return;\n"
3174             "}",
3175             format("switch(foo=barbaz){case quux:return;}", Style));
3176   EXPECT_EQ("try {\n"
3177             "  foo();\n"
3178             "} catch (\n"
3179             "    Exception &bar)\n"
3180             "{\n"
3181             "  baz();\n"
3182             "}",
3183             format("try{foo();}catch(Exception&bar){baz();}", Style));
3184   Style.ColumnLimit =
3185       40; // to concentrate at brace wrapping, not line wrap due to column limit
3186   EXPECT_EQ("try {\n"
3187             "  foo();\n"
3188             "} catch (Exception &bar) {\n"
3189             "  baz();\n"
3190             "}",
3191             format("try{foo();}catch(Exception&bar){baz();}", Style));
3192   Style.ColumnLimit =
3193       20; // to concentrate at brace wrapping, not line wrap due to column limit
3194 
3195   Style.BraceWrapping.BeforeElse = true;
3196   EXPECT_EQ(
3197       "if (foo) {\n"
3198       "  bar();\n"
3199       "}\n"
3200       "else if (baz ||\n"
3201       "         quux)\n"
3202       "{\n"
3203       "  foobar();\n"
3204       "}\n"
3205       "else {\n"
3206       "  barbaz();\n"
3207       "}",
3208       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
3209              Style));
3210 
3211   Style.BraceWrapping.BeforeCatch = true;
3212   EXPECT_EQ("try {\n"
3213             "  foo();\n"
3214             "}\n"
3215             "catch (...) {\n"
3216             "  baz();\n"
3217             "}",
3218             format("try{foo();}catch(...){baz();}", Style));
3219 
3220   Style.BraceWrapping.AfterFunction = true;
3221   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
3222   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
3223   Style.ColumnLimit = 80;
3224   verifyFormat("void shortfunction() { bar(); }", Style);
3225 
3226   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
3227   verifyFormat("void shortfunction()\n"
3228                "{\n"
3229                "  bar();\n"
3230                "}",
3231                Style);
3232 }
3233 
3234 TEST_F(FormatTest, BeforeWhile) {
3235   FormatStyle Style = getLLVMStyle();
3236   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
3237 
3238   verifyFormat("do {\n"
3239                "  foo();\n"
3240                "} while (1);",
3241                Style);
3242   Style.BraceWrapping.BeforeWhile = true;
3243   verifyFormat("do {\n"
3244                "  foo();\n"
3245                "}\n"
3246                "while (1);",
3247                Style);
3248 }
3249 
3250 //===----------------------------------------------------------------------===//
3251 // Tests for classes, namespaces, etc.
3252 //===----------------------------------------------------------------------===//
3253 
3254 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3255   verifyFormat("class A {};");
3256 }
3257 
3258 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
3259   verifyFormat("class A {\n"
3260                "public:\n"
3261                "public: // comment\n"
3262                "protected:\n"
3263                "private:\n"
3264                "  void f() {}\n"
3265                "};");
3266   verifyFormat("export class A {\n"
3267                "public:\n"
3268                "public: // comment\n"
3269                "protected:\n"
3270                "private:\n"
3271                "  void f() {}\n"
3272                "};");
3273   verifyGoogleFormat("class A {\n"
3274                      " public:\n"
3275                      " protected:\n"
3276                      " private:\n"
3277                      "  void f() {}\n"
3278                      "};");
3279   verifyGoogleFormat("export class A {\n"
3280                      " public:\n"
3281                      " protected:\n"
3282                      " private:\n"
3283                      "  void f() {}\n"
3284                      "};");
3285   verifyFormat("class A {\n"
3286                "public slots:\n"
3287                "  void f1() {}\n"
3288                "public Q_SLOTS:\n"
3289                "  void f2() {}\n"
3290                "protected slots:\n"
3291                "  void f3() {}\n"
3292                "protected Q_SLOTS:\n"
3293                "  void f4() {}\n"
3294                "private slots:\n"
3295                "  void f5() {}\n"
3296                "private Q_SLOTS:\n"
3297                "  void f6() {}\n"
3298                "signals:\n"
3299                "  void g1();\n"
3300                "Q_SIGNALS:\n"
3301                "  void g2();\n"
3302                "};");
3303 
3304   // Don't interpret 'signals' the wrong way.
3305   verifyFormat("signals.set();");
3306   verifyFormat("for (Signals signals : f()) {\n}");
3307   verifyFormat("{\n"
3308                "  signals.set(); // This needs indentation.\n"
3309                "}");
3310   verifyFormat("void f() {\n"
3311                "label:\n"
3312                "  signals.baz();\n"
3313                "}");
3314   verifyFormat("private[1];");
3315   verifyFormat("testArray[public] = 1;");
3316   verifyFormat("public();");
3317   verifyFormat("myFunc(public);");
3318   verifyFormat("std::vector<int> testVec = {private};");
3319   verifyFormat("private.p = 1;");
3320   verifyFormat("void function(private...){};");
3321   verifyFormat("if (private && public)\n");
3322   verifyFormat("private &= true;");
3323   verifyFormat("int x = private * public;");
3324   verifyFormat("public *= private;");
3325   verifyFormat("int x = public + private;");
3326   verifyFormat("private++;");
3327   verifyFormat("++private;");
3328   verifyFormat("public += private;");
3329   verifyFormat("public = public - private;");
3330   verifyFormat("public->foo();");
3331   verifyFormat("private--;");
3332   verifyFormat("--private;");
3333   verifyFormat("public -= 1;");
3334   verifyFormat("if (!private && !public)\n");
3335   verifyFormat("public != private;");
3336   verifyFormat("int x = public / private;");
3337   verifyFormat("public /= 2;");
3338   verifyFormat("public = public % 2;");
3339   verifyFormat("public %= 2;");
3340   verifyFormat("if (public < private)\n");
3341   verifyFormat("public << private;");
3342   verifyFormat("public <<= private;");
3343   verifyFormat("if (public > private)\n");
3344   verifyFormat("public >> private;");
3345   verifyFormat("public >>= private;");
3346   verifyFormat("public ^ private;");
3347   verifyFormat("public ^= private;");
3348   verifyFormat("public | private;");
3349   verifyFormat("public |= private;");
3350   verifyFormat("auto x = private ? 1 : 2;");
3351   verifyFormat("if (public == private)\n");
3352   verifyFormat("void foo(public, private)");
3353   verifyFormat("public::foo();");
3354 
3355   verifyFormat("class A {\n"
3356                "public:\n"
3357                "  std::unique_ptr<int *[]> b() { return nullptr; }\n"
3358                "\n"
3359                "private:\n"
3360                "  int c;\n"
3361                "};");
3362 }
3363 
3364 TEST_F(FormatTest, SeparatesLogicalBlocks) {
3365   EXPECT_EQ("class A {\n"
3366             "public:\n"
3367             "  void f();\n"
3368             "\n"
3369             "private:\n"
3370             "  void g() {}\n"
3371             "  // test\n"
3372             "protected:\n"
3373             "  int h;\n"
3374             "};",
3375             format("class A {\n"
3376                    "public:\n"
3377                    "void f();\n"
3378                    "private:\n"
3379                    "void g() {}\n"
3380                    "// test\n"
3381                    "protected:\n"
3382                    "int h;\n"
3383                    "};"));
3384   EXPECT_EQ("class A {\n"
3385             "protected:\n"
3386             "public:\n"
3387             "  void f();\n"
3388             "};",
3389             format("class A {\n"
3390                    "protected:\n"
3391                    "\n"
3392                    "public:\n"
3393                    "\n"
3394                    "  void f();\n"
3395                    "};"));
3396 
3397   // Even ensure proper spacing inside macros.
3398   EXPECT_EQ("#define B     \\\n"
3399             "  class A {   \\\n"
3400             "   protected: \\\n"
3401             "   public:    \\\n"
3402             "    void f(); \\\n"
3403             "  };",
3404             format("#define B     \\\n"
3405                    "  class A {   \\\n"
3406                    "   protected: \\\n"
3407                    "              \\\n"
3408                    "   public:    \\\n"
3409                    "              \\\n"
3410                    "    void f(); \\\n"
3411                    "  };",
3412                    getGoogleStyle()));
3413   // But don't remove empty lines after macros ending in access specifiers.
3414   EXPECT_EQ("#define A private:\n"
3415             "\n"
3416             "int i;",
3417             format("#define A         private:\n"
3418                    "\n"
3419                    "int              i;"));
3420 }
3421 
3422 TEST_F(FormatTest, FormatsClasses) {
3423   verifyFormat("class A : public B {};");
3424   verifyFormat("class A : public ::B {};");
3425 
3426   verifyFormat(
3427       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3428       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3429   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3430                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3431                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3432   verifyFormat(
3433       "class A : public B, public C, public D, public E, public F {};");
3434   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3435                "                     public C,\n"
3436                "                     public D,\n"
3437                "                     public E,\n"
3438                "                     public F,\n"
3439                "                     public G {};");
3440 
3441   verifyFormat("class\n"
3442                "    ReallyReallyLongClassName {\n"
3443                "  int i;\n"
3444                "};",
3445                getLLVMStyleWithColumns(32));
3446   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3447                "                           aaaaaaaaaaaaaaaa> {};");
3448   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3449                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3450                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3451   verifyFormat("template <class R, class C>\n"
3452                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3453                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3454   verifyFormat("class ::A::B {};");
3455 }
3456 
3457 TEST_F(FormatTest, BreakInheritanceStyle) {
3458   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3459   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3460       FormatStyle::BILS_BeforeComma;
3461   verifyFormat("class MyClass : public X {};",
3462                StyleWithInheritanceBreakBeforeComma);
3463   verifyFormat("class MyClass\n"
3464                "    : public X\n"
3465                "    , public Y {};",
3466                StyleWithInheritanceBreakBeforeComma);
3467   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3468                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3469                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3470                StyleWithInheritanceBreakBeforeComma);
3471   verifyFormat("struct aaaaaaaaaaaaa\n"
3472                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3473                "          aaaaaaaaaaaaaaaa> {};",
3474                StyleWithInheritanceBreakBeforeComma);
3475 
3476   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3477   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3478       FormatStyle::BILS_AfterColon;
3479   verifyFormat("class MyClass : public X {};",
3480                StyleWithInheritanceBreakAfterColon);
3481   verifyFormat("class MyClass : public X, public Y {};",
3482                StyleWithInheritanceBreakAfterColon);
3483   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3484                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3485                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3486                StyleWithInheritanceBreakAfterColon);
3487   verifyFormat("struct aaaaaaaaaaaaa :\n"
3488                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3489                "        aaaaaaaaaaaaaaaa> {};",
3490                StyleWithInheritanceBreakAfterColon);
3491 
3492   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3493   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3494       FormatStyle::BILS_AfterComma;
3495   verifyFormat("class MyClass : public X {};",
3496                StyleWithInheritanceBreakAfterComma);
3497   verifyFormat("class MyClass : public X,\n"
3498                "                public Y {};",
3499                StyleWithInheritanceBreakAfterComma);
3500   verifyFormat(
3501       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3502       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3503       "{};",
3504       StyleWithInheritanceBreakAfterComma);
3505   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3506                "                           aaaaaaaaaaaaaaaa> {};",
3507                StyleWithInheritanceBreakAfterComma);
3508   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3509                "    : public OnceBreak,\n"
3510                "      public AlwaysBreak,\n"
3511                "      EvenBasesFitInOneLine {};",
3512                StyleWithInheritanceBreakAfterComma);
3513 }
3514 
3515 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) {
3516   verifyFormat("class A {\n} a, b;");
3517   verifyFormat("struct A {\n} a, b;");
3518   verifyFormat("union A {\n} a, b;");
3519 
3520   verifyFormat("constexpr class A {\n} a, b;");
3521   verifyFormat("constexpr struct A {\n} a, b;");
3522   verifyFormat("constexpr union A {\n} a, b;");
3523 
3524   verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace");
3525   verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace");
3526   verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace");
3527 
3528   verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace");
3529   verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace");
3530   verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace");
3531 
3532   verifyFormat("namespace ns {\n"
3533                "class {\n"
3534                "} a, b;\n"
3535                "} // namespace ns");
3536   verifyFormat("namespace ns {\n"
3537                "const class {\n"
3538                "} a, b;\n"
3539                "} // namespace ns");
3540   verifyFormat("namespace ns {\n"
3541                "constexpr class C {\n"
3542                "} a, b;\n"
3543                "} // namespace ns");
3544   verifyFormat("namespace ns {\n"
3545                "class { /* comment */\n"
3546                "} a, b;\n"
3547                "} // namespace ns");
3548   verifyFormat("namespace ns {\n"
3549                "const class { /* comment */\n"
3550                "} a, b;\n"
3551                "} // namespace ns");
3552 }
3553 
3554 TEST_F(FormatTest, FormatsEnum) {
3555   verifyFormat("enum {\n"
3556                "  Zero,\n"
3557                "  One = 1,\n"
3558                "  Two = One + 1,\n"
3559                "  Three = (One + Two),\n"
3560                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3561                "  Five = (One, Two, Three, Four, 5)\n"
3562                "};");
3563   verifyGoogleFormat("enum {\n"
3564                      "  Zero,\n"
3565                      "  One = 1,\n"
3566                      "  Two = One + 1,\n"
3567                      "  Three = (One + Two),\n"
3568                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3569                      "  Five = (One, Two, Three, Four, 5)\n"
3570                      "};");
3571   verifyFormat("enum Enum {};");
3572   verifyFormat("enum {};");
3573   verifyFormat("enum X E {} d;");
3574   verifyFormat("enum __attribute__((...)) E {} d;");
3575   verifyFormat("enum __declspec__((...)) E {} d;");
3576   verifyFormat("enum [[nodiscard]] E {} d;");
3577   verifyFormat("enum {\n"
3578                "  Bar = Foo<int, int>::value\n"
3579                "};",
3580                getLLVMStyleWithColumns(30));
3581 
3582   verifyFormat("enum ShortEnum { A, B, C };");
3583   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3584 
3585   EXPECT_EQ("enum KeepEmptyLines {\n"
3586             "  ONE,\n"
3587             "\n"
3588             "  TWO,\n"
3589             "\n"
3590             "  THREE\n"
3591             "}",
3592             format("enum KeepEmptyLines {\n"
3593                    "  ONE,\n"
3594                    "\n"
3595                    "  TWO,\n"
3596                    "\n"
3597                    "\n"
3598                    "  THREE\n"
3599                    "}"));
3600   verifyFormat("enum E { // comment\n"
3601                "  ONE,\n"
3602                "  TWO\n"
3603                "};\n"
3604                "int i;");
3605 
3606   FormatStyle EightIndent = getLLVMStyle();
3607   EightIndent.IndentWidth = 8;
3608   verifyFormat("enum {\n"
3609                "        VOID,\n"
3610                "        CHAR,\n"
3611                "        SHORT,\n"
3612                "        INT,\n"
3613                "        LONG,\n"
3614                "        SIGNED,\n"
3615                "        UNSIGNED,\n"
3616                "        BOOL,\n"
3617                "        FLOAT,\n"
3618                "        DOUBLE,\n"
3619                "        COMPLEX\n"
3620                "};",
3621                EightIndent);
3622 
3623   verifyFormat("enum [[nodiscard]] E {\n"
3624                "  ONE,\n"
3625                "  TWO,\n"
3626                "};");
3627   verifyFormat("enum [[nodiscard]] E {\n"
3628                "  // Comment 1\n"
3629                "  ONE,\n"
3630                "  // Comment 2\n"
3631                "  TWO,\n"
3632                "};");
3633 
3634   // Not enums.
3635   verifyFormat("enum X f() {\n"
3636                "  a();\n"
3637                "  return 42;\n"
3638                "}");
3639   verifyFormat("enum X Type::f() {\n"
3640                "  a();\n"
3641                "  return 42;\n"
3642                "}");
3643   verifyFormat("enum ::X f() {\n"
3644                "  a();\n"
3645                "  return 42;\n"
3646                "}");
3647   verifyFormat("enum ns::X f() {\n"
3648                "  a();\n"
3649                "  return 42;\n"
3650                "}");
3651 }
3652 
3653 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3654   verifyFormat("enum Type {\n"
3655                "  One = 0; // These semicolons should be commas.\n"
3656                "  Two = 1;\n"
3657                "};");
3658   verifyFormat("namespace n {\n"
3659                "enum Type {\n"
3660                "  One,\n"
3661                "  Two, // missing };\n"
3662                "  int i;\n"
3663                "}\n"
3664                "void g() {}");
3665 }
3666 
3667 TEST_F(FormatTest, FormatsEnumStruct) {
3668   verifyFormat("enum struct {\n"
3669                "  Zero,\n"
3670                "  One = 1,\n"
3671                "  Two = One + 1,\n"
3672                "  Three = (One + Two),\n"
3673                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3674                "  Five = (One, Two, Three, Four, 5)\n"
3675                "};");
3676   verifyFormat("enum struct Enum {};");
3677   verifyFormat("enum struct {};");
3678   verifyFormat("enum struct X E {} d;");
3679   verifyFormat("enum struct __attribute__((...)) E {} d;");
3680   verifyFormat("enum struct __declspec__((...)) E {} d;");
3681   verifyFormat("enum struct [[nodiscard]] E {} d;");
3682   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3683 
3684   verifyFormat("enum struct [[nodiscard]] E {\n"
3685                "  ONE,\n"
3686                "  TWO,\n"
3687                "};");
3688   verifyFormat("enum struct [[nodiscard]] E {\n"
3689                "  // Comment 1\n"
3690                "  ONE,\n"
3691                "  // Comment 2\n"
3692                "  TWO,\n"
3693                "};");
3694 }
3695 
3696 TEST_F(FormatTest, FormatsEnumClass) {
3697   verifyFormat("enum class {\n"
3698                "  Zero,\n"
3699                "  One = 1,\n"
3700                "  Two = One + 1,\n"
3701                "  Three = (One + Two),\n"
3702                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3703                "  Five = (One, Two, Three, Four, 5)\n"
3704                "};");
3705   verifyFormat("enum class Enum {};");
3706   verifyFormat("enum class {};");
3707   verifyFormat("enum class X E {} d;");
3708   verifyFormat("enum class __attribute__((...)) E {} d;");
3709   verifyFormat("enum class __declspec__((...)) E {} d;");
3710   verifyFormat("enum class [[nodiscard]] E {} d;");
3711   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3712 
3713   verifyFormat("enum class [[nodiscard]] E {\n"
3714                "  ONE,\n"
3715                "  TWO,\n"
3716                "};");
3717   verifyFormat("enum class [[nodiscard]] E {\n"
3718                "  // Comment 1\n"
3719                "  ONE,\n"
3720                "  // Comment 2\n"
3721                "  TWO,\n"
3722                "};");
3723 }
3724 
3725 TEST_F(FormatTest, FormatsEnumTypes) {
3726   verifyFormat("enum X : int {\n"
3727                "  A, // Force multiple lines.\n"
3728                "  B\n"
3729                "};");
3730   verifyFormat("enum X : int { A, B };");
3731   verifyFormat("enum X : std::uint32_t { A, B };");
3732 }
3733 
3734 TEST_F(FormatTest, FormatsTypedefEnum) {
3735   FormatStyle Style = getLLVMStyleWithColumns(40);
3736   verifyFormat("typedef enum {} EmptyEnum;");
3737   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3738   verifyFormat("typedef enum {\n"
3739                "  ZERO = 0,\n"
3740                "  ONE = 1,\n"
3741                "  TWO = 2,\n"
3742                "  THREE = 3\n"
3743                "} LongEnum;",
3744                Style);
3745   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3746   Style.BraceWrapping.AfterEnum = true;
3747   verifyFormat("typedef enum {} EmptyEnum;");
3748   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3749   verifyFormat("typedef enum\n"
3750                "{\n"
3751                "  ZERO = 0,\n"
3752                "  ONE = 1,\n"
3753                "  TWO = 2,\n"
3754                "  THREE = 3\n"
3755                "} LongEnum;",
3756                Style);
3757 }
3758 
3759 TEST_F(FormatTest, FormatsNSEnums) {
3760   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3761   verifyGoogleFormat(
3762       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3763   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3764                      "  // Information about someDecentlyLongValue.\n"
3765                      "  someDecentlyLongValue,\n"
3766                      "  // Information about anotherDecentlyLongValue.\n"
3767                      "  anotherDecentlyLongValue,\n"
3768                      "  // Information about aThirdDecentlyLongValue.\n"
3769                      "  aThirdDecentlyLongValue\n"
3770                      "};");
3771   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3772                      "  // Information about someDecentlyLongValue.\n"
3773                      "  someDecentlyLongValue,\n"
3774                      "  // Information about anotherDecentlyLongValue.\n"
3775                      "  anotherDecentlyLongValue,\n"
3776                      "  // Information about aThirdDecentlyLongValue.\n"
3777                      "  aThirdDecentlyLongValue\n"
3778                      "};");
3779   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3780                      "  a = 1,\n"
3781                      "  b = 2,\n"
3782                      "  c = 3,\n"
3783                      "};");
3784   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3785                      "  a = 1,\n"
3786                      "  b = 2,\n"
3787                      "  c = 3,\n"
3788                      "};");
3789   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3790                      "  a = 1,\n"
3791                      "  b = 2,\n"
3792                      "  c = 3,\n"
3793                      "};");
3794   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3795                      "  a = 1,\n"
3796                      "  b = 2,\n"
3797                      "  c = 3,\n"
3798                      "};");
3799 }
3800 
3801 TEST_F(FormatTest, FormatsBitfields) {
3802   verifyFormat("struct Bitfields {\n"
3803                "  unsigned sClass : 8;\n"
3804                "  unsigned ValueKind : 2;\n"
3805                "};");
3806   verifyFormat("struct A {\n"
3807                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3808                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3809                "};");
3810   verifyFormat("struct MyStruct {\n"
3811                "  uchar data;\n"
3812                "  uchar : 8;\n"
3813                "  uchar : 8;\n"
3814                "  uchar other;\n"
3815                "};");
3816   FormatStyle Style = getLLVMStyle();
3817   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3818   verifyFormat("struct Bitfields {\n"
3819                "  unsigned sClass:8;\n"
3820                "  unsigned ValueKind:2;\n"
3821                "  uchar other;\n"
3822                "};",
3823                Style);
3824   verifyFormat("struct A {\n"
3825                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3826                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3827                "};",
3828                Style);
3829   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3830   verifyFormat("struct Bitfields {\n"
3831                "  unsigned sClass :8;\n"
3832                "  unsigned ValueKind :2;\n"
3833                "  uchar other;\n"
3834                "};",
3835                Style);
3836   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3837   verifyFormat("struct Bitfields {\n"
3838                "  unsigned sClass: 8;\n"
3839                "  unsigned ValueKind: 2;\n"
3840                "  uchar other;\n"
3841                "};",
3842                Style);
3843 }
3844 
3845 TEST_F(FormatTest, FormatsNamespaces) {
3846   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3847   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3848 
3849   verifyFormat("namespace some_namespace {\n"
3850                "class A {};\n"
3851                "void f() { f(); }\n"
3852                "}",
3853                LLVMWithNoNamespaceFix);
3854   verifyFormat("#define M(x) x##x\n"
3855                "namespace M(x) {\n"
3856                "class A {};\n"
3857                "void f() { f(); }\n"
3858                "}",
3859                LLVMWithNoNamespaceFix);
3860   verifyFormat("#define M(x) x##x\n"
3861                "namespace N::inline M(x) {\n"
3862                "class A {};\n"
3863                "void f() { f(); }\n"
3864                "}",
3865                LLVMWithNoNamespaceFix);
3866   verifyFormat("#define M(x) x##x\n"
3867                "namespace M(x)::inline N {\n"
3868                "class A {};\n"
3869                "void f() { f(); }\n"
3870                "}",
3871                LLVMWithNoNamespaceFix);
3872   verifyFormat("#define M(x) x##x\n"
3873                "namespace N::M(x) {\n"
3874                "class A {};\n"
3875                "void f() { f(); }\n"
3876                "}",
3877                LLVMWithNoNamespaceFix);
3878   verifyFormat("#define M(x) x##x\n"
3879                "namespace M::N(x) {\n"
3880                "class A {};\n"
3881                "void f() { f(); }\n"
3882                "}",
3883                LLVMWithNoNamespaceFix);
3884   verifyFormat("namespace N::inline D {\n"
3885                "class A {};\n"
3886                "void f() { f(); }\n"
3887                "}",
3888                LLVMWithNoNamespaceFix);
3889   verifyFormat("namespace N::inline D::E {\n"
3890                "class A {};\n"
3891                "void f() { f(); }\n"
3892                "}",
3893                LLVMWithNoNamespaceFix);
3894   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3895                "class A {};\n"
3896                "void f() { f(); }\n"
3897                "}",
3898                LLVMWithNoNamespaceFix);
3899   verifyFormat("/* something */ namespace some_namespace {\n"
3900                "class A {};\n"
3901                "void f() { f(); }\n"
3902                "}",
3903                LLVMWithNoNamespaceFix);
3904   verifyFormat("namespace {\n"
3905                "class A {};\n"
3906                "void f() { f(); }\n"
3907                "}",
3908                LLVMWithNoNamespaceFix);
3909   verifyFormat("/* something */ namespace {\n"
3910                "class A {};\n"
3911                "void f() { f(); }\n"
3912                "}",
3913                LLVMWithNoNamespaceFix);
3914   verifyFormat("inline namespace X {\n"
3915                "class A {};\n"
3916                "void f() { f(); }\n"
3917                "}",
3918                LLVMWithNoNamespaceFix);
3919   verifyFormat("/* something */ inline namespace X {\n"
3920                "class A {};\n"
3921                "void f() { f(); }\n"
3922                "}",
3923                LLVMWithNoNamespaceFix);
3924   verifyFormat("export namespace X {\n"
3925                "class A {};\n"
3926                "void f() { f(); }\n"
3927                "}",
3928                LLVMWithNoNamespaceFix);
3929   verifyFormat("using namespace some_namespace;\n"
3930                "class A {};\n"
3931                "void f() { f(); }",
3932                LLVMWithNoNamespaceFix);
3933 
3934   // This code is more common than we thought; if we
3935   // layout this correctly the semicolon will go into
3936   // its own line, which is undesirable.
3937   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3938   verifyFormat("namespace {\n"
3939                "class A {};\n"
3940                "};",
3941                LLVMWithNoNamespaceFix);
3942 
3943   verifyFormat("namespace {\n"
3944                "int SomeVariable = 0; // comment\n"
3945                "} // namespace",
3946                LLVMWithNoNamespaceFix);
3947   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3948             "#define HEADER_GUARD\n"
3949             "namespace my_namespace {\n"
3950             "int i;\n"
3951             "} // my_namespace\n"
3952             "#endif // HEADER_GUARD",
3953             format("#ifndef HEADER_GUARD\n"
3954                    " #define HEADER_GUARD\n"
3955                    "   namespace my_namespace {\n"
3956                    "int i;\n"
3957                    "}    // my_namespace\n"
3958                    "#endif    // HEADER_GUARD",
3959                    LLVMWithNoNamespaceFix));
3960 
3961   EXPECT_EQ("namespace A::B {\n"
3962             "class C {};\n"
3963             "}",
3964             format("namespace A::B {\n"
3965                    "class C {};\n"
3966                    "}",
3967                    LLVMWithNoNamespaceFix));
3968 
3969   FormatStyle Style = getLLVMStyle();
3970   Style.NamespaceIndentation = FormatStyle::NI_All;
3971   EXPECT_EQ("namespace out {\n"
3972             "  int i;\n"
3973             "  namespace in {\n"
3974             "    int i;\n"
3975             "  } // namespace in\n"
3976             "} // namespace out",
3977             format("namespace out {\n"
3978                    "int i;\n"
3979                    "namespace in {\n"
3980                    "int i;\n"
3981                    "} // namespace in\n"
3982                    "} // namespace out",
3983                    Style));
3984 
3985   FormatStyle ShortInlineFunctions = getLLVMStyle();
3986   ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
3987   ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
3988       FormatStyle::SFS_Inline;
3989   verifyFormat("namespace {\n"
3990                "  void f() {\n"
3991                "    return;\n"
3992                "  }\n"
3993                "} // namespace\n",
3994                ShortInlineFunctions);
3995   verifyFormat("namespace { /* comment */\n"
3996                "  void f() {\n"
3997                "    return;\n"
3998                "  }\n"
3999                "} // namespace\n",
4000                ShortInlineFunctions);
4001   verifyFormat("namespace { // comment\n"
4002                "  void f() {\n"
4003                "    return;\n"
4004                "  }\n"
4005                "} // namespace\n",
4006                ShortInlineFunctions);
4007   verifyFormat("namespace {\n"
4008                "  int some_int;\n"
4009                "  void f() {\n"
4010                "    return;\n"
4011                "  }\n"
4012                "} // namespace\n",
4013                ShortInlineFunctions);
4014   verifyFormat("namespace interface {\n"
4015                "  void f() {\n"
4016                "    return;\n"
4017                "  }\n"
4018                "} // namespace interface\n",
4019                ShortInlineFunctions);
4020   verifyFormat("namespace {\n"
4021                "  class X {\n"
4022                "    void f() { return; }\n"
4023                "  };\n"
4024                "} // namespace\n",
4025                ShortInlineFunctions);
4026   verifyFormat("namespace {\n"
4027                "  class X { /* comment */\n"
4028                "    void f() { return; }\n"
4029                "  };\n"
4030                "} // namespace\n",
4031                ShortInlineFunctions);
4032   verifyFormat("namespace {\n"
4033                "  class X { // comment\n"
4034                "    void f() { return; }\n"
4035                "  };\n"
4036                "} // namespace\n",
4037                ShortInlineFunctions);
4038   verifyFormat("namespace {\n"
4039                "  struct X {\n"
4040                "    void f() { return; }\n"
4041                "  };\n"
4042                "} // namespace\n",
4043                ShortInlineFunctions);
4044   verifyFormat("namespace {\n"
4045                "  union X {\n"
4046                "    void f() { return; }\n"
4047                "  };\n"
4048                "} // namespace\n",
4049                ShortInlineFunctions);
4050   verifyFormat("extern \"C\" {\n"
4051                "void f() {\n"
4052                "  return;\n"
4053                "}\n"
4054                "} // namespace\n",
4055                ShortInlineFunctions);
4056   verifyFormat("namespace {\n"
4057                "  class X {\n"
4058                "    void f() { return; }\n"
4059                "  } x;\n"
4060                "} // namespace\n",
4061                ShortInlineFunctions);
4062   verifyFormat("namespace {\n"
4063                "  [[nodiscard]] class X {\n"
4064                "    void f() { return; }\n"
4065                "  };\n"
4066                "} // namespace\n",
4067                ShortInlineFunctions);
4068   verifyFormat("namespace {\n"
4069                "  static class X {\n"
4070                "    void f() { return; }\n"
4071                "  } x;\n"
4072                "} // namespace\n",
4073                ShortInlineFunctions);
4074   verifyFormat("namespace {\n"
4075                "  constexpr class X {\n"
4076                "    void f() { return; }\n"
4077                "  } x;\n"
4078                "} // namespace\n",
4079                ShortInlineFunctions);
4080 
4081   ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent;
4082   verifyFormat("extern \"C\" {\n"
4083                "  void f() {\n"
4084                "    return;\n"
4085                "  }\n"
4086                "} // namespace\n",
4087                ShortInlineFunctions);
4088 
4089   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4090   EXPECT_EQ("namespace out {\n"
4091             "int i;\n"
4092             "namespace in {\n"
4093             "  int i;\n"
4094             "} // namespace in\n"
4095             "} // namespace out",
4096             format("namespace out {\n"
4097                    "int i;\n"
4098                    "namespace in {\n"
4099                    "int i;\n"
4100                    "} // namespace in\n"
4101                    "} // namespace out",
4102                    Style));
4103 
4104   Style.NamespaceIndentation = FormatStyle::NI_None;
4105   verifyFormat("template <class T>\n"
4106                "concept a_concept = X<>;\n"
4107                "namespace B {\n"
4108                "struct b_struct {};\n"
4109                "} // namespace B\n",
4110                Style);
4111   verifyFormat("template <int I>\n"
4112                "constexpr void foo()\n"
4113                "  requires(I == 42)\n"
4114                "{}\n"
4115                "namespace ns {\n"
4116                "void foo() {}\n"
4117                "} // namespace ns\n",
4118                Style);
4119 }
4120 
4121 TEST_F(FormatTest, NamespaceMacros) {
4122   FormatStyle Style = getLLVMStyle();
4123   Style.NamespaceMacros.push_back("TESTSUITE");
4124 
4125   verifyFormat("TESTSUITE(A) {\n"
4126                "int foo();\n"
4127                "} // TESTSUITE(A)",
4128                Style);
4129 
4130   verifyFormat("TESTSUITE(A, B) {\n"
4131                "int foo();\n"
4132                "} // TESTSUITE(A)",
4133                Style);
4134 
4135   // Properly indent according to NamespaceIndentation style
4136   Style.NamespaceIndentation = FormatStyle::NI_All;
4137   verifyFormat("TESTSUITE(A) {\n"
4138                "  int foo();\n"
4139                "} // TESTSUITE(A)",
4140                Style);
4141   verifyFormat("TESTSUITE(A) {\n"
4142                "  namespace B {\n"
4143                "    int foo();\n"
4144                "  } // namespace B\n"
4145                "} // TESTSUITE(A)",
4146                Style);
4147   verifyFormat("namespace A {\n"
4148                "  TESTSUITE(B) {\n"
4149                "    int foo();\n"
4150                "  } // TESTSUITE(B)\n"
4151                "} // namespace A",
4152                Style);
4153 
4154   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4155   verifyFormat("TESTSUITE(A) {\n"
4156                "TESTSUITE(B) {\n"
4157                "  int foo();\n"
4158                "} // TESTSUITE(B)\n"
4159                "} // TESTSUITE(A)",
4160                Style);
4161   verifyFormat("TESTSUITE(A) {\n"
4162                "namespace B {\n"
4163                "  int foo();\n"
4164                "} // namespace B\n"
4165                "} // TESTSUITE(A)",
4166                Style);
4167   verifyFormat("namespace A {\n"
4168                "TESTSUITE(B) {\n"
4169                "  int foo();\n"
4170                "} // TESTSUITE(B)\n"
4171                "} // namespace A",
4172                Style);
4173 
4174   // Properly merge namespace-macros blocks in CompactNamespaces mode
4175   Style.NamespaceIndentation = FormatStyle::NI_None;
4176   Style.CompactNamespaces = true;
4177   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
4178                "}} // TESTSUITE(A::B)",
4179                Style);
4180 
4181   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4182             "}} // TESTSUITE(out::in)",
4183             format("TESTSUITE(out) {\n"
4184                    "TESTSUITE(in) {\n"
4185                    "} // TESTSUITE(in)\n"
4186                    "} // TESTSUITE(out)",
4187                    Style));
4188 
4189   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
4190             "}} // TESTSUITE(out::in)",
4191             format("TESTSUITE(out) {\n"
4192                    "TESTSUITE(in) {\n"
4193                    "} // TESTSUITE(in)\n"
4194                    "} // TESTSUITE(out)",
4195                    Style));
4196 
4197   // Do not merge different namespaces/macros
4198   EXPECT_EQ("namespace out {\n"
4199             "TESTSUITE(in) {\n"
4200             "} // TESTSUITE(in)\n"
4201             "} // namespace out",
4202             format("namespace out {\n"
4203                    "TESTSUITE(in) {\n"
4204                    "} // TESTSUITE(in)\n"
4205                    "} // namespace out",
4206                    Style));
4207   EXPECT_EQ("TESTSUITE(out) {\n"
4208             "namespace in {\n"
4209             "} // namespace in\n"
4210             "} // TESTSUITE(out)",
4211             format("TESTSUITE(out) {\n"
4212                    "namespace in {\n"
4213                    "} // namespace in\n"
4214                    "} // TESTSUITE(out)",
4215                    Style));
4216   Style.NamespaceMacros.push_back("FOOBAR");
4217   EXPECT_EQ("TESTSUITE(out) {\n"
4218             "FOOBAR(in) {\n"
4219             "} // FOOBAR(in)\n"
4220             "} // TESTSUITE(out)",
4221             format("TESTSUITE(out) {\n"
4222                    "FOOBAR(in) {\n"
4223                    "} // FOOBAR(in)\n"
4224                    "} // TESTSUITE(out)",
4225                    Style));
4226 }
4227 
4228 TEST_F(FormatTest, FormatsCompactNamespaces) {
4229   FormatStyle Style = getLLVMStyle();
4230   Style.CompactNamespaces = true;
4231   Style.NamespaceMacros.push_back("TESTSUITE");
4232 
4233   verifyFormat("namespace A { namespace B {\n"
4234                "}} // namespace A::B",
4235                Style);
4236 
4237   EXPECT_EQ("namespace out { namespace in {\n"
4238             "}} // namespace out::in",
4239             format("namespace out {\n"
4240                    "namespace in {\n"
4241                    "} // namespace in\n"
4242                    "} // namespace out",
4243                    Style));
4244 
4245   // Only namespaces which have both consecutive opening and end get compacted
4246   EXPECT_EQ("namespace out {\n"
4247             "namespace in1 {\n"
4248             "} // namespace in1\n"
4249             "namespace in2 {\n"
4250             "} // namespace in2\n"
4251             "} // namespace out",
4252             format("namespace out {\n"
4253                    "namespace in1 {\n"
4254                    "} // namespace in1\n"
4255                    "namespace in2 {\n"
4256                    "} // namespace in2\n"
4257                    "} // namespace out",
4258                    Style));
4259 
4260   EXPECT_EQ("namespace out {\n"
4261             "int i;\n"
4262             "namespace in {\n"
4263             "int j;\n"
4264             "} // namespace in\n"
4265             "int k;\n"
4266             "} // namespace out",
4267             format("namespace out { int i;\n"
4268                    "namespace in { int j; } // namespace in\n"
4269                    "int k; } // namespace out",
4270                    Style));
4271 
4272   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
4273             "}}} // namespace A::B::C\n",
4274             format("namespace A { namespace B {\n"
4275                    "namespace C {\n"
4276                    "}} // namespace B::C\n"
4277                    "} // namespace A\n",
4278                    Style));
4279 
4280   Style.ColumnLimit = 40;
4281   EXPECT_EQ("namespace aaaaaaaaaa {\n"
4282             "namespace bbbbbbbbbb {\n"
4283             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
4284             format("namespace aaaaaaaaaa {\n"
4285                    "namespace bbbbbbbbbb {\n"
4286                    "} // namespace bbbbbbbbbb\n"
4287                    "} // namespace aaaaaaaaaa",
4288                    Style));
4289 
4290   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
4291             "namespace cccccc {\n"
4292             "}}} // namespace aaaaaa::bbbbbb::cccccc",
4293             format("namespace aaaaaa {\n"
4294                    "namespace bbbbbb {\n"
4295                    "namespace cccccc {\n"
4296                    "} // namespace cccccc\n"
4297                    "} // namespace bbbbbb\n"
4298                    "} // namespace aaaaaa",
4299                    Style));
4300   Style.ColumnLimit = 80;
4301 
4302   // Extra semicolon after 'inner' closing brace prevents merging
4303   EXPECT_EQ("namespace out { namespace in {\n"
4304             "}; } // namespace out::in",
4305             format("namespace out {\n"
4306                    "namespace in {\n"
4307                    "}; // namespace in\n"
4308                    "} // namespace out",
4309                    Style));
4310 
4311   // Extra semicolon after 'outer' closing brace is conserved
4312   EXPECT_EQ("namespace out { namespace in {\n"
4313             "}}; // namespace out::in",
4314             format("namespace out {\n"
4315                    "namespace in {\n"
4316                    "} // namespace in\n"
4317                    "}; // namespace out",
4318                    Style));
4319 
4320   Style.NamespaceIndentation = FormatStyle::NI_All;
4321   EXPECT_EQ("namespace out { namespace in {\n"
4322             "  int i;\n"
4323             "}} // namespace out::in",
4324             format("namespace out {\n"
4325                    "namespace in {\n"
4326                    "int i;\n"
4327                    "} // namespace in\n"
4328                    "} // namespace out",
4329                    Style));
4330   EXPECT_EQ("namespace out { namespace mid {\n"
4331             "  namespace in {\n"
4332             "    int j;\n"
4333             "  } // namespace in\n"
4334             "  int k;\n"
4335             "}} // namespace out::mid",
4336             format("namespace out { namespace mid {\n"
4337                    "namespace in { int j; } // namespace in\n"
4338                    "int k; }} // namespace out::mid",
4339                    Style));
4340 
4341   Style.NamespaceIndentation = FormatStyle::NI_Inner;
4342   EXPECT_EQ("namespace out { namespace in {\n"
4343             "  int i;\n"
4344             "}} // namespace out::in",
4345             format("namespace out {\n"
4346                    "namespace in {\n"
4347                    "int i;\n"
4348                    "} // namespace in\n"
4349                    "} // namespace out",
4350                    Style));
4351   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
4352             "  int i;\n"
4353             "}}} // namespace out::mid::in",
4354             format("namespace out {\n"
4355                    "namespace mid {\n"
4356                    "namespace in {\n"
4357                    "int i;\n"
4358                    "} // namespace in\n"
4359                    "} // namespace mid\n"
4360                    "} // namespace out",
4361                    Style));
4362 
4363   Style.CompactNamespaces = true;
4364   Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
4365   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4366   Style.BraceWrapping.BeforeLambdaBody = true;
4367   verifyFormat("namespace out { namespace in {\n"
4368                "}} // namespace out::in",
4369                Style);
4370   EXPECT_EQ("namespace out { namespace in {\n"
4371             "}} // namespace out::in",
4372             format("namespace out {\n"
4373                    "namespace in {\n"
4374                    "} // namespace in\n"
4375                    "} // namespace out",
4376                    Style));
4377 }
4378 
4379 TEST_F(FormatTest, FormatsExternC) {
4380   verifyFormat("extern \"C\" {\nint a;");
4381   verifyFormat("extern \"C\" {}");
4382   verifyFormat("extern \"C\" {\n"
4383                "int foo();\n"
4384                "}");
4385   verifyFormat("extern \"C\" int foo() {}");
4386   verifyFormat("extern \"C\" int foo();");
4387   verifyFormat("extern \"C\" int foo() {\n"
4388                "  int i = 42;\n"
4389                "  return i;\n"
4390                "}");
4391 
4392   FormatStyle Style = getLLVMStyle();
4393   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4394   Style.BraceWrapping.AfterFunction = true;
4395   verifyFormat("extern \"C\" int foo() {}", Style);
4396   verifyFormat("extern \"C\" int foo();", Style);
4397   verifyFormat("extern \"C\" int foo()\n"
4398                "{\n"
4399                "  int i = 42;\n"
4400                "  return i;\n"
4401                "}",
4402                Style);
4403 
4404   Style.BraceWrapping.AfterExternBlock = true;
4405   Style.BraceWrapping.SplitEmptyRecord = false;
4406   verifyFormat("extern \"C\"\n"
4407                "{}",
4408                Style);
4409   verifyFormat("extern \"C\"\n"
4410                "{\n"
4411                "  int foo();\n"
4412                "}",
4413                Style);
4414 }
4415 
4416 TEST_F(FormatTest, IndentExternBlockStyle) {
4417   FormatStyle Style = getLLVMStyle();
4418   Style.IndentWidth = 2;
4419 
4420   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4421   verifyFormat("extern \"C\" { /*9*/\n"
4422                "}",
4423                Style);
4424   verifyFormat("extern \"C\" {\n"
4425                "  int foo10();\n"
4426                "}",
4427                Style);
4428 
4429   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4430   verifyFormat("extern \"C\" { /*11*/\n"
4431                "}",
4432                Style);
4433   verifyFormat("extern \"C\" {\n"
4434                "int foo12();\n"
4435                "}",
4436                Style);
4437 
4438   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4439   Style.BraceWrapping.AfterExternBlock = true;
4440   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4441   verifyFormat("extern \"C\"\n"
4442                "{ /*13*/\n"
4443                "}",
4444                Style);
4445   verifyFormat("extern \"C\"\n{\n"
4446                "  int foo14();\n"
4447                "}",
4448                Style);
4449 
4450   Style.BraceWrapping.AfterExternBlock = false;
4451   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
4452   verifyFormat("extern \"C\" { /*15*/\n"
4453                "}",
4454                Style);
4455   verifyFormat("extern \"C\" {\n"
4456                "int foo16();\n"
4457                "}",
4458                Style);
4459 
4460   Style.BraceWrapping.AfterExternBlock = true;
4461   verifyFormat("extern \"C\"\n"
4462                "{ /*13*/\n"
4463                "}",
4464                Style);
4465   verifyFormat("extern \"C\"\n"
4466                "{\n"
4467                "int foo14();\n"
4468                "}",
4469                Style);
4470 
4471   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
4472   verifyFormat("extern \"C\"\n"
4473                "{ /*13*/\n"
4474                "}",
4475                Style);
4476   verifyFormat("extern \"C\"\n"
4477                "{\n"
4478                "  int foo14();\n"
4479                "}",
4480                Style);
4481 }
4482 
4483 TEST_F(FormatTest, FormatsInlineASM) {
4484   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
4485   verifyFormat("asm(\"nop\" ::: \"memory\");");
4486   verifyFormat(
4487       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
4488       "    \"cpuid\\n\\t\"\n"
4489       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
4490       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
4491       "    : \"a\"(value));");
4492   EXPECT_EQ(
4493       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
4494       "  __asm {\n"
4495       "        mov     edx,[that] // vtable in edx\n"
4496       "        mov     eax,methodIndex\n"
4497       "        call    [edx][eax*4] // stdcall\n"
4498       "  }\n"
4499       "}",
4500       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
4501              "    __asm {\n"
4502              "        mov     edx,[that] // vtable in edx\n"
4503              "        mov     eax,methodIndex\n"
4504              "        call    [edx][eax*4] // stdcall\n"
4505              "    }\n"
4506              "}"));
4507   EXPECT_EQ("_asm {\n"
4508             "  xor eax, eax;\n"
4509             "  cpuid;\n"
4510             "}",
4511             format("_asm {\n"
4512                    "  xor eax, eax;\n"
4513                    "  cpuid;\n"
4514                    "}"));
4515   verifyFormat("void function() {\n"
4516                "  // comment\n"
4517                "  asm(\"\");\n"
4518                "}");
4519   EXPECT_EQ("__asm {\n"
4520             "}\n"
4521             "int i;",
4522             format("__asm   {\n"
4523                    "}\n"
4524                    "int   i;"));
4525 }
4526 
4527 TEST_F(FormatTest, FormatTryCatch) {
4528   verifyFormat("try {\n"
4529                "  throw a * b;\n"
4530                "} catch (int a) {\n"
4531                "  // Do nothing.\n"
4532                "} catch (...) {\n"
4533                "  exit(42);\n"
4534                "}");
4535 
4536   // Function-level try statements.
4537   verifyFormat("int f() try { return 4; } catch (...) {\n"
4538                "  return 5;\n"
4539                "}");
4540   verifyFormat("class A {\n"
4541                "  int a;\n"
4542                "  A() try : a(0) {\n"
4543                "  } catch (...) {\n"
4544                "    throw;\n"
4545                "  }\n"
4546                "};\n");
4547   verifyFormat("class A {\n"
4548                "  int a;\n"
4549                "  A() try : a(0), b{1} {\n"
4550                "  } catch (...) {\n"
4551                "    throw;\n"
4552                "  }\n"
4553                "};\n");
4554   verifyFormat("class A {\n"
4555                "  int a;\n"
4556                "  A() try : a(0), b{1}, c{2} {\n"
4557                "  } catch (...) {\n"
4558                "    throw;\n"
4559                "  }\n"
4560                "};\n");
4561   verifyFormat("class A {\n"
4562                "  int a;\n"
4563                "  A() try : a(0), b{1}, c{2} {\n"
4564                "    { // New scope.\n"
4565                "    }\n"
4566                "  } catch (...) {\n"
4567                "    throw;\n"
4568                "  }\n"
4569                "};\n");
4570 
4571   // Incomplete try-catch blocks.
4572   verifyIncompleteFormat("try {} catch (");
4573 }
4574 
4575 TEST_F(FormatTest, FormatTryAsAVariable) {
4576   verifyFormat("int try;");
4577   verifyFormat("int try, size;");
4578   verifyFormat("try = foo();");
4579   verifyFormat("if (try < size) {\n  return true;\n}");
4580 
4581   verifyFormat("int catch;");
4582   verifyFormat("int catch, size;");
4583   verifyFormat("catch = foo();");
4584   verifyFormat("if (catch < size) {\n  return true;\n}");
4585 
4586   FormatStyle Style = getLLVMStyle();
4587   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4588   Style.BraceWrapping.AfterFunction = true;
4589   Style.BraceWrapping.BeforeCatch = true;
4590   verifyFormat("try {\n"
4591                "  int bar = 1;\n"
4592                "}\n"
4593                "catch (...) {\n"
4594                "  int bar = 1;\n"
4595                "}",
4596                Style);
4597   verifyFormat("#if NO_EX\n"
4598                "try\n"
4599                "#endif\n"
4600                "{\n"
4601                "}\n"
4602                "#if NO_EX\n"
4603                "catch (...) {\n"
4604                "}",
4605                Style);
4606   verifyFormat("try /* abc */ {\n"
4607                "  int bar = 1;\n"
4608                "}\n"
4609                "catch (...) {\n"
4610                "  int bar = 1;\n"
4611                "}",
4612                Style);
4613   verifyFormat("try\n"
4614                "// abc\n"
4615                "{\n"
4616                "  int bar = 1;\n"
4617                "}\n"
4618                "catch (...) {\n"
4619                "  int bar = 1;\n"
4620                "}",
4621                Style);
4622 }
4623 
4624 TEST_F(FormatTest, FormatSEHTryCatch) {
4625   verifyFormat("__try {\n"
4626                "  int a = b * c;\n"
4627                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
4628                "  // Do nothing.\n"
4629                "}");
4630 
4631   verifyFormat("__try {\n"
4632                "  int a = b * c;\n"
4633                "} __finally {\n"
4634                "  // Do nothing.\n"
4635                "}");
4636 
4637   verifyFormat("DEBUG({\n"
4638                "  __try {\n"
4639                "  } __finally {\n"
4640                "  }\n"
4641                "});\n");
4642 }
4643 
4644 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
4645   verifyFormat("try {\n"
4646                "  f();\n"
4647                "} catch {\n"
4648                "  g();\n"
4649                "}");
4650   verifyFormat("try {\n"
4651                "  f();\n"
4652                "} catch (A a) MACRO(x) {\n"
4653                "  g();\n"
4654                "} catch (B b) MACRO(x) {\n"
4655                "  g();\n"
4656                "}");
4657 }
4658 
4659 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
4660   FormatStyle Style = getLLVMStyle();
4661   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
4662                           FormatStyle::BS_WebKit}) {
4663     Style.BreakBeforeBraces = BraceStyle;
4664     verifyFormat("try {\n"
4665                  "  // something\n"
4666                  "} catch (...) {\n"
4667                  "  // something\n"
4668                  "}",
4669                  Style);
4670   }
4671   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4672   verifyFormat("try {\n"
4673                "  // something\n"
4674                "}\n"
4675                "catch (...) {\n"
4676                "  // something\n"
4677                "}",
4678                Style);
4679   verifyFormat("__try {\n"
4680                "  // something\n"
4681                "}\n"
4682                "__finally {\n"
4683                "  // something\n"
4684                "}",
4685                Style);
4686   verifyFormat("@try {\n"
4687                "  // something\n"
4688                "}\n"
4689                "@finally {\n"
4690                "  // something\n"
4691                "}",
4692                Style);
4693   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4694   verifyFormat("try\n"
4695                "{\n"
4696                "  // something\n"
4697                "}\n"
4698                "catch (...)\n"
4699                "{\n"
4700                "  // something\n"
4701                "}",
4702                Style);
4703   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4704   verifyFormat("try\n"
4705                "  {\n"
4706                "  // something white\n"
4707                "  }\n"
4708                "catch (...)\n"
4709                "  {\n"
4710                "  // something white\n"
4711                "  }",
4712                Style);
4713   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4714   verifyFormat("try\n"
4715                "  {\n"
4716                "    // something\n"
4717                "  }\n"
4718                "catch (...)\n"
4719                "  {\n"
4720                "    // something\n"
4721                "  }",
4722                Style);
4723   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4724   Style.BraceWrapping.BeforeCatch = true;
4725   verifyFormat("try {\n"
4726                "  // something\n"
4727                "}\n"
4728                "catch (...) {\n"
4729                "  // something\n"
4730                "}",
4731                Style);
4732 }
4733 
4734 TEST_F(FormatTest, StaticInitializers) {
4735   verifyFormat("static SomeClass SC = {1, 'a'};");
4736 
4737   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4738                "    100000000, "
4739                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4740 
4741   // Here, everything other than the "}" would fit on a line.
4742   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4743                "    10000000000000000000000000};");
4744   EXPECT_EQ("S s = {a,\n"
4745             "\n"
4746             "       b};",
4747             format("S s = {\n"
4748                    "  a,\n"
4749                    "\n"
4750                    "  b\n"
4751                    "};"));
4752 
4753   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4754   // line. However, the formatting looks a bit off and this probably doesn't
4755   // happen often in practice.
4756   verifyFormat("static int Variable[1] = {\n"
4757                "    {1000000000000000000000000000000000000}};",
4758                getLLVMStyleWithColumns(40));
4759 }
4760 
4761 TEST_F(FormatTest, DesignatedInitializers) {
4762   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4763   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4764                "                    .bbbbbbbbbb = 2,\n"
4765                "                    .cccccccccc = 3,\n"
4766                "                    .dddddddddd = 4,\n"
4767                "                    .eeeeeeeeee = 5};");
4768   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4769                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4770                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4771                "    .ccccccccccccccccccccccccccc = 3,\n"
4772                "    .ddddddddddddddddddddddddddd = 4,\n"
4773                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4774 
4775   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4776 
4777   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4778   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4779                "                    [2] = bbbbbbbbbb,\n"
4780                "                    [3] = cccccccccc,\n"
4781                "                    [4] = dddddddddd,\n"
4782                "                    [5] = eeeeeeeeee};");
4783   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4784                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4785                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4786                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4787                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4788                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4789 }
4790 
4791 TEST_F(FormatTest, NestedStaticInitializers) {
4792   verifyFormat("static A x = {{{}}};\n");
4793   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4794                "               {init1, init2, init3, init4}}};",
4795                getLLVMStyleWithColumns(50));
4796 
4797   verifyFormat("somes Status::global_reps[3] = {\n"
4798                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4799                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4800                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4801                getLLVMStyleWithColumns(60));
4802   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4803                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4804                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4805                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4806   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4807                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4808                "rect.fTop}};");
4809 
4810   verifyFormat(
4811       "SomeArrayOfSomeType a = {\n"
4812       "    {{1, 2, 3},\n"
4813       "     {1, 2, 3},\n"
4814       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4815       "      333333333333333333333333333333},\n"
4816       "     {1, 2, 3},\n"
4817       "     {1, 2, 3}}};");
4818   verifyFormat(
4819       "SomeArrayOfSomeType a = {\n"
4820       "    {{1, 2, 3}},\n"
4821       "    {{1, 2, 3}},\n"
4822       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4823       "      333333333333333333333333333333}},\n"
4824       "    {{1, 2, 3}},\n"
4825       "    {{1, 2, 3}}};");
4826 
4827   verifyFormat("struct {\n"
4828                "  unsigned bit;\n"
4829                "  const char *const name;\n"
4830                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4831                "                 {kOsWin, \"Windows\"},\n"
4832                "                 {kOsLinux, \"Linux\"},\n"
4833                "                 {kOsCrOS, \"Chrome OS\"}};");
4834   verifyFormat("struct {\n"
4835                "  unsigned bit;\n"
4836                "  const char *const name;\n"
4837                "} kBitsToOs[] = {\n"
4838                "    {kOsMac, \"Mac\"},\n"
4839                "    {kOsWin, \"Windows\"},\n"
4840                "    {kOsLinux, \"Linux\"},\n"
4841                "    {kOsCrOS, \"Chrome OS\"},\n"
4842                "};");
4843 }
4844 
4845 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4846   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4847                "                      \\\n"
4848                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4849 }
4850 
4851 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4852   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4853                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4854 
4855   // Do break defaulted and deleted functions.
4856   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4857                "    default;",
4858                getLLVMStyleWithColumns(40));
4859   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4860                "    delete;",
4861                getLLVMStyleWithColumns(40));
4862 }
4863 
4864 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4865   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4866                getLLVMStyleWithColumns(40));
4867   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4868                getLLVMStyleWithColumns(40));
4869   EXPECT_EQ("#define Q                              \\\n"
4870             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4871             "  \"aaaaaaaa.cpp\"",
4872             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4873                    getLLVMStyleWithColumns(40)));
4874 }
4875 
4876 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4877   EXPECT_EQ("# 123 \"A string literal\"",
4878             format("   #     123    \"A string literal\""));
4879 }
4880 
4881 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4882   EXPECT_EQ("#;", format("#;"));
4883   verifyFormat("#\n;\n;\n;");
4884 }
4885 
4886 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4887   EXPECT_EQ("#line 42 \"test\"\n",
4888             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4889   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4890                                     getLLVMStyleWithColumns(12)));
4891 }
4892 
4893 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4894   EXPECT_EQ("#line 42 \"test\"",
4895             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4896   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4897 }
4898 
4899 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4900   verifyFormat("#define A \\x20");
4901   verifyFormat("#define A \\ x20");
4902   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4903   verifyFormat("#define A ''");
4904   verifyFormat("#define A ''qqq");
4905   verifyFormat("#define A `qqq");
4906   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4907   EXPECT_EQ("const char *c = STRINGIFY(\n"
4908             "\\na : b);",
4909             format("const char * c = STRINGIFY(\n"
4910                    "\\na : b);"));
4911 
4912   verifyFormat("a\r\\");
4913   verifyFormat("a\v\\");
4914   verifyFormat("a\f\\");
4915 }
4916 
4917 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4918   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4919   style.IndentWidth = 4;
4920   style.PPIndentWidth = 1;
4921 
4922   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4923   verifyFormat("#ifdef __linux__\n"
4924                "void foo() {\n"
4925                "    int x = 0;\n"
4926                "}\n"
4927                "#define FOO\n"
4928                "#endif\n"
4929                "void bar() {\n"
4930                "    int y = 0;\n"
4931                "}\n",
4932                style);
4933 
4934   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4935   verifyFormat("#ifdef __linux__\n"
4936                "void foo() {\n"
4937                "    int x = 0;\n"
4938                "}\n"
4939                "# define FOO foo\n"
4940                "#endif\n"
4941                "void bar() {\n"
4942                "    int y = 0;\n"
4943                "}\n",
4944                style);
4945 
4946   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4947   verifyFormat("#ifdef __linux__\n"
4948                "void foo() {\n"
4949                "    int x = 0;\n"
4950                "}\n"
4951                " #define FOO foo\n"
4952                "#endif\n"
4953                "void bar() {\n"
4954                "    int y = 0;\n"
4955                "}\n",
4956                style);
4957 }
4958 
4959 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4960   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4961   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4962   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4963   // FIXME: We never break before the macro name.
4964   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4965 
4966   verifyFormat("#define A A\n#define A A");
4967   verifyFormat("#define A(X) A\n#define A A");
4968 
4969   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4970   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4971 }
4972 
4973 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4974   EXPECT_EQ("// somecomment\n"
4975             "#include \"a.h\"\n"
4976             "#define A(  \\\n"
4977             "    A, B)\n"
4978             "#include \"b.h\"\n"
4979             "// somecomment\n",
4980             format("  // somecomment\n"
4981                    "  #include \"a.h\"\n"
4982                    "#define A(A,\\\n"
4983                    "    B)\n"
4984                    "    #include \"b.h\"\n"
4985                    " // somecomment\n",
4986                    getLLVMStyleWithColumns(13)));
4987 }
4988 
4989 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4990 
4991 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4992   EXPECT_EQ("#define A    \\\n"
4993             "  c;         \\\n"
4994             "  e;\n"
4995             "f;",
4996             format("#define A c; e;\n"
4997                    "f;",
4998                    getLLVMStyleWithColumns(14)));
4999 }
5000 
5001 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
5002 
5003 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
5004   EXPECT_EQ("int x,\n"
5005             "#define A\n"
5006             "    y;",
5007             format("int x,\n#define A\ny;"));
5008 }
5009 
5010 TEST_F(FormatTest, HashInMacroDefinition) {
5011   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
5012   EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
5013   EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
5014   EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
5015   EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
5016   EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
5017   EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
5018   EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
5019   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
5020   verifyFormat("#define A  \\\n"
5021                "  {        \\\n"
5022                "    f(#c); \\\n"
5023                "  }",
5024                getLLVMStyleWithColumns(11));
5025 
5026   verifyFormat("#define A(X)         \\\n"
5027                "  void function##X()",
5028                getLLVMStyleWithColumns(22));
5029 
5030   verifyFormat("#define A(a, b, c)   \\\n"
5031                "  void a##b##c()",
5032                getLLVMStyleWithColumns(22));
5033 
5034   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
5035 }
5036 
5037 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
5038   EXPECT_EQ("#define A (x)", format("#define A (x)"));
5039   EXPECT_EQ("#define A(x)", format("#define A(x)"));
5040 
5041   FormatStyle Style = getLLVMStyle();
5042   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
5043   verifyFormat("#define true ((foo)1)", Style);
5044   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
5045   verifyFormat("#define false((foo)0)", Style);
5046 }
5047 
5048 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
5049   EXPECT_EQ("#define A b;", format("#define A \\\n"
5050                                    "          \\\n"
5051                                    "  b;",
5052                                    getLLVMStyleWithColumns(25)));
5053   EXPECT_EQ("#define A \\\n"
5054             "          \\\n"
5055             "  a;      \\\n"
5056             "  b;",
5057             format("#define A \\\n"
5058                    "          \\\n"
5059                    "  a;      \\\n"
5060                    "  b;",
5061                    getLLVMStyleWithColumns(11)));
5062   EXPECT_EQ("#define A \\\n"
5063             "  a;      \\\n"
5064             "          \\\n"
5065             "  b;",
5066             format("#define A \\\n"
5067                    "  a;      \\\n"
5068                    "          \\\n"
5069                    "  b;",
5070                    getLLVMStyleWithColumns(11)));
5071 }
5072 
5073 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
5074   verifyIncompleteFormat("#define A :");
5075   verifyFormat("#define SOMECASES  \\\n"
5076                "  case 1:          \\\n"
5077                "  case 2\n",
5078                getLLVMStyleWithColumns(20));
5079   verifyFormat("#define MACRO(a) \\\n"
5080                "  if (a)         \\\n"
5081                "    f();         \\\n"
5082                "  else           \\\n"
5083                "    g()",
5084                getLLVMStyleWithColumns(18));
5085   verifyFormat("#define A template <typename T>");
5086   verifyIncompleteFormat("#define STR(x) #x\n"
5087                          "f(STR(this_is_a_string_literal{));");
5088   verifyFormat("#pragma omp threadprivate( \\\n"
5089                "    y)), // expected-warning",
5090                getLLVMStyleWithColumns(28));
5091   verifyFormat("#d, = };");
5092   verifyFormat("#if \"a");
5093   verifyIncompleteFormat("({\n"
5094                          "#define b     \\\n"
5095                          "  }           \\\n"
5096                          "  a\n"
5097                          "a",
5098                          getLLVMStyleWithColumns(15));
5099   verifyFormat("#define A     \\\n"
5100                "  {           \\\n"
5101                "    {\n"
5102                "#define B     \\\n"
5103                "  }           \\\n"
5104                "  }",
5105                getLLVMStyleWithColumns(15));
5106   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
5107   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
5108   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
5109   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
5110 }
5111 
5112 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
5113   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
5114   EXPECT_EQ("class A : public QObject {\n"
5115             "  Q_OBJECT\n"
5116             "\n"
5117             "  A() {}\n"
5118             "};",
5119             format("class A  :  public QObject {\n"
5120                    "     Q_OBJECT\n"
5121                    "\n"
5122                    "  A() {\n}\n"
5123                    "}  ;"));
5124   EXPECT_EQ("MACRO\n"
5125             "/*static*/ int i;",
5126             format("MACRO\n"
5127                    " /*static*/ int   i;"));
5128   EXPECT_EQ("SOME_MACRO\n"
5129             "namespace {\n"
5130             "void f();\n"
5131             "} // namespace",
5132             format("SOME_MACRO\n"
5133                    "  namespace    {\n"
5134                    "void   f(  );\n"
5135                    "} // namespace"));
5136   // Only if the identifier contains at least 5 characters.
5137   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
5138   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
5139   // Only if everything is upper case.
5140   EXPECT_EQ("class A : public QObject {\n"
5141             "  Q_Object A() {}\n"
5142             "};",
5143             format("class A  :  public QObject {\n"
5144                    "     Q_Object\n"
5145                    "  A() {\n}\n"
5146                    "}  ;"));
5147 
5148   // Only if the next line can actually start an unwrapped line.
5149   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
5150             format("SOME_WEIRD_LOG_MACRO\n"
5151                    "<< SomeThing;"));
5152 
5153   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
5154                "(n, buffers))\n",
5155                getChromiumStyle(FormatStyle::LK_Cpp));
5156 
5157   // See PR41483
5158   EXPECT_EQ("/**/ FOO(a)\n"
5159             "FOO(b)",
5160             format("/**/ FOO(a)\n"
5161                    "FOO(b)"));
5162 }
5163 
5164 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
5165   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5166             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5167             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5168             "class X {};\n"
5169             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5170             "int *createScopDetectionPass() { return 0; }",
5171             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
5172                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
5173                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
5174                    "  class X {};\n"
5175                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
5176                    "  int *createScopDetectionPass() { return 0; }"));
5177   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
5178   // braces, so that inner block is indented one level more.
5179   EXPECT_EQ("int q() {\n"
5180             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5181             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5182             "  IPC_END_MESSAGE_MAP()\n"
5183             "}",
5184             format("int q() {\n"
5185                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
5186                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
5187                    "  IPC_END_MESSAGE_MAP()\n"
5188                    "}"));
5189 
5190   // Same inside macros.
5191   EXPECT_EQ("#define LIST(L) \\\n"
5192             "  L(A)          \\\n"
5193             "  L(B)          \\\n"
5194             "  L(C)",
5195             format("#define LIST(L) \\\n"
5196                    "  L(A) \\\n"
5197                    "  L(B) \\\n"
5198                    "  L(C)",
5199                    getGoogleStyle()));
5200 
5201   // These must not be recognized as macros.
5202   EXPECT_EQ("int q() {\n"
5203             "  f(x);\n"
5204             "  f(x) {}\n"
5205             "  f(x)->g();\n"
5206             "  f(x)->*g();\n"
5207             "  f(x).g();\n"
5208             "  f(x) = x;\n"
5209             "  f(x) += x;\n"
5210             "  f(x) -= x;\n"
5211             "  f(x) *= x;\n"
5212             "  f(x) /= x;\n"
5213             "  f(x) %= x;\n"
5214             "  f(x) &= x;\n"
5215             "  f(x) |= x;\n"
5216             "  f(x) ^= x;\n"
5217             "  f(x) >>= x;\n"
5218             "  f(x) <<= x;\n"
5219             "  f(x)[y].z();\n"
5220             "  LOG(INFO) << x;\n"
5221             "  ifstream(x) >> x;\n"
5222             "}\n",
5223             format("int q() {\n"
5224                    "  f(x)\n;\n"
5225                    "  f(x)\n {}\n"
5226                    "  f(x)\n->g();\n"
5227                    "  f(x)\n->*g();\n"
5228                    "  f(x)\n.g();\n"
5229                    "  f(x)\n = x;\n"
5230                    "  f(x)\n += x;\n"
5231                    "  f(x)\n -= x;\n"
5232                    "  f(x)\n *= x;\n"
5233                    "  f(x)\n /= x;\n"
5234                    "  f(x)\n %= x;\n"
5235                    "  f(x)\n &= x;\n"
5236                    "  f(x)\n |= x;\n"
5237                    "  f(x)\n ^= x;\n"
5238                    "  f(x)\n >>= x;\n"
5239                    "  f(x)\n <<= x;\n"
5240                    "  f(x)\n[y].z();\n"
5241                    "  LOG(INFO)\n << x;\n"
5242                    "  ifstream(x)\n >> x;\n"
5243                    "}\n"));
5244   EXPECT_EQ("int q() {\n"
5245             "  F(x)\n"
5246             "  if (1) {\n"
5247             "  }\n"
5248             "  F(x)\n"
5249             "  while (1) {\n"
5250             "  }\n"
5251             "  F(x)\n"
5252             "  G(x);\n"
5253             "  F(x)\n"
5254             "  try {\n"
5255             "    Q();\n"
5256             "  } catch (...) {\n"
5257             "  }\n"
5258             "}\n",
5259             format("int q() {\n"
5260                    "F(x)\n"
5261                    "if (1) {}\n"
5262                    "F(x)\n"
5263                    "while (1) {}\n"
5264                    "F(x)\n"
5265                    "G(x);\n"
5266                    "F(x)\n"
5267                    "try { Q(); } catch (...) {}\n"
5268                    "}\n"));
5269   EXPECT_EQ("class A {\n"
5270             "  A() : t(0) {}\n"
5271             "  A(int i) noexcept() : {}\n"
5272             "  A(X x)\n" // FIXME: function-level try blocks are broken.
5273             "  try : t(0) {\n"
5274             "  } catch (...) {\n"
5275             "  }\n"
5276             "};",
5277             format("class A {\n"
5278                    "  A()\n : t(0) {}\n"
5279                    "  A(int i)\n noexcept() : {}\n"
5280                    "  A(X x)\n"
5281                    "  try : t(0) {} catch (...) {}\n"
5282                    "};"));
5283   FormatStyle Style = getLLVMStyle();
5284   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
5285   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
5286   Style.BraceWrapping.AfterFunction = true;
5287   EXPECT_EQ("void f()\n"
5288             "try\n"
5289             "{\n"
5290             "}",
5291             format("void f() try {\n"
5292                    "}",
5293                    Style));
5294   EXPECT_EQ("class SomeClass {\n"
5295             "public:\n"
5296             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5297             "};",
5298             format("class SomeClass {\n"
5299                    "public:\n"
5300                    "  SomeClass()\n"
5301                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5302                    "};"));
5303   EXPECT_EQ("class SomeClass {\n"
5304             "public:\n"
5305             "  SomeClass()\n"
5306             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5307             "};",
5308             format("class SomeClass {\n"
5309                    "public:\n"
5310                    "  SomeClass()\n"
5311                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
5312                    "};",
5313                    getLLVMStyleWithColumns(40)));
5314 
5315   verifyFormat("MACRO(>)");
5316 
5317   // Some macros contain an implicit semicolon.
5318   Style = getLLVMStyle();
5319   Style.StatementMacros.push_back("FOO");
5320   verifyFormat("FOO(a) int b = 0;");
5321   verifyFormat("FOO(a)\n"
5322                "int b = 0;",
5323                Style);
5324   verifyFormat("FOO(a);\n"
5325                "int b = 0;",
5326                Style);
5327   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
5328                "int b = 0;",
5329                Style);
5330   verifyFormat("FOO()\n"
5331                "int b = 0;",
5332                Style);
5333   verifyFormat("FOO\n"
5334                "int b = 0;",
5335                Style);
5336   verifyFormat("void f() {\n"
5337                "  FOO(a)\n"
5338                "  return a;\n"
5339                "}",
5340                Style);
5341   verifyFormat("FOO(a)\n"
5342                "FOO(b)",
5343                Style);
5344   verifyFormat("int a = 0;\n"
5345                "FOO(b)\n"
5346                "int c = 0;",
5347                Style);
5348   verifyFormat("int a = 0;\n"
5349                "int x = FOO(a)\n"
5350                "int b = 0;",
5351                Style);
5352   verifyFormat("void foo(int a) { FOO(a) }\n"
5353                "uint32_t bar() {}",
5354                Style);
5355 }
5356 
5357 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
5358   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
5359 
5360   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
5361                ZeroColumn);
5362 }
5363 
5364 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5365   verifyFormat("#define A \\\n"
5366                "  f({     \\\n"
5367                "    g();  \\\n"
5368                "  });",
5369                getLLVMStyleWithColumns(11));
5370 }
5371 
5372 TEST_F(FormatTest, IndentPreprocessorDirectives) {
5373   FormatStyle Style = getLLVMStyleWithColumns(40);
5374   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
5375   verifyFormat("#ifdef _WIN32\n"
5376                "#define A 0\n"
5377                "#ifdef VAR2\n"
5378                "#define B 1\n"
5379                "#include <someheader.h>\n"
5380                "#define MACRO                          \\\n"
5381                "  some_very_long_func_aaaaaaaaaa();\n"
5382                "#endif\n"
5383                "#else\n"
5384                "#define A 1\n"
5385                "#endif",
5386                Style);
5387   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
5388   verifyFormat("#if 1\n"
5389                "#  define __STR(x) #x\n"
5390                "#endif",
5391                Style);
5392   verifyFormat("#ifdef _WIN32\n"
5393                "#  define A 0\n"
5394                "#  ifdef VAR2\n"
5395                "#    define B 1\n"
5396                "#    include <someheader.h>\n"
5397                "#    define MACRO                      \\\n"
5398                "      some_very_long_func_aaaaaaaaaa();\n"
5399                "#  endif\n"
5400                "#else\n"
5401                "#  define A 1\n"
5402                "#endif",
5403                Style);
5404   verifyFormat("#if A\n"
5405                "#  define MACRO                        \\\n"
5406                "    void a(int x) {                    \\\n"
5407                "      b();                             \\\n"
5408                "      c();                             \\\n"
5409                "      d();                             \\\n"
5410                "      e();                             \\\n"
5411                "      f();                             \\\n"
5412                "    }\n"
5413                "#endif",
5414                Style);
5415   // Comments before include guard.
5416   verifyFormat("// file comment\n"
5417                "// file comment\n"
5418                "#ifndef HEADER_H\n"
5419                "#define HEADER_H\n"
5420                "code();\n"
5421                "#endif",
5422                Style);
5423   // Test with include guards.
5424   verifyFormat("#ifndef HEADER_H\n"
5425                "#define HEADER_H\n"
5426                "code();\n"
5427                "#endif",
5428                Style);
5429   // Include guards must have a #define with the same variable immediately
5430   // after #ifndef.
5431   verifyFormat("#ifndef NOT_GUARD\n"
5432                "#  define FOO\n"
5433                "code();\n"
5434                "#endif",
5435                Style);
5436 
5437   // Include guards must cover the entire file.
5438   verifyFormat("code();\n"
5439                "code();\n"
5440                "#ifndef NOT_GUARD\n"
5441                "#  define NOT_GUARD\n"
5442                "code();\n"
5443                "#endif",
5444                Style);
5445   verifyFormat("#ifndef NOT_GUARD\n"
5446                "#  define NOT_GUARD\n"
5447                "code();\n"
5448                "#endif\n"
5449                "code();",
5450                Style);
5451   // Test with trailing blank lines.
5452   verifyFormat("#ifndef HEADER_H\n"
5453                "#define HEADER_H\n"
5454                "code();\n"
5455                "#endif\n",
5456                Style);
5457   // Include guards don't have #else.
5458   verifyFormat("#ifndef NOT_GUARD\n"
5459                "#  define NOT_GUARD\n"
5460                "code();\n"
5461                "#else\n"
5462                "#endif",
5463                Style);
5464   verifyFormat("#ifndef NOT_GUARD\n"
5465                "#  define NOT_GUARD\n"
5466                "code();\n"
5467                "#elif FOO\n"
5468                "#endif",
5469                Style);
5470   // Non-identifier #define after potential include guard.
5471   verifyFormat("#ifndef FOO\n"
5472                "#  define 1\n"
5473                "#endif\n",
5474                Style);
5475   // #if closes past last non-preprocessor line.
5476   verifyFormat("#ifndef FOO\n"
5477                "#define FOO\n"
5478                "#if 1\n"
5479                "int i;\n"
5480                "#  define A 0\n"
5481                "#endif\n"
5482                "#endif\n",
5483                Style);
5484   // Don't crash if there is an #elif directive without a condition.
5485   verifyFormat("#if 1\n"
5486                "int x;\n"
5487                "#elif\n"
5488                "int y;\n"
5489                "#else\n"
5490                "int z;\n"
5491                "#endif",
5492                Style);
5493   // FIXME: This doesn't handle the case where there's code between the
5494   // #ifndef and #define but all other conditions hold. This is because when
5495   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
5496   // previous code line yet, so we can't detect it.
5497   EXPECT_EQ("#ifndef NOT_GUARD\n"
5498             "code();\n"
5499             "#define NOT_GUARD\n"
5500             "code();\n"
5501             "#endif",
5502             format("#ifndef NOT_GUARD\n"
5503                    "code();\n"
5504                    "#  define NOT_GUARD\n"
5505                    "code();\n"
5506                    "#endif",
5507                    Style));
5508   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
5509   // be outside an include guard. Examples are #pragma once and
5510   // #pragma GCC diagnostic, or anything else that does not change the meaning
5511   // of the file if it's included multiple times.
5512   EXPECT_EQ("#ifdef WIN32\n"
5513             "#  pragma once\n"
5514             "#endif\n"
5515             "#ifndef HEADER_H\n"
5516             "#  define HEADER_H\n"
5517             "code();\n"
5518             "#endif",
5519             format("#ifdef WIN32\n"
5520                    "#  pragma once\n"
5521                    "#endif\n"
5522                    "#ifndef HEADER_H\n"
5523                    "#define HEADER_H\n"
5524                    "code();\n"
5525                    "#endif",
5526                    Style));
5527   // FIXME: This does not detect when there is a single non-preprocessor line
5528   // in front of an include-guard-like structure where other conditions hold
5529   // because ScopedLineState hides the line.
5530   EXPECT_EQ("code();\n"
5531             "#ifndef HEADER_H\n"
5532             "#define HEADER_H\n"
5533             "code();\n"
5534             "#endif",
5535             format("code();\n"
5536                    "#ifndef HEADER_H\n"
5537                    "#  define HEADER_H\n"
5538                    "code();\n"
5539                    "#endif",
5540                    Style));
5541   // Keep comments aligned with #, otherwise indent comments normally. These
5542   // tests cannot use verifyFormat because messUp manipulates leading
5543   // whitespace.
5544   {
5545     const char *Expected = ""
5546                            "void f() {\n"
5547                            "#if 1\n"
5548                            "// Preprocessor aligned.\n"
5549                            "#  define A 0\n"
5550                            "  // Code. Separated by blank line.\n"
5551                            "\n"
5552                            "#  define B 0\n"
5553                            "  // Code. Not aligned with #\n"
5554                            "#  define C 0\n"
5555                            "#endif";
5556     const char *ToFormat = ""
5557                            "void f() {\n"
5558                            "#if 1\n"
5559                            "// Preprocessor aligned.\n"
5560                            "#  define A 0\n"
5561                            "// Code. Separated by blank line.\n"
5562                            "\n"
5563                            "#  define B 0\n"
5564                            "   // Code. Not aligned with #\n"
5565                            "#  define C 0\n"
5566                            "#endif";
5567     EXPECT_EQ(Expected, format(ToFormat, Style));
5568     EXPECT_EQ(Expected, format(Expected, Style));
5569   }
5570   // Keep block quotes aligned.
5571   {
5572     const char *Expected = ""
5573                            "void f() {\n"
5574                            "#if 1\n"
5575                            "/* Preprocessor aligned. */\n"
5576                            "#  define A 0\n"
5577                            "  /* Code. Separated by blank line. */\n"
5578                            "\n"
5579                            "#  define B 0\n"
5580                            "  /* Code. Not aligned with # */\n"
5581                            "#  define C 0\n"
5582                            "#endif";
5583     const char *ToFormat = ""
5584                            "void f() {\n"
5585                            "#if 1\n"
5586                            "/* Preprocessor aligned. */\n"
5587                            "#  define A 0\n"
5588                            "/* Code. Separated by blank line. */\n"
5589                            "\n"
5590                            "#  define B 0\n"
5591                            "   /* Code. Not aligned with # */\n"
5592                            "#  define C 0\n"
5593                            "#endif";
5594     EXPECT_EQ(Expected, format(ToFormat, Style));
5595     EXPECT_EQ(Expected, format(Expected, Style));
5596   }
5597   // Keep comments aligned with un-indented directives.
5598   {
5599     const char *Expected = ""
5600                            "void f() {\n"
5601                            "// Preprocessor aligned.\n"
5602                            "#define A 0\n"
5603                            "  // Code. Separated by blank line.\n"
5604                            "\n"
5605                            "#define B 0\n"
5606                            "  // Code. Not aligned with #\n"
5607                            "#define C 0\n";
5608     const char *ToFormat = ""
5609                            "void f() {\n"
5610                            "// Preprocessor aligned.\n"
5611                            "#define A 0\n"
5612                            "// Code. Separated by blank line.\n"
5613                            "\n"
5614                            "#define B 0\n"
5615                            "   // Code. Not aligned with #\n"
5616                            "#define C 0\n";
5617     EXPECT_EQ(Expected, format(ToFormat, Style));
5618     EXPECT_EQ(Expected, format(Expected, Style));
5619   }
5620   // Test AfterHash with tabs.
5621   {
5622     FormatStyle Tabbed = Style;
5623     Tabbed.UseTab = FormatStyle::UT_Always;
5624     Tabbed.IndentWidth = 8;
5625     Tabbed.TabWidth = 8;
5626     verifyFormat("#ifdef _WIN32\n"
5627                  "#\tdefine A 0\n"
5628                  "#\tifdef VAR2\n"
5629                  "#\t\tdefine B 1\n"
5630                  "#\t\tinclude <someheader.h>\n"
5631                  "#\t\tdefine MACRO          \\\n"
5632                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
5633                  "#\tendif\n"
5634                  "#else\n"
5635                  "#\tdefine A 1\n"
5636                  "#endif",
5637                  Tabbed);
5638   }
5639 
5640   // Regression test: Multiline-macro inside include guards.
5641   verifyFormat("#ifndef HEADER_H\n"
5642                "#define HEADER_H\n"
5643                "#define A()        \\\n"
5644                "  int i;           \\\n"
5645                "  int j;\n"
5646                "#endif // HEADER_H",
5647                getLLVMStyleWithColumns(20));
5648 
5649   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
5650   // Basic before hash indent tests
5651   verifyFormat("#ifdef _WIN32\n"
5652                "  #define A 0\n"
5653                "  #ifdef VAR2\n"
5654                "    #define B 1\n"
5655                "    #include <someheader.h>\n"
5656                "    #define MACRO                      \\\n"
5657                "      some_very_long_func_aaaaaaaaaa();\n"
5658                "  #endif\n"
5659                "#else\n"
5660                "  #define A 1\n"
5661                "#endif",
5662                Style);
5663   verifyFormat("#if A\n"
5664                "  #define MACRO                        \\\n"
5665                "    void a(int x) {                    \\\n"
5666                "      b();                             \\\n"
5667                "      c();                             \\\n"
5668                "      d();                             \\\n"
5669                "      e();                             \\\n"
5670                "      f();                             \\\n"
5671                "    }\n"
5672                "#endif",
5673                Style);
5674   // Keep comments aligned with indented directives. These
5675   // tests cannot use verifyFormat because messUp manipulates leading
5676   // whitespace.
5677   {
5678     const char *Expected = "void f() {\n"
5679                            "// Aligned to preprocessor.\n"
5680                            "#if 1\n"
5681                            "  // Aligned to code.\n"
5682                            "  int a;\n"
5683                            "  #if 1\n"
5684                            "    // Aligned to preprocessor.\n"
5685                            "    #define A 0\n"
5686                            "  // Aligned to code.\n"
5687                            "  int b;\n"
5688                            "  #endif\n"
5689                            "#endif\n"
5690                            "}";
5691     const char *ToFormat = "void f() {\n"
5692                            "// Aligned to preprocessor.\n"
5693                            "#if 1\n"
5694                            "// Aligned to code.\n"
5695                            "int a;\n"
5696                            "#if 1\n"
5697                            "// Aligned to preprocessor.\n"
5698                            "#define A 0\n"
5699                            "// Aligned to code.\n"
5700                            "int b;\n"
5701                            "#endif\n"
5702                            "#endif\n"
5703                            "}";
5704     EXPECT_EQ(Expected, format(ToFormat, Style));
5705     EXPECT_EQ(Expected, format(Expected, Style));
5706   }
5707   {
5708     const char *Expected = "void f() {\n"
5709                            "/* Aligned to preprocessor. */\n"
5710                            "#if 1\n"
5711                            "  /* Aligned to code. */\n"
5712                            "  int a;\n"
5713                            "  #if 1\n"
5714                            "    /* Aligned to preprocessor. */\n"
5715                            "    #define A 0\n"
5716                            "  /* Aligned to code. */\n"
5717                            "  int b;\n"
5718                            "  #endif\n"
5719                            "#endif\n"
5720                            "}";
5721     const char *ToFormat = "void f() {\n"
5722                            "/* Aligned to preprocessor. */\n"
5723                            "#if 1\n"
5724                            "/* Aligned to code. */\n"
5725                            "int a;\n"
5726                            "#if 1\n"
5727                            "/* Aligned to preprocessor. */\n"
5728                            "#define A 0\n"
5729                            "/* Aligned to code. */\n"
5730                            "int b;\n"
5731                            "#endif\n"
5732                            "#endif\n"
5733                            "}";
5734     EXPECT_EQ(Expected, format(ToFormat, Style));
5735     EXPECT_EQ(Expected, format(Expected, Style));
5736   }
5737 
5738   // Test single comment before preprocessor
5739   verifyFormat("// Comment\n"
5740                "\n"
5741                "#if 1\n"
5742                "#endif",
5743                Style);
5744 }
5745 
5746 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5747   verifyFormat("{\n  { a #c; }\n}");
5748 }
5749 
5750 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5751   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5752             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5753   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5754             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5755 }
5756 
5757 TEST_F(FormatTest, EscapedNewlines) {
5758   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5759   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5760             format("#define A \\\nint i;\\\n  int j;", Narrow));
5761   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5762   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5763   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5764   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5765 
5766   FormatStyle AlignLeft = getLLVMStyle();
5767   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5768   EXPECT_EQ("#define MACRO(x) \\\n"
5769             "private:         \\\n"
5770             "  int x(int a);\n",
5771             format("#define MACRO(x) \\\n"
5772                    "private:         \\\n"
5773                    "  int x(int a);\n",
5774                    AlignLeft));
5775 
5776   // CRLF line endings
5777   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5778             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5779   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5780   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5781   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5782   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5783   EXPECT_EQ("#define MACRO(x) \\\r\n"
5784             "private:         \\\r\n"
5785             "  int x(int a);\r\n",
5786             format("#define MACRO(x) \\\r\n"
5787                    "private:         \\\r\n"
5788                    "  int x(int a);\r\n",
5789                    AlignLeft));
5790 
5791   FormatStyle DontAlign = getLLVMStyle();
5792   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5793   DontAlign.MaxEmptyLinesToKeep = 3;
5794   // FIXME: can't use verifyFormat here because the newline before
5795   // "public:" is not inserted the first time it's reformatted
5796   EXPECT_EQ("#define A \\\n"
5797             "  class Foo { \\\n"
5798             "    void bar(); \\\n"
5799             "\\\n"
5800             "\\\n"
5801             "\\\n"
5802             "  public: \\\n"
5803             "    void baz(); \\\n"
5804             "  };",
5805             format("#define A \\\n"
5806                    "  class Foo { \\\n"
5807                    "    void bar(); \\\n"
5808                    "\\\n"
5809                    "\\\n"
5810                    "\\\n"
5811                    "  public: \\\n"
5812                    "    void baz(); \\\n"
5813                    "  };",
5814                    DontAlign));
5815 }
5816 
5817 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5818   verifyFormat("#define A \\\n"
5819                "  int v(  \\\n"
5820                "      a); \\\n"
5821                "  int i;",
5822                getLLVMStyleWithColumns(11));
5823 }
5824 
5825 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5826   EXPECT_EQ(
5827       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5828       "                      \\\n"
5829       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5830       "\n"
5831       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5832       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5833       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5834              "\\\n"
5835              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5836              "  \n"
5837              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5838              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5839 }
5840 
5841 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5842   EXPECT_EQ("int\n"
5843             "#define A\n"
5844             "    a;",
5845             format("int\n#define A\na;"));
5846   verifyFormat("functionCallTo(\n"
5847                "    someOtherFunction(\n"
5848                "        withSomeParameters, whichInSequence,\n"
5849                "        areLongerThanALine(andAnotherCall,\n"
5850                "#define A B\n"
5851                "                           withMoreParamters,\n"
5852                "                           whichStronglyInfluenceTheLayout),\n"
5853                "        andMoreParameters),\n"
5854                "    trailing);",
5855                getLLVMStyleWithColumns(69));
5856   verifyFormat("Foo::Foo()\n"
5857                "#ifdef BAR\n"
5858                "    : baz(0)\n"
5859                "#endif\n"
5860                "{\n"
5861                "}");
5862   verifyFormat("void f() {\n"
5863                "  if (true)\n"
5864                "#ifdef A\n"
5865                "    f(42);\n"
5866                "  x();\n"
5867                "#else\n"
5868                "    g();\n"
5869                "  x();\n"
5870                "#endif\n"
5871                "}");
5872   verifyFormat("void f(param1, param2,\n"
5873                "       param3,\n"
5874                "#ifdef A\n"
5875                "       param4(param5,\n"
5876                "#ifdef A1\n"
5877                "              param6,\n"
5878                "#ifdef A2\n"
5879                "              param7),\n"
5880                "#else\n"
5881                "              param8),\n"
5882                "       param9,\n"
5883                "#endif\n"
5884                "       param10,\n"
5885                "#endif\n"
5886                "       param11)\n"
5887                "#else\n"
5888                "       param12)\n"
5889                "#endif\n"
5890                "{\n"
5891                "  x();\n"
5892                "}",
5893                getLLVMStyleWithColumns(28));
5894   verifyFormat("#if 1\n"
5895                "int i;");
5896   verifyFormat("#if 1\n"
5897                "#endif\n"
5898                "#if 1\n"
5899                "#else\n"
5900                "#endif\n");
5901   verifyFormat("DEBUG({\n"
5902                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5903                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5904                "});\n"
5905                "#if a\n"
5906                "#else\n"
5907                "#endif");
5908 
5909   verifyIncompleteFormat("void f(\n"
5910                          "#if A\n"
5911                          ");\n"
5912                          "#else\n"
5913                          "#endif");
5914 }
5915 
5916 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5917   verifyFormat("#endif\n"
5918                "#if B");
5919 }
5920 
5921 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5922   FormatStyle SingleLine = getLLVMStyle();
5923   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5924   verifyFormat("#if 0\n"
5925                "#elif 1\n"
5926                "#endif\n"
5927                "void foo() {\n"
5928                "  if (test) foo2();\n"
5929                "}",
5930                SingleLine);
5931 }
5932 
5933 TEST_F(FormatTest, LayoutBlockInsideParens) {
5934   verifyFormat("functionCall({ int i; });");
5935   verifyFormat("functionCall({\n"
5936                "  int i;\n"
5937                "  int j;\n"
5938                "});");
5939   verifyFormat("functionCall(\n"
5940                "    {\n"
5941                "      int i;\n"
5942                "      int j;\n"
5943                "    },\n"
5944                "    aaaa, bbbb, cccc);");
5945   verifyFormat("functionA(functionB({\n"
5946                "            int i;\n"
5947                "            int j;\n"
5948                "          }),\n"
5949                "          aaaa, bbbb, cccc);");
5950   verifyFormat("functionCall(\n"
5951                "    {\n"
5952                "      int i;\n"
5953                "      int j;\n"
5954                "    },\n"
5955                "    aaaa, bbbb, // comment\n"
5956                "    cccc);");
5957   verifyFormat("functionA(functionB({\n"
5958                "            int i;\n"
5959                "            int j;\n"
5960                "          }),\n"
5961                "          aaaa, bbbb, // comment\n"
5962                "          cccc);");
5963   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5964   verifyFormat("functionCall(aaaa, bbbb, {\n"
5965                "  int i;\n"
5966                "  int j;\n"
5967                "});");
5968   verifyFormat(
5969       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5970       "    {\n"
5971       "      int i; // break\n"
5972       "    },\n"
5973       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5974       "                                     ccccccccccccccccc));");
5975   verifyFormat("DEBUG({\n"
5976                "  if (a)\n"
5977                "    f();\n"
5978                "});");
5979 }
5980 
5981 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5982   EXPECT_EQ("SOME_MACRO { int i; }\n"
5983             "int i;",
5984             format("  SOME_MACRO  {int i;}  int i;"));
5985 }
5986 
5987 TEST_F(FormatTest, LayoutNestedBlocks) {
5988   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5989                "  struct s {\n"
5990                "    int i;\n"
5991                "  };\n"
5992                "  s kBitsToOs[] = {{10}};\n"
5993                "  for (int i = 0; i < 10; ++i)\n"
5994                "    return;\n"
5995                "}");
5996   verifyFormat("call(parameter, {\n"
5997                "  something();\n"
5998                "  // Comment using all columns.\n"
5999                "  somethingelse();\n"
6000                "});",
6001                getLLVMStyleWithColumns(40));
6002   verifyFormat("DEBUG( //\n"
6003                "    { f(); }, a);");
6004   verifyFormat("DEBUG( //\n"
6005                "    {\n"
6006                "      f(); //\n"
6007                "    },\n"
6008                "    a);");
6009 
6010   EXPECT_EQ("call(parameter, {\n"
6011             "  something();\n"
6012             "  // Comment too\n"
6013             "  // looooooooooong.\n"
6014             "  somethingElse();\n"
6015             "});",
6016             format("call(parameter, {\n"
6017                    "  something();\n"
6018                    "  // Comment too looooooooooong.\n"
6019                    "  somethingElse();\n"
6020                    "});",
6021                    getLLVMStyleWithColumns(29)));
6022   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
6023   EXPECT_EQ("DEBUG({ // comment\n"
6024             "  int i;\n"
6025             "});",
6026             format("DEBUG({ // comment\n"
6027                    "int  i;\n"
6028                    "});"));
6029   EXPECT_EQ("DEBUG({\n"
6030             "  int i;\n"
6031             "\n"
6032             "  // comment\n"
6033             "  int j;\n"
6034             "});",
6035             format("DEBUG({\n"
6036                    "  int  i;\n"
6037                    "\n"
6038                    "  // comment\n"
6039                    "  int  j;\n"
6040                    "});"));
6041 
6042   verifyFormat("DEBUG({\n"
6043                "  if (a)\n"
6044                "    return;\n"
6045                "});");
6046   verifyGoogleFormat("DEBUG({\n"
6047                      "  if (a) return;\n"
6048                      "});");
6049   FormatStyle Style = getGoogleStyle();
6050   Style.ColumnLimit = 45;
6051   verifyFormat("Debug(\n"
6052                "    aaaaa,\n"
6053                "    {\n"
6054                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
6055                "    },\n"
6056                "    a);",
6057                Style);
6058 
6059   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
6060 
6061   verifyNoCrash("^{v^{a}}");
6062 }
6063 
6064 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
6065   EXPECT_EQ("#define MACRO()                     \\\n"
6066             "  Debug(aaa, /* force line break */ \\\n"
6067             "        {                           \\\n"
6068             "          int i;                    \\\n"
6069             "          int j;                    \\\n"
6070             "        })",
6071             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
6072                    "          {  int   i;  int  j;   })",
6073                    getGoogleStyle()));
6074 
6075   EXPECT_EQ("#define A                                       \\\n"
6076             "  [] {                                          \\\n"
6077             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
6078             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
6079             "  }",
6080             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
6081                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
6082                    getGoogleStyle()));
6083 }
6084 
6085 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
6086   EXPECT_EQ("{}", format("{}"));
6087   verifyFormat("enum E {};");
6088   verifyFormat("enum E {}");
6089   FormatStyle Style = getLLVMStyle();
6090   Style.SpaceInEmptyBlock = true;
6091   EXPECT_EQ("void f() { }", format("void f() {}", Style));
6092   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
6093   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
6094   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
6095   Style.BraceWrapping.BeforeElse = false;
6096   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
6097   verifyFormat("if (a)\n"
6098                "{\n"
6099                "} else if (b)\n"
6100                "{\n"
6101                "} else\n"
6102                "{ }",
6103                Style);
6104   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
6105   verifyFormat("if (a) {\n"
6106                "} else if (b) {\n"
6107                "} else {\n"
6108                "}",
6109                Style);
6110   Style.BraceWrapping.BeforeElse = true;
6111   verifyFormat("if (a) { }\n"
6112                "else if (b) { }\n"
6113                "else { }",
6114                Style);
6115 }
6116 
6117 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
6118   FormatStyle Style = getLLVMStyle();
6119   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
6120   Style.MacroBlockEnd = "^[A-Z_]+_END$";
6121   verifyFormat("FOO_BEGIN\n"
6122                "  FOO_ENTRY\n"
6123                "FOO_END",
6124                Style);
6125   verifyFormat("FOO_BEGIN\n"
6126                "  NESTED_FOO_BEGIN\n"
6127                "    NESTED_FOO_ENTRY\n"
6128                "  NESTED_FOO_END\n"
6129                "FOO_END",
6130                Style);
6131   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
6132                "  int x;\n"
6133                "  x = 1;\n"
6134                "FOO_END(Baz)",
6135                Style);
6136 }
6137 
6138 //===----------------------------------------------------------------------===//
6139 // Line break tests.
6140 //===----------------------------------------------------------------------===//
6141 
6142 TEST_F(FormatTest, PreventConfusingIndents) {
6143   verifyFormat(
6144       "void f() {\n"
6145       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
6146       "                         parameter, parameter, parameter)),\n"
6147       "                     SecondLongCall(parameter));\n"
6148       "}");
6149   verifyFormat(
6150       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6151       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6152       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6153       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
6154   verifyFormat(
6155       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6156       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
6157       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6158       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
6159   verifyFormat(
6160       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
6161       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
6162       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
6163       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
6164   verifyFormat("int a = bbbb && ccc &&\n"
6165                "        fffff(\n"
6166                "#define A Just forcing a new line\n"
6167                "            ddd);");
6168 }
6169 
6170 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
6171   verifyFormat(
6172       "bool aaaaaaa =\n"
6173       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
6174       "    bbbbbbbb();");
6175   verifyFormat(
6176       "bool aaaaaaa =\n"
6177       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
6178       "    bbbbbbbb();");
6179 
6180   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6181                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
6182                "    ccccccccc == ddddddddddd;");
6183   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
6184                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
6185                "    ccccccccc == ddddddddddd;");
6186   verifyFormat(
6187       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6188       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
6189       "    ccccccccc == ddddddddddd;");
6190 
6191   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6192                "                 aaaaaa) &&\n"
6193                "         bbbbbb && cccccc;");
6194   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
6195                "                 aaaaaa) >>\n"
6196                "         bbbbbb;");
6197   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
6198                "    SourceMgr.getSpellingColumnNumber(\n"
6199                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
6200                "    1);");
6201 
6202   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6203                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
6204                "    cccccc) {\n}");
6205   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6206                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6207                "              cccccc) {\n}");
6208   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6209                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
6210                "              cccccc) {\n}");
6211   verifyFormat("b = a &&\n"
6212                "    // Comment\n"
6213                "    b.c && d;");
6214 
6215   // If the LHS of a comparison is not a binary expression itself, the
6216   // additional linebreak confuses many people.
6217   verifyFormat(
6218       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6219       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
6220       "}");
6221   verifyFormat(
6222       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6223       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6224       "}");
6225   verifyFormat(
6226       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
6227       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6228       "}");
6229   verifyFormat(
6230       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6231       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
6232       "}");
6233   // Even explicit parentheses stress the precedence enough to make the
6234   // additional break unnecessary.
6235   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6236                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
6237                "}");
6238   // This cases is borderline, but with the indentation it is still readable.
6239   verifyFormat(
6240       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6241       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6242       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6243       "}",
6244       getLLVMStyleWithColumns(75));
6245 
6246   // If the LHS is a binary expression, we should still use the additional break
6247   // as otherwise the formatting hides the operator precedence.
6248   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6249                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6250                "    5) {\n"
6251                "}");
6252   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6253                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
6254                "    5) {\n"
6255                "}");
6256 
6257   FormatStyle OnePerLine = getLLVMStyle();
6258   OnePerLine.BinPackParameters = false;
6259   verifyFormat(
6260       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6261       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6262       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
6263       OnePerLine);
6264 
6265   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
6266                "                .aaa(aaaaaaaaaaaaa) *\n"
6267                "            aaaaaaa +\n"
6268                "        aaaaaaa;",
6269                getLLVMStyleWithColumns(40));
6270 }
6271 
6272 TEST_F(FormatTest, ExpressionIndentation) {
6273   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6274                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6275                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6276                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6277                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6278                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
6279                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6280                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
6281                "                 ccccccccccccccccccccccccccccccccccccccccc;");
6282   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6283                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6284                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6285                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6286   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6287                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6288                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6289                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6290   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
6291                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
6292                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6293                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
6294   verifyFormat("if () {\n"
6295                "} else if (aaaaa && bbbbb > // break\n"
6296                "                        ccccc) {\n"
6297                "}");
6298   verifyFormat("if () {\n"
6299                "} else if constexpr (aaaaa && bbbbb > // break\n"
6300                "                                  ccccc) {\n"
6301                "}");
6302   verifyFormat("if () {\n"
6303                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
6304                "                                  ccccc) {\n"
6305                "}");
6306   verifyFormat("if () {\n"
6307                "} else if (aaaaa &&\n"
6308                "           bbbbb > // break\n"
6309                "               ccccc &&\n"
6310                "           ddddd) {\n"
6311                "}");
6312 
6313   // Presence of a trailing comment used to change indentation of b.
6314   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
6315                "       b;\n"
6316                "return aaaaaaaaaaaaaaaaaaa +\n"
6317                "       b; //",
6318                getLLVMStyleWithColumns(30));
6319 }
6320 
6321 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
6322   // Not sure what the best system is here. Like this, the LHS can be found
6323   // immediately above an operator (everything with the same or a higher
6324   // indent). The RHS is aligned right of the operator and so compasses
6325   // everything until something with the same indent as the operator is found.
6326   // FIXME: Is this a good system?
6327   FormatStyle Style = getLLVMStyle();
6328   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6329   verifyFormat(
6330       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6331       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6332       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6333       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6334       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6335       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6336       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6337       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6338       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
6339       Style);
6340   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6341                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6342                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6343                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6344                Style);
6345   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6346                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6347                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6348                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6349                Style);
6350   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6351                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6352                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6353                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6354                Style);
6355   verifyFormat("if () {\n"
6356                "} else if (aaaaa\n"
6357                "           && bbbbb // break\n"
6358                "                  > ccccc) {\n"
6359                "}",
6360                Style);
6361   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6362                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6363                Style);
6364   verifyFormat("return (a)\n"
6365                "       // comment\n"
6366                "       + b;",
6367                Style);
6368   verifyFormat(
6369       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6370       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6371       "             + cc;",
6372       Style);
6373 
6374   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6375                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6376                Style);
6377 
6378   // Forced by comments.
6379   verifyFormat(
6380       "unsigned ContentSize =\n"
6381       "    sizeof(int16_t)   // DWARF ARange version number\n"
6382       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6383       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6384       "    + sizeof(int8_t); // Segment Size (in bytes)");
6385 
6386   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6387                "       == boost::fusion::at_c<1>(iiii).second;",
6388                Style);
6389 
6390   Style.ColumnLimit = 60;
6391   verifyFormat("zzzzzzzzzz\n"
6392                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6393                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6394                Style);
6395 
6396   Style.ColumnLimit = 80;
6397   Style.IndentWidth = 4;
6398   Style.TabWidth = 4;
6399   Style.UseTab = FormatStyle::UT_Always;
6400   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6401   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6402   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
6403             "\t&& (someOtherLongishConditionPart1\n"
6404             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
6405             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
6406                    "(someOtherLongishConditionPart1 || "
6407                    "someOtherEvenLongerNestedConditionPart2);",
6408                    Style));
6409 }
6410 
6411 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
6412   FormatStyle Style = getLLVMStyle();
6413   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6414   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
6415 
6416   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6417                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6418                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6419                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6420                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6421                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6422                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6423                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6424                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
6425                Style);
6426   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6427                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6428                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6429                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6430                Style);
6431   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6432                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6433                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6434                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6435                Style);
6436   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6437                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6438                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6439                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
6440                Style);
6441   verifyFormat("if () {\n"
6442                "} else if (aaaaa\n"
6443                "           && bbbbb // break\n"
6444                "                  > ccccc) {\n"
6445                "}",
6446                Style);
6447   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6448                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6449                Style);
6450   verifyFormat("return (a)\n"
6451                "     // comment\n"
6452                "     + b;",
6453                Style);
6454   verifyFormat(
6455       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6456       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6457       "           + cc;",
6458       Style);
6459   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6460                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6461                "                        : 3333333333333333;",
6462                Style);
6463   verifyFormat(
6464       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6465       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6466       "                                             : eeeeeeeeeeeeeeeeee)\n"
6467       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6468       "                        : 3333333333333333;",
6469       Style);
6470   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6471                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6472                Style);
6473 
6474   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
6475                "    == boost::fusion::at_c<1>(iiii).second;",
6476                Style);
6477 
6478   Style.ColumnLimit = 60;
6479   verifyFormat("zzzzzzzzzzzzz\n"
6480                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6481                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
6482                Style);
6483 
6484   // Forced by comments.
6485   Style.ColumnLimit = 80;
6486   verifyFormat(
6487       "unsigned ContentSize\n"
6488       "    = sizeof(int16_t) // DWARF ARange version number\n"
6489       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6490       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6491       "    + sizeof(int8_t); // Segment Size (in bytes)",
6492       Style);
6493 
6494   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6495   verifyFormat(
6496       "unsigned ContentSize =\n"
6497       "    sizeof(int16_t)   // DWARF ARange version number\n"
6498       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6499       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6500       "    + sizeof(int8_t); // Segment Size (in bytes)",
6501       Style);
6502 
6503   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6504   verifyFormat(
6505       "unsigned ContentSize =\n"
6506       "    sizeof(int16_t)   // DWARF ARange version number\n"
6507       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
6508       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
6509       "    + sizeof(int8_t); // Segment Size (in bytes)",
6510       Style);
6511 }
6512 
6513 TEST_F(FormatTest, EnforcedOperatorWraps) {
6514   // Here we'd like to wrap after the || operators, but a comment is forcing an
6515   // earlier wrap.
6516   verifyFormat("bool x = aaaaa //\n"
6517                "         || bbbbb\n"
6518                "         //\n"
6519                "         || cccc;");
6520 }
6521 
6522 TEST_F(FormatTest, NoOperandAlignment) {
6523   FormatStyle Style = getLLVMStyle();
6524   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6525   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
6526                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6527                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6528                Style);
6529   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6530   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6531                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6532                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6533                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6534                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6535                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6536                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6537                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6538                "        > ccccccccccccccccccccccccccccccccccccccccc;",
6539                Style);
6540 
6541   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6542                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6543                "    + cc;",
6544                Style);
6545   verifyFormat("int a = aa\n"
6546                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
6547                "        * cccccccccccccccccccccccccccccccccccc;\n",
6548                Style);
6549 
6550   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6551   verifyFormat("return (a > b\n"
6552                "    // comment1\n"
6553                "    // comment2\n"
6554                "    || c);",
6555                Style);
6556 }
6557 
6558 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
6559   FormatStyle Style = getLLVMStyle();
6560   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6561   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6562                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6563                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
6564                Style);
6565 }
6566 
6567 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
6568   FormatStyle Style = getLLVMStyleWithColumns(40);
6569   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6570   Style.BinPackArguments = false;
6571   verifyFormat("void test() {\n"
6572                "  someFunction(\n"
6573                "      this + argument + is + quite\n"
6574                "      + long + so + it + gets + wrapped\n"
6575                "      + but + remains + bin - packed);\n"
6576                "}",
6577                Style);
6578   verifyFormat("void test() {\n"
6579                "  someFunction(arg1,\n"
6580                "               this + argument + is\n"
6581                "                   + quite + long + so\n"
6582                "                   + it + gets + wrapped\n"
6583                "                   + but + remains + bin\n"
6584                "                   - packed,\n"
6585                "               arg3);\n"
6586                "}",
6587                Style);
6588   verifyFormat("void test() {\n"
6589                "  someFunction(\n"
6590                "      arg1,\n"
6591                "      this + argument + has\n"
6592                "          + anotherFunc(nested,\n"
6593                "                        calls + whose\n"
6594                "                            + arguments\n"
6595                "                            + are + also\n"
6596                "                            + wrapped,\n"
6597                "                        in + addition)\n"
6598                "          + to + being + bin - packed,\n"
6599                "      arg3);\n"
6600                "}",
6601                Style);
6602 
6603   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6604   verifyFormat("void test() {\n"
6605                "  someFunction(\n"
6606                "      arg1,\n"
6607                "      this + argument + has +\n"
6608                "          anotherFunc(nested,\n"
6609                "                      calls + whose +\n"
6610                "                          arguments +\n"
6611                "                          are + also +\n"
6612                "                          wrapped,\n"
6613                "                      in + addition) +\n"
6614                "          to + being + bin - packed,\n"
6615                "      arg3);\n"
6616                "}",
6617                Style);
6618 }
6619 
6620 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) {
6621   auto Style = getLLVMStyleWithColumns(45);
6622   EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None);
6623   verifyFormat("bool b =\n"
6624                "    is_default_constructible_v<hash<T>> and\n"
6625                "    is_copy_constructible_v<hash<T>> and\n"
6626                "    is_move_constructible_v<hash<T>> and\n"
6627                "    is_copy_assignable_v<hash<T>> and\n"
6628                "    is_move_assignable_v<hash<T>> and\n"
6629                "    is_destructible_v<hash<T>> and\n"
6630                "    is_swappable_v<hash<T>> and\n"
6631                "    is_callable_v<hash<T>(T)>;",
6632                Style);
6633 
6634   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
6635   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6636                "         and is_copy_constructible_v<hash<T>>\n"
6637                "         and is_move_constructible_v<hash<T>>\n"
6638                "         and is_copy_assignable_v<hash<T>>\n"
6639                "         and is_move_assignable_v<hash<T>>\n"
6640                "         and is_destructible_v<hash<T>>\n"
6641                "         and is_swappable_v<hash<T>>\n"
6642                "         and is_callable_v<hash<T>(T)>;",
6643                Style);
6644 
6645   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6646   verifyFormat("bool b = is_default_constructible_v<hash<T>>\n"
6647                "         and is_copy_constructible_v<hash<T>>\n"
6648                "         and is_move_constructible_v<hash<T>>\n"
6649                "         and is_copy_assignable_v<hash<T>>\n"
6650                "         and is_move_assignable_v<hash<T>>\n"
6651                "         and is_destructible_v<hash<T>>\n"
6652                "         and is_swappable_v<hash<T>>\n"
6653                "         and is_callable_v<hash<T>(T)>;",
6654                Style);
6655 }
6656 
6657 TEST_F(FormatTest, ConstructorInitializers) {
6658   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6659   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
6660                getLLVMStyleWithColumns(45));
6661   verifyFormat("Constructor()\n"
6662                "    : Inttializer(FitsOnTheLine) {}",
6663                getLLVMStyleWithColumns(44));
6664   verifyFormat("Constructor()\n"
6665                "    : Inttializer(FitsOnTheLine) {}",
6666                getLLVMStyleWithColumns(43));
6667 
6668   verifyFormat("template <typename T>\n"
6669                "Constructor() : Initializer(FitsOnTheLine) {}",
6670                getLLVMStyleWithColumns(45));
6671 
6672   verifyFormat(
6673       "SomeClass::Constructor()\n"
6674       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6675 
6676   verifyFormat(
6677       "SomeClass::Constructor()\n"
6678       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6679       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
6680   verifyFormat(
6681       "SomeClass::Constructor()\n"
6682       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6683       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
6684   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6685                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6686                "    : aaaaaaaaaa(aaaaaa) {}");
6687 
6688   verifyFormat("Constructor()\n"
6689                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6690                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6691                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6692                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
6693 
6694   verifyFormat("Constructor()\n"
6695                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6696                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6697 
6698   verifyFormat("Constructor(int Parameter = 0)\n"
6699                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6700                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
6701   verifyFormat("Constructor()\n"
6702                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6703                "}",
6704                getLLVMStyleWithColumns(60));
6705   verifyFormat("Constructor()\n"
6706                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6707                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
6708 
6709   // Here a line could be saved by splitting the second initializer onto two
6710   // lines, but that is not desirable.
6711   verifyFormat("Constructor()\n"
6712                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6713                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
6714                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6715 
6716   FormatStyle OnePerLine = getLLVMStyle();
6717   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
6718   verifyFormat("MyClass::MyClass()\n"
6719                "    : a(a),\n"
6720                "      b(b),\n"
6721                "      c(c) {}",
6722                OnePerLine);
6723   verifyFormat("MyClass::MyClass()\n"
6724                "    : a(a), // comment\n"
6725                "      b(b),\n"
6726                "      c(c) {}",
6727                OnePerLine);
6728   verifyFormat("MyClass::MyClass(int a)\n"
6729                "    : b(a),      // comment\n"
6730                "      c(a + 1) { // lined up\n"
6731                "}",
6732                OnePerLine);
6733   verifyFormat("Constructor()\n"
6734                "    : a(b, b, b) {}",
6735                OnePerLine);
6736   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6737   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
6738   verifyFormat("SomeClass::Constructor()\n"
6739                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6740                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6741                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6742                OnePerLine);
6743   verifyFormat("SomeClass::Constructor()\n"
6744                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6745                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6746                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6747                OnePerLine);
6748   verifyFormat("MyClass::MyClass(int var)\n"
6749                "    : some_var_(var),            // 4 space indent\n"
6750                "      some_other_var_(var + 1) { // lined up\n"
6751                "}",
6752                OnePerLine);
6753   verifyFormat("Constructor()\n"
6754                "    : aaaaa(aaaaaa),\n"
6755                "      aaaaa(aaaaaa),\n"
6756                "      aaaaa(aaaaaa),\n"
6757                "      aaaaa(aaaaaa),\n"
6758                "      aaaaa(aaaaaa) {}",
6759                OnePerLine);
6760   verifyFormat("Constructor()\n"
6761                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6762                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6763                OnePerLine);
6764   OnePerLine.BinPackParameters = false;
6765   verifyFormat(
6766       "Constructor()\n"
6767       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6768       "          aaaaaaaaaaa().aaa(),\n"
6769       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6770       OnePerLine);
6771   OnePerLine.ColumnLimit = 60;
6772   verifyFormat("Constructor()\n"
6773                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6774                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6775                OnePerLine);
6776 
6777   EXPECT_EQ("Constructor()\n"
6778             "    : // Comment forcing unwanted break.\n"
6779             "      aaaa(aaaa) {}",
6780             format("Constructor() :\n"
6781                    "    // Comment forcing unwanted break.\n"
6782                    "    aaaa(aaaa) {}"));
6783 }
6784 
6785 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6786   FormatStyle Style = getLLVMStyleWithColumns(60);
6787   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6788   Style.BinPackParameters = false;
6789 
6790   for (int i = 0; i < 4; ++i) {
6791     // Test all combinations of parameters that should not have an effect.
6792     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6793     Style.AllowAllArgumentsOnNextLine = i & 2;
6794 
6795     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6796     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6797     verifyFormat("Constructor()\n"
6798                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6799                  Style);
6800     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6801 
6802     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6803     verifyFormat("Constructor()\n"
6804                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6805                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6806                  Style);
6807     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6808 
6809     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6810     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6811     verifyFormat("Constructor()\n"
6812                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6813                  Style);
6814 
6815     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6816     verifyFormat("Constructor()\n"
6817                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6818                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6819                  Style);
6820 
6821     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6822     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6823     verifyFormat("Constructor() :\n"
6824                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6825                  Style);
6826 
6827     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6828     verifyFormat("Constructor() :\n"
6829                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6830                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6831                  Style);
6832   }
6833 
6834   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6835   // AllowAllConstructorInitializersOnNextLine in all
6836   // BreakConstructorInitializers modes
6837   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6838   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6839   verifyFormat("SomeClassWithALongName::Constructor(\n"
6840                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6841                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6842                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6843                Style);
6844 
6845   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6846   verifyFormat("SomeClassWithALongName::Constructor(\n"
6847                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6848                "    int bbbbbbbbbbbbb,\n"
6849                "    int cccccccccccccccc)\n"
6850                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6851                Style);
6852 
6853   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6854   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6855   verifyFormat("SomeClassWithALongName::Constructor(\n"
6856                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6857                "    int bbbbbbbbbbbbb)\n"
6858                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6859                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6860                Style);
6861 
6862   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6863 
6864   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6865   verifyFormat("SomeClassWithALongName::Constructor(\n"
6866                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6867                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6868                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6869                Style);
6870 
6871   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6872   verifyFormat("SomeClassWithALongName::Constructor(\n"
6873                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6874                "    int bbbbbbbbbbbbb,\n"
6875                "    int cccccccccccccccc)\n"
6876                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6877                Style);
6878 
6879   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6880   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6881   verifyFormat("SomeClassWithALongName::Constructor(\n"
6882                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6883                "    int bbbbbbbbbbbbb)\n"
6884                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6885                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6886                Style);
6887 
6888   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6889   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6890   verifyFormat("SomeClassWithALongName::Constructor(\n"
6891                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6892                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6893                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6894                Style);
6895 
6896   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6897   verifyFormat("SomeClassWithALongName::Constructor(\n"
6898                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6899                "    int bbbbbbbbbbbbb,\n"
6900                "    int cccccccccccccccc) :\n"
6901                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6902                Style);
6903 
6904   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6905   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6906   verifyFormat("SomeClassWithALongName::Constructor(\n"
6907                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6908                "    int bbbbbbbbbbbbb) :\n"
6909                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6910                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6911                Style);
6912 }
6913 
6914 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6915   FormatStyle Style = getLLVMStyleWithColumns(60);
6916   Style.BinPackArguments = false;
6917   for (int i = 0; i < 4; ++i) {
6918     // Test all combinations of parameters that should not have an effect.
6919     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6920     Style.PackConstructorInitializers =
6921         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6922 
6923     Style.AllowAllArgumentsOnNextLine = true;
6924     verifyFormat("void foo() {\n"
6925                  "  FunctionCallWithReallyLongName(\n"
6926                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6927                  "}",
6928                  Style);
6929     Style.AllowAllArgumentsOnNextLine = false;
6930     verifyFormat("void foo() {\n"
6931                  "  FunctionCallWithReallyLongName(\n"
6932                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6933                  "      bbbbbbbbbbbb);\n"
6934                  "}",
6935                  Style);
6936 
6937     Style.AllowAllArgumentsOnNextLine = true;
6938     verifyFormat("void foo() {\n"
6939                  "  auto VariableWithReallyLongName = {\n"
6940                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6941                  "}",
6942                  Style);
6943     Style.AllowAllArgumentsOnNextLine = false;
6944     verifyFormat("void foo() {\n"
6945                  "  auto VariableWithReallyLongName = {\n"
6946                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6947                  "      bbbbbbbbbbbb};\n"
6948                  "}",
6949                  Style);
6950   }
6951 
6952   // This parameter should not affect declarations.
6953   Style.BinPackParameters = false;
6954   Style.AllowAllArgumentsOnNextLine = false;
6955   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6956   verifyFormat("void FunctionCallWithReallyLongName(\n"
6957                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6958                Style);
6959   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6960   verifyFormat("void FunctionCallWithReallyLongName(\n"
6961                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6962                "    int bbbbbbbbbbbb);",
6963                Style);
6964 }
6965 
6966 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6967   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6968   // and BAS_Align.
6969   FormatStyle Style = getLLVMStyleWithColumns(35);
6970   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6971                     "void functionDecl(int A, int B, int C);";
6972   Style.AllowAllArgumentsOnNextLine = false;
6973   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6974   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6975                       "    paramC);\n"
6976                       "void functionDecl(int A, int B,\n"
6977                       "    int C);"),
6978             format(Input, Style));
6979   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6980   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6981                       "             paramC);\n"
6982                       "void functionDecl(int A, int B,\n"
6983                       "                  int C);"),
6984             format(Input, Style));
6985   // However, BAS_AlwaysBreak should take precedence over
6986   // AllowAllArgumentsOnNextLine.
6987   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6988   EXPECT_EQ(StringRef("functionCall(\n"
6989                       "    paramA, paramB, paramC);\n"
6990                       "void functionDecl(\n"
6991                       "    int A, int B, int C);"),
6992             format(Input, Style));
6993 
6994   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6995   // first argument.
6996   Style.AllowAllArgumentsOnNextLine = true;
6997   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6998   EXPECT_EQ(StringRef("functionCall(\n"
6999                       "    paramA, paramB, paramC);\n"
7000                       "void functionDecl(\n"
7001                       "    int A, int B, int C);"),
7002             format(Input, Style));
7003   // It wouldn't fit on one line with aligned parameters so this setting
7004   // doesn't change anything for BAS_Align.
7005   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7006   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
7007                       "             paramC);\n"
7008                       "void functionDecl(int A, int B,\n"
7009                       "                  int C);"),
7010             format(Input, Style));
7011   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7012   EXPECT_EQ(StringRef("functionCall(\n"
7013                       "    paramA, paramB, paramC);\n"
7014                       "void functionDecl(\n"
7015                       "    int A, int B, int C);"),
7016             format(Input, Style));
7017 }
7018 
7019 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
7020   FormatStyle Style = getLLVMStyle();
7021   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
7022 
7023   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
7024   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
7025                getStyleWithColumns(Style, 45));
7026   verifyFormat("Constructor() :\n"
7027                "    Initializer(FitsOnTheLine) {}",
7028                getStyleWithColumns(Style, 44));
7029   verifyFormat("Constructor() :\n"
7030                "    Initializer(FitsOnTheLine) {}",
7031                getStyleWithColumns(Style, 43));
7032 
7033   verifyFormat("template <typename T>\n"
7034                "Constructor() : Initializer(FitsOnTheLine) {}",
7035                getStyleWithColumns(Style, 50));
7036   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7037   verifyFormat(
7038       "SomeClass::Constructor() :\n"
7039       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
7040       Style);
7041   verifyFormat(
7042       "SomeClass::Constructor() : // NOLINT\n"
7043       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
7044       Style);
7045 
7046   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
7047   verifyFormat(
7048       "SomeClass::Constructor() :\n"
7049       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
7050       Style);
7051 
7052   verifyFormat(
7053       "SomeClass::Constructor() :\n"
7054       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7055       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7056       Style);
7057   verifyFormat(
7058       "SomeClass::Constructor() :\n"
7059       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7060       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
7061       Style);
7062   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7063                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7064                "    aaaaaaaaaa(aaaaaa) {}",
7065                Style);
7066 
7067   verifyFormat("Constructor() :\n"
7068                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7069                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7070                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7071                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
7072                Style);
7073 
7074   verifyFormat("Constructor() :\n"
7075                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7076                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7077                Style);
7078 
7079   verifyFormat("Constructor(int Parameter = 0) :\n"
7080                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
7081                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
7082                Style);
7083   verifyFormat("Constructor() :\n"
7084                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
7085                "}",
7086                getStyleWithColumns(Style, 60));
7087   verifyFormat("Constructor() :\n"
7088                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7089                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
7090                Style);
7091 
7092   // Here a line could be saved by splitting the second initializer onto two
7093   // lines, but that is not desirable.
7094   verifyFormat("Constructor() :\n"
7095                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
7096                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
7097                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7098                Style);
7099 
7100   FormatStyle OnePerLine = Style;
7101   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
7102   verifyFormat("SomeClass::Constructor() :\n"
7103                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7104                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7105                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7106                OnePerLine);
7107   verifyFormat("SomeClass::Constructor() :\n"
7108                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
7109                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
7110                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
7111                OnePerLine);
7112   verifyFormat("Foo::Foo(int i, int j) : // NOLINT\n"
7113                "    i(i),                // comment\n"
7114                "    j(j) {}",
7115                OnePerLine);
7116   verifyFormat("MyClass::MyClass(int var) :\n"
7117                "    some_var_(var),            // 4 space indent\n"
7118                "    some_other_var_(var + 1) { // lined up\n"
7119                "}",
7120                OnePerLine);
7121   verifyFormat("Constructor() :\n"
7122                "    aaaaa(aaaaaa),\n"
7123                "    aaaaa(aaaaaa),\n"
7124                "    aaaaa(aaaaaa),\n"
7125                "    aaaaa(aaaaaa),\n"
7126                "    aaaaa(aaaaaa) {}",
7127                OnePerLine);
7128   verifyFormat("Constructor() :\n"
7129                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
7130                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
7131                OnePerLine);
7132   OnePerLine.BinPackParameters = false;
7133   verifyFormat("Constructor() :\n"
7134                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7135                "        aaaaaaaaaaa().aaa(),\n"
7136                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7137                OnePerLine);
7138   OnePerLine.ColumnLimit = 60;
7139   verifyFormat("Constructor() :\n"
7140                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
7141                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
7142                OnePerLine);
7143 
7144   verifyFormat("Constructor() :\n"
7145                "    // Comment forcing unwanted break.\n"
7146                "    aaaa(aaaa) {}",
7147                Style);
7148   verifyFormat("Constructor() : // NOLINT\n"
7149                "    aaaa(aaaa) {}",
7150                Style);
7151   verifyFormat("Constructor() : // A very long trailing comment that cannot fit"
7152                " on a single\n"
7153                "                // line.\n"
7154                "    aaaa(aaaa) {}",
7155                "Constructor() : // A very long trailing comment that cannot fit"
7156                " on a single line.\n"
7157                "    aaaa(aaaa) {}",
7158                Style);
7159 
7160   Style.ColumnLimit = 0;
7161   verifyFormat("SomeClass::Constructor() :\n"
7162                "    a(a) {}",
7163                Style);
7164   verifyFormat("SomeClass::Constructor() noexcept :\n"
7165                "    a(a) {}",
7166                Style);
7167   verifyFormat("SomeClass::Constructor() :\n"
7168                "    a(a), b(b), c(c) {}",
7169                Style);
7170   verifyFormat("SomeClass::Constructor() :\n"
7171                "    a(a) {\n"
7172                "  foo();\n"
7173                "  bar();\n"
7174                "}",
7175                Style);
7176 
7177   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
7178   verifyFormat("SomeClass::Constructor() :\n"
7179                "    a(a), b(b), c(c) {\n"
7180                "}",
7181                Style);
7182   verifyFormat("SomeClass::Constructor() :\n"
7183                "    a(a) {\n"
7184                "}",
7185                Style);
7186 
7187   Style.ColumnLimit = 80;
7188   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
7189   Style.ConstructorInitializerIndentWidth = 2;
7190   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
7191   verifyFormat("SomeClass::Constructor() :\n"
7192                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7193                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
7194                Style);
7195 
7196   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
7197   // well
7198   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
7199   verifyFormat(
7200       "class SomeClass\n"
7201       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7202       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7203       Style);
7204   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
7205   verifyFormat(
7206       "class SomeClass\n"
7207       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7208       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7209       Style);
7210   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
7211   verifyFormat(
7212       "class SomeClass :\n"
7213       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7214       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7215       Style);
7216   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
7217   verifyFormat(
7218       "class SomeClass\n"
7219       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7220       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
7221       Style);
7222 }
7223 
7224 #ifndef EXPENSIVE_CHECKS
7225 // Expensive checks enables libstdc++ checking which includes validating the
7226 // state of ranges used in std::priority_queue - this blows out the
7227 // runtime/scalability of the function and makes this test unacceptably slow.
7228 TEST_F(FormatTest, MemoizationTests) {
7229   // This breaks if the memoization lookup does not take \c Indent and
7230   // \c LastSpace into account.
7231   verifyFormat(
7232       "extern CFRunLoopTimerRef\n"
7233       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
7234       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
7235       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
7236       "                     CFRunLoopTimerContext *context) {}");
7237 
7238   // Deep nesting somewhat works around our memoization.
7239   verifyFormat(
7240       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7241       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7242       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7243       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
7244       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
7245       getLLVMStyleWithColumns(65));
7246   verifyFormat(
7247       "aaaaa(\n"
7248       "    aaaaa,\n"
7249       "    aaaaa(\n"
7250       "        aaaaa,\n"
7251       "        aaaaa(\n"
7252       "            aaaaa,\n"
7253       "            aaaaa(\n"
7254       "                aaaaa,\n"
7255       "                aaaaa(\n"
7256       "                    aaaaa,\n"
7257       "                    aaaaa(\n"
7258       "                        aaaaa,\n"
7259       "                        aaaaa(\n"
7260       "                            aaaaa,\n"
7261       "                            aaaaa(\n"
7262       "                                aaaaa,\n"
7263       "                                aaaaa(\n"
7264       "                                    aaaaa,\n"
7265       "                                    aaaaa(\n"
7266       "                                        aaaaa,\n"
7267       "                                        aaaaa(\n"
7268       "                                            aaaaa,\n"
7269       "                                            aaaaa(\n"
7270       "                                                aaaaa,\n"
7271       "                                                aaaaa))))))))))));",
7272       getLLVMStyleWithColumns(65));
7273   verifyFormat(
7274       "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"
7275       "                                  a),\n"
7276       "                                a),\n"
7277       "                              a),\n"
7278       "                            a),\n"
7279       "                          a),\n"
7280       "                        a),\n"
7281       "                      a),\n"
7282       "                    a),\n"
7283       "                  a),\n"
7284       "                a),\n"
7285       "              a),\n"
7286       "            a),\n"
7287       "          a),\n"
7288       "        a),\n"
7289       "      a),\n"
7290       "    a),\n"
7291       "  a)",
7292       getLLVMStyleWithColumns(65));
7293 
7294   // This test takes VERY long when memoization is broken.
7295   FormatStyle OnePerLine = getLLVMStyle();
7296   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
7297   OnePerLine.BinPackParameters = false;
7298   std::string input = "Constructor()\n"
7299                       "    : aaaa(a,\n";
7300   for (unsigned i = 0, e = 80; i != e; ++i)
7301     input += "           a,\n";
7302   input += "           a) {}";
7303   verifyFormat(input, OnePerLine);
7304 }
7305 #endif
7306 
7307 TEST_F(FormatTest, BreaksAsHighAsPossible) {
7308   verifyFormat(
7309       "void f() {\n"
7310       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
7311       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
7312       "    f();\n"
7313       "}");
7314   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
7315                "    Intervals[i - 1].getRange().getLast()) {\n}");
7316 }
7317 
7318 TEST_F(FormatTest, BreaksFunctionDeclarations) {
7319   // Principially, we break function declarations in a certain order:
7320   // 1) break amongst arguments.
7321   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
7322                "                              Cccccccccccccc cccccccccccccc);");
7323   verifyFormat("template <class TemplateIt>\n"
7324                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
7325                "                            TemplateIt *stop) {}");
7326 
7327   // 2) break after return type.
7328   verifyFormat(
7329       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7330       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
7331       getGoogleStyle());
7332 
7333   // 3) break after (.
7334   verifyFormat(
7335       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
7336       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
7337       getGoogleStyle());
7338 
7339   // 4) break before after nested name specifiers.
7340   verifyFormat(
7341       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7342       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
7343       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
7344       getGoogleStyle());
7345 
7346   // However, there are exceptions, if a sufficient amount of lines can be
7347   // saved.
7348   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
7349   // more adjusting.
7350   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7351                "                                  Cccccccccccccc cccccccccc,\n"
7352                "                                  Cccccccccccccc cccccccccc,\n"
7353                "                                  Cccccccccccccc cccccccccc,\n"
7354                "                                  Cccccccccccccc cccccccccc);");
7355   verifyFormat(
7356       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7357       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7358       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7359       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
7360       getGoogleStyle());
7361   verifyFormat(
7362       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
7363       "                                          Cccccccccccccc cccccccccc,\n"
7364       "                                          Cccccccccccccc cccccccccc,\n"
7365       "                                          Cccccccccccccc cccccccccc,\n"
7366       "                                          Cccccccccccccc cccccccccc,\n"
7367       "                                          Cccccccccccccc cccccccccc,\n"
7368       "                                          Cccccccccccccc cccccccccc);");
7369   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7370                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7371                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7372                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
7373                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
7374 
7375   // Break after multi-line parameters.
7376   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7377                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7378                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7379                "    bbbb bbbb);");
7380   verifyFormat("void SomeLoooooooooooongFunction(\n"
7381                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
7382                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7383                "    int bbbbbbbbbbbbb);");
7384 
7385   // Treat overloaded operators like other functions.
7386   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7387                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
7388   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7389                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
7390   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
7391                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
7392   verifyGoogleFormat(
7393       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
7394       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7395   verifyGoogleFormat(
7396       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
7397       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
7398   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7399                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7400   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
7401                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
7402   verifyGoogleFormat(
7403       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
7404       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7405       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
7406   verifyGoogleFormat("template <typename T>\n"
7407                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7408                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
7409                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
7410 
7411   FormatStyle Style = getLLVMStyle();
7412   Style.PointerAlignment = FormatStyle::PAS_Left;
7413   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7414                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
7415                Style);
7416   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
7417                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7418                Style);
7419 }
7420 
7421 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
7422   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
7423   // Prefer keeping `::` followed by `operator` together.
7424   EXPECT_EQ("const aaaa::bbbbbbb &\n"
7425             "ccccccccc::operator++() {\n"
7426             "  stuff();\n"
7427             "}",
7428             format("const aaaa::bbbbbbb\n"
7429                    "&ccccccccc::operator++() { stuff(); }",
7430                    getLLVMStyleWithColumns(40)));
7431 }
7432 
7433 TEST_F(FormatTest, TrailingReturnType) {
7434   verifyFormat("auto foo() -> int;\n");
7435   // correct trailing return type spacing
7436   verifyFormat("auto operator->() -> int;\n");
7437   verifyFormat("auto operator++(int) -> int;\n");
7438 
7439   verifyFormat("struct S {\n"
7440                "  auto bar() const -> int;\n"
7441                "};");
7442   verifyFormat("template <size_t Order, typename T>\n"
7443                "auto load_img(const std::string &filename)\n"
7444                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
7445   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
7446                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
7447   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
7448   verifyFormat("template <typename T>\n"
7449                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
7450                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
7451 
7452   // Not trailing return types.
7453   verifyFormat("void f() { auto a = b->c(); }");
7454   verifyFormat("auto a = p->foo();");
7455   verifyFormat("int a = p->foo();");
7456   verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
7457 }
7458 
7459 TEST_F(FormatTest, DeductionGuides) {
7460   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
7461   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
7462   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
7463   verifyFormat(
7464       "template <class... T>\n"
7465       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
7466   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
7467   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
7468   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
7469   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
7470   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
7471   verifyFormat("template <class T> x() -> x<1>;");
7472   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
7473 
7474   // Ensure not deduction guides.
7475   verifyFormat("c()->f<int>();");
7476   verifyFormat("x()->foo<1>;");
7477   verifyFormat("x = p->foo<3>();");
7478   verifyFormat("x()->x<1>();");
7479   verifyFormat("x()->x<1>;");
7480 }
7481 
7482 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
7483   // Avoid breaking before trailing 'const' or other trailing annotations, if
7484   // they are not function-like.
7485   FormatStyle Style = getGoogleStyleWithColumns(47);
7486   verifyFormat("void someLongFunction(\n"
7487                "    int someLoooooooooooooongParameter) const {\n}",
7488                getLLVMStyleWithColumns(47));
7489   verifyFormat("LoooooongReturnType\n"
7490                "someLoooooooongFunction() const {}",
7491                getLLVMStyleWithColumns(47));
7492   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
7493                "    const {}",
7494                Style);
7495   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7496                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
7497   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7498                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
7499   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
7500                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
7501   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
7502                "                   aaaaaaaaaaa aaaaa) const override;");
7503   verifyGoogleFormat(
7504       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7505       "    const override;");
7506 
7507   // Even if the first parameter has to be wrapped.
7508   verifyFormat("void someLongFunction(\n"
7509                "    int someLongParameter) const {}",
7510                getLLVMStyleWithColumns(46));
7511   verifyFormat("void someLongFunction(\n"
7512                "    int someLongParameter) const {}",
7513                Style);
7514   verifyFormat("void someLongFunction(\n"
7515                "    int someLongParameter) override {}",
7516                Style);
7517   verifyFormat("void someLongFunction(\n"
7518                "    int someLongParameter) OVERRIDE {}",
7519                Style);
7520   verifyFormat("void someLongFunction(\n"
7521                "    int someLongParameter) final {}",
7522                Style);
7523   verifyFormat("void someLongFunction(\n"
7524                "    int someLongParameter) FINAL {}",
7525                Style);
7526   verifyFormat("void someLongFunction(\n"
7527                "    int parameter) const override {}",
7528                Style);
7529 
7530   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
7531   verifyFormat("void someLongFunction(\n"
7532                "    int someLongParameter) const\n"
7533                "{\n"
7534                "}",
7535                Style);
7536 
7537   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
7538   verifyFormat("void someLongFunction(\n"
7539                "    int someLongParameter) const\n"
7540                "  {\n"
7541                "  }",
7542                Style);
7543 
7544   // Unless these are unknown annotations.
7545   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
7546                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7547                "    LONG_AND_UGLY_ANNOTATION;");
7548 
7549   // Breaking before function-like trailing annotations is fine to keep them
7550   // close to their arguments.
7551   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7552                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7553   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7554                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
7555   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
7556                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
7557   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
7558                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
7559   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
7560 
7561   verifyFormat(
7562       "void aaaaaaaaaaaaaaaaaa()\n"
7563       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
7564       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
7565   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7566                "    __attribute__((unused));");
7567   verifyGoogleFormat(
7568       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7569       "    GUARDED_BY(aaaaaaaaaaaa);");
7570   verifyGoogleFormat(
7571       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7572       "    GUARDED_BY(aaaaaaaaaaaa);");
7573   verifyGoogleFormat(
7574       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7575       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7576   verifyGoogleFormat(
7577       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
7578       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
7579 }
7580 
7581 TEST_F(FormatTest, FunctionAnnotations) {
7582   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7583                "int OldFunction(const string &parameter) {}");
7584   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7585                "string OldFunction(const string &parameter) {}");
7586   verifyFormat("template <typename T>\n"
7587                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
7588                "string OldFunction(const string &parameter) {}");
7589 
7590   // Not function annotations.
7591   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7592                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
7593   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
7594                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
7595   verifyFormat("MACRO(abc).function() // wrap\n"
7596                "    << abc;");
7597   verifyFormat("MACRO(abc)->function() // wrap\n"
7598                "    << abc;");
7599   verifyFormat("MACRO(abc)::function() // wrap\n"
7600                "    << abc;");
7601 }
7602 
7603 TEST_F(FormatTest, BreaksDesireably) {
7604   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7605                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
7606                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
7607   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7608                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
7609                "}");
7610 
7611   verifyFormat(
7612       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7613       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
7614 
7615   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7616                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7617                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7618 
7619   verifyFormat(
7620       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7621       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7622       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7623       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7624       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
7625 
7626   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7627                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7628 
7629   verifyFormat(
7630       "void f() {\n"
7631       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7632       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7633       "}");
7634   verifyFormat(
7635       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7636       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7637   verifyFormat(
7638       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7639       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7640   verifyFormat(
7641       "aaaaaa(aaa,\n"
7642       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7643       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7644       "       aaaa);");
7645   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7646                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7647                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7648 
7649   // Indent consistently independent of call expression and unary operator.
7650   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7651                "    dddddddddddddddddddddddddddddd));");
7652   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
7653                "    dddddddddddddddddddddddddddddd));");
7654   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
7655                "    dddddddddddddddddddddddddddddd));");
7656 
7657   // This test case breaks on an incorrect memoization, i.e. an optimization not
7658   // taking into account the StopAt value.
7659   verifyFormat(
7660       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7661       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7662       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
7663       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7664 
7665   verifyFormat("{\n  {\n    {\n"
7666                "      Annotation.SpaceRequiredBefore =\n"
7667                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
7668                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
7669                "    }\n  }\n}");
7670 
7671   // Break on an outer level if there was a break on an inner level.
7672   EXPECT_EQ("f(g(h(a, // comment\n"
7673             "      b, c),\n"
7674             "    d, e),\n"
7675             "  x, y);",
7676             format("f(g(h(a, // comment\n"
7677                    "    b, c), d, e), x, y);"));
7678 
7679   // Prefer breaking similar line breaks.
7680   verifyFormat(
7681       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
7682       "                             NSTrackingMouseEnteredAndExited |\n"
7683       "                             NSTrackingActiveAlways;");
7684 }
7685 
7686 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
7687   FormatStyle NoBinPacking = getGoogleStyle();
7688   NoBinPacking.BinPackParameters = false;
7689   NoBinPacking.BinPackArguments = true;
7690   verifyFormat("void f() {\n"
7691                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
7692                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7693                "}",
7694                NoBinPacking);
7695   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
7696                "       int aaaaaaaaaaaaaaaaaaaa,\n"
7697                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7698                NoBinPacking);
7699 
7700   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7701   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7702                "                        vector<int> bbbbbbbbbbbbbbb);",
7703                NoBinPacking);
7704   // FIXME: This behavior difference is probably not wanted. However, currently
7705   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
7706   // template arguments from BreakBeforeParameter being set because of the
7707   // one-per-line formatting.
7708   verifyFormat(
7709       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7710       "                                             aaaaaaaaaa> aaaaaaaaaa);",
7711       NoBinPacking);
7712   verifyFormat(
7713       "void fffffffffff(\n"
7714       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
7715       "        aaaaaaaaaa);");
7716 }
7717 
7718 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
7719   FormatStyle NoBinPacking = getGoogleStyle();
7720   NoBinPacking.BinPackParameters = false;
7721   NoBinPacking.BinPackArguments = false;
7722   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
7723                "  aaaaaaaaaaaaaaaaaaaa,\n"
7724                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
7725                NoBinPacking);
7726   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
7727                "        aaaaaaaaaaaaa,\n"
7728                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
7729                NoBinPacking);
7730   verifyFormat(
7731       "aaaaaaaa(aaaaaaaaaaaaa,\n"
7732       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7733       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
7734       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7735       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
7736       NoBinPacking);
7737   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7738                "    .aaaaaaaaaaaaaaaaaa();",
7739                NoBinPacking);
7740   verifyFormat("void f() {\n"
7741                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7742                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
7743                "}",
7744                NoBinPacking);
7745 
7746   verifyFormat(
7747       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7748       "             aaaaaaaaaaaa,\n"
7749       "             aaaaaaaaaaaa);",
7750       NoBinPacking);
7751   verifyFormat(
7752       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
7753       "                               ddddddddddddddddddddddddddddd),\n"
7754       "             test);",
7755       NoBinPacking);
7756 
7757   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
7758                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
7759                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
7760                "    aaaaaaaaaaaaaaaaaa;",
7761                NoBinPacking);
7762   verifyFormat("a(\"a\"\n"
7763                "  \"a\",\n"
7764                "  a);");
7765 
7766   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
7767   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7768                "                aaaaaaaaa,\n"
7769                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7770                NoBinPacking);
7771   verifyFormat(
7772       "void f() {\n"
7773       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7774       "      .aaaaaaa();\n"
7775       "}",
7776       NoBinPacking);
7777   verifyFormat(
7778       "template <class SomeType, class SomeOtherType>\n"
7779       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7780       NoBinPacking);
7781 }
7782 
7783 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7784   FormatStyle Style = getLLVMStyleWithColumns(15);
7785   Style.ExperimentalAutoDetectBinPacking = true;
7786   EXPECT_EQ("aaa(aaaa,\n"
7787             "    aaaa,\n"
7788             "    aaaa);\n"
7789             "aaa(aaaa,\n"
7790             "    aaaa,\n"
7791             "    aaaa);",
7792             format("aaa(aaaa,\n" // one-per-line
7793                    "  aaaa,\n"
7794                    "    aaaa  );\n"
7795                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7796                    Style));
7797   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7798             "    aaaa);\n"
7799             "aaa(aaaa, aaaa,\n"
7800             "    aaaa);",
7801             format("aaa(aaaa,  aaaa,\n" // bin-packed
7802                    "    aaaa  );\n"
7803                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7804                    Style));
7805 }
7806 
7807 TEST_F(FormatTest, FormatsBuilderPattern) {
7808   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7809                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7810                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7811                "    .StartsWith(\".init\", ORDER_INIT)\n"
7812                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7813                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7814                "    .Default(ORDER_TEXT);\n");
7815 
7816   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7817                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7818   verifyFormat("aaaaaaa->aaaaaaa\n"
7819                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7820                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7821                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7822   verifyFormat(
7823       "aaaaaaa->aaaaaaa\n"
7824       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7825       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7826   verifyFormat(
7827       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7828       "    aaaaaaaaaaaaaa);");
7829   verifyFormat(
7830       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7831       "    aaaaaa->aaaaaaaaaaaa()\n"
7832       "        ->aaaaaaaaaaaaaaaa(\n"
7833       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7834       "        ->aaaaaaaaaaaaaaaaa();");
7835   verifyGoogleFormat(
7836       "void f() {\n"
7837       "  someo->Add((new util::filetools::Handler(dir))\n"
7838       "                 ->OnEvent1(NewPermanentCallback(\n"
7839       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7840       "                 ->OnEvent2(NewPermanentCallback(\n"
7841       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7842       "                 ->OnEvent3(NewPermanentCallback(\n"
7843       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7844       "                 ->OnEvent5(NewPermanentCallback(\n"
7845       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7846       "                 ->OnEvent6(NewPermanentCallback(\n"
7847       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7848       "}");
7849 
7850   verifyFormat(
7851       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7852   verifyFormat("aaaaaaaaaaaaaaa()\n"
7853                "    .aaaaaaaaaaaaaaa()\n"
7854                "    .aaaaaaaaaaaaaaa()\n"
7855                "    .aaaaaaaaaaaaaaa()\n"
7856                "    .aaaaaaaaaaaaaaa();");
7857   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7858                "    .aaaaaaaaaaaaaaa()\n"
7859                "    .aaaaaaaaaaaaaaa()\n"
7860                "    .aaaaaaaaaaaaaaa();");
7861   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7862                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7863                "    .aaaaaaaaaaaaaaa();");
7864   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7865                "    ->aaaaaaaaaaaaaae(0)\n"
7866                "    ->aaaaaaaaaaaaaaa();");
7867 
7868   // Don't linewrap after very short segments.
7869   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7870                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7871                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7872   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7873                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7874                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7875   verifyFormat("aaa()\n"
7876                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7877                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7878                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7879 
7880   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7881                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7882                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7883   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7884                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7885                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7886 
7887   // Prefer not to break after empty parentheses.
7888   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7889                "    First->LastNewlineOffset);");
7890 
7891   // Prefer not to create "hanging" indents.
7892   verifyFormat(
7893       "return !soooooooooooooome_map\n"
7894       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7895       "            .second;");
7896   verifyFormat(
7897       "return aaaaaaaaaaaaaaaa\n"
7898       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7899       "    .aaaa(aaaaaaaaaaaaaa);");
7900   // No hanging indent here.
7901   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7902                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7903   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7904                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7905   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7906                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7907                getLLVMStyleWithColumns(60));
7908   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7909                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7910                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7911                getLLVMStyleWithColumns(59));
7912   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7913                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7914                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7915 
7916   // Dont break if only closing statements before member call
7917   verifyFormat("test() {\n"
7918                "  ([]() -> {\n"
7919                "    int b = 32;\n"
7920                "    return 3;\n"
7921                "  }).foo();\n"
7922                "}");
7923   verifyFormat("test() {\n"
7924                "  (\n"
7925                "      []() -> {\n"
7926                "        int b = 32;\n"
7927                "        return 3;\n"
7928                "      },\n"
7929                "      foo, bar)\n"
7930                "      .foo();\n"
7931                "}");
7932   verifyFormat("test() {\n"
7933                "  ([]() -> {\n"
7934                "    int b = 32;\n"
7935                "    return 3;\n"
7936                "  })\n"
7937                "      .foo()\n"
7938                "      .bar();\n"
7939                "}");
7940   verifyFormat("test() {\n"
7941                "  ([]() -> {\n"
7942                "    int b = 32;\n"
7943                "    return 3;\n"
7944                "  })\n"
7945                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7946                "           \"bbbb\");\n"
7947                "}",
7948                getLLVMStyleWithColumns(30));
7949 }
7950 
7951 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7952   verifyFormat(
7953       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7954       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7955   verifyFormat(
7956       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7957       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7958 
7959   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7960                "    ccccccccccccccccccccccccc) {\n}");
7961   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7962                "    ccccccccccccccccccccccccc) {\n}");
7963 
7964   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7965                "    ccccccccccccccccccccccccc) {\n}");
7966   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7967                "    ccccccccccccccccccccccccc) {\n}");
7968 
7969   verifyFormat(
7970       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7971       "    ccccccccccccccccccccccccc) {\n}");
7972   verifyFormat(
7973       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7974       "    ccccccccccccccccccccccccc) {\n}");
7975 
7976   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7977                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7978                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7979                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7980   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7981                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7982                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7983                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7984 
7985   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7986                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7987                "    aaaaaaaaaaaaaaa != aa) {\n}");
7988   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7989                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7990                "    aaaaaaaaaaaaaaa != aa) {\n}");
7991 }
7992 
7993 TEST_F(FormatTest, BreaksAfterAssignments) {
7994   verifyFormat(
7995       "unsigned Cost =\n"
7996       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7997       "                        SI->getPointerAddressSpaceee());\n");
7998   verifyFormat(
7999       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
8000       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
8001 
8002   verifyFormat(
8003       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
8004       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
8005   verifyFormat("unsigned OriginalStartColumn =\n"
8006                "    SourceMgr.getSpellingColumnNumber(\n"
8007                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
8008                "    1;");
8009 }
8010 
8011 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
8012   FormatStyle Style = getLLVMStyle();
8013   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8014                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
8015                Style);
8016 
8017   Style.PenaltyBreakAssignment = 20;
8018   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
8019                "                                 cccccccccccccccccccccccccc;",
8020                Style);
8021 }
8022 
8023 TEST_F(FormatTest, AlignsAfterAssignments) {
8024   verifyFormat(
8025       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8026       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
8027   verifyFormat(
8028       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8029       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
8030   verifyFormat(
8031       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8032       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
8033   verifyFormat(
8034       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8035       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
8036   verifyFormat(
8037       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
8038       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
8039       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
8040 }
8041 
8042 TEST_F(FormatTest, AlignsAfterReturn) {
8043   verifyFormat(
8044       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8045       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
8046   verifyFormat(
8047       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8048       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
8049   verifyFormat(
8050       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
8051       "       aaaaaaaaaaaaaaaaaaaaaa();");
8052   verifyFormat(
8053       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
8054       "        aaaaaaaaaaaaaaaaaaaaaa());");
8055   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8056                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8057   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8058                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
8059                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8060   verifyFormat("return\n"
8061                "    // true if code is one of a or b.\n"
8062                "    code == a || code == b;");
8063 }
8064 
8065 TEST_F(FormatTest, AlignsAfterOpenBracket) {
8066   verifyFormat(
8067       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
8068       "                                                aaaaaaaaa aaaaaaa) {}");
8069   verifyFormat(
8070       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
8071       "                                               aaaaaaaaaaa aaaaaaaaa);");
8072   verifyFormat(
8073       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
8074       "                                             aaaaaaaaaaaaaaaaaaaaa));");
8075   FormatStyle Style = getLLVMStyle();
8076   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8077   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8078                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
8079                Style);
8080   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8081                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
8082                Style);
8083   verifyFormat("SomeLongVariableName->someFunction(\n"
8084                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
8085                Style);
8086   verifyFormat(
8087       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
8088       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8089       Style);
8090   verifyFormat(
8091       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
8092       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8093       Style);
8094   verifyFormat(
8095       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
8096       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8097       Style);
8098 
8099   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
8100                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
8101                "        b));",
8102                Style);
8103 
8104   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8105   Style.BinPackArguments = false;
8106   Style.BinPackParameters = false;
8107   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8108                "    aaaaaaaaaaa aaaaaaaa,\n"
8109                "    aaaaaaaaa aaaaaaa,\n"
8110                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
8111                Style);
8112   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
8113                "    aaaaaaaaaaa aaaaaaaaa,\n"
8114                "    aaaaaaaaaaa aaaaaaaaa,\n"
8115                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8116                Style);
8117   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
8118                "    aaaaaaaaaaaaaaa,\n"
8119                "    aaaaaaaaaaaaaaaaaaaaa,\n"
8120                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
8121                Style);
8122   verifyFormat(
8123       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
8124       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8125       Style);
8126   verifyFormat(
8127       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
8128       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
8129       Style);
8130   verifyFormat(
8131       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8132       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8133       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
8134       "    aaaaaaaaaaaaaaaa);",
8135       Style);
8136   verifyFormat(
8137       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
8138       "    aaaaaaaaaaaaaaaaaaaaa(\n"
8139       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
8140       "    aaaaaaaaaaaaaaaa);",
8141       Style);
8142 }
8143 
8144 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
8145   FormatStyle Style = getLLVMStyleWithColumns(40);
8146   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8147                "          bbbbbbbbbbbbbbbbbbbbbb);",
8148                Style);
8149   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
8150   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8151   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8152                "          bbbbbbbbbbbbbbbbbbbbbb);",
8153                Style);
8154   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8155   Style.AlignOperands = FormatStyle::OAS_Align;
8156   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8157                "          bbbbbbbbbbbbbbbbbbbbbb);",
8158                Style);
8159   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8160   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8161   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
8162                "    bbbbbbbbbbbbbbbbbbbbbb);",
8163                Style);
8164 }
8165 
8166 TEST_F(FormatTest, BreaksConditionalExpressions) {
8167   verifyFormat(
8168       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8169       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8170       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8171   verifyFormat(
8172       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8173       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8174       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8175   verifyFormat(
8176       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8177       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8178   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
8179                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8180                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8181   verifyFormat(
8182       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
8183       "                                                    : aaaaaaaaaaaaa);");
8184   verifyFormat(
8185       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8186       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8187       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8188       "                   aaaaaaaaaaaaa);");
8189   verifyFormat(
8190       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8191       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8192       "                   aaaaaaaaaaaaa);");
8193   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8194                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8195                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8196                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8197                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8198   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8199                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8200                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8201                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8202                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8203                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8204                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8205   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8206                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8207                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8208                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8209                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8210   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8211                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8212                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8213   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8214                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8215                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8216                "        : aaaaaaaaaaaaaaaa;");
8217   verifyFormat(
8218       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8219       "    ? aaaaaaaaaaaaaaa\n"
8220       "    : aaaaaaaaaaaaaaa;");
8221   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8222                "          aaaaaaaaa\n"
8223                "      ? b\n"
8224                "      : c);");
8225   verifyFormat("return aaaa == bbbb\n"
8226                "           // comment\n"
8227                "           ? aaaa\n"
8228                "           : bbbb;");
8229   verifyFormat("unsigned Indent =\n"
8230                "    format(TheLine.First,\n"
8231                "           IndentForLevel[TheLine.Level] >= 0\n"
8232                "               ? IndentForLevel[TheLine.Level]\n"
8233                "               : TheLine * 2,\n"
8234                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8235                getLLVMStyleWithColumns(60));
8236   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8237                "                  ? aaaaaaaaaaaaaaa\n"
8238                "                  : bbbbbbbbbbbbbbb //\n"
8239                "                        ? ccccccccccccccc\n"
8240                "                        : ddddddddddddddd;");
8241   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
8242                "                  ? aaaaaaaaaaaaaaa\n"
8243                "                  : (bbbbbbbbbbbbbbb //\n"
8244                "                         ? ccccccccccccccc\n"
8245                "                         : ddddddddddddddd);");
8246   verifyFormat(
8247       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8248       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
8249       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
8250       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
8251       "                                      : aaaaaaaaaa;");
8252   verifyFormat(
8253       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8254       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
8255       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8256 
8257   FormatStyle NoBinPacking = getLLVMStyle();
8258   NoBinPacking.BinPackArguments = false;
8259   verifyFormat(
8260       "void f() {\n"
8261       "  g(aaa,\n"
8262       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8263       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8264       "        ? aaaaaaaaaaaaaaa\n"
8265       "        : aaaaaaaaaaaaaaa);\n"
8266       "}",
8267       NoBinPacking);
8268   verifyFormat(
8269       "void f() {\n"
8270       "  g(aaa,\n"
8271       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
8272       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8273       "        ?: aaaaaaaaaaaaaaa);\n"
8274       "}",
8275       NoBinPacking);
8276 
8277   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
8278                "             // comment.\n"
8279                "             ccccccccccccccccccccccccccccccccccccccc\n"
8280                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8281                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
8282 
8283   // Assignments in conditional expressions. Apparently not uncommon :-(.
8284   verifyFormat("return a != b\n"
8285                "           // comment\n"
8286                "           ? a = b\n"
8287                "           : a = b;");
8288   verifyFormat("return a != b\n"
8289                "           // comment\n"
8290                "           ? a = a != b\n"
8291                "                     // comment\n"
8292                "                     ? a = b\n"
8293                "                     : a\n"
8294                "           : a;\n");
8295   verifyFormat("return a != b\n"
8296                "           // comment\n"
8297                "           ? a\n"
8298                "           : a = a != b\n"
8299                "                     // comment\n"
8300                "                     ? a = b\n"
8301                "                     : a;");
8302 
8303   // Chained conditionals
8304   FormatStyle Style = getLLVMStyleWithColumns(70);
8305   Style.AlignOperands = FormatStyle::OAS_Align;
8306   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8307                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8308                "                        : 3333333333333333;",
8309                Style);
8310   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8311                "       : bbbbbbbbbb     ? 2222222222222222\n"
8312                "                        : 3333333333333333;",
8313                Style);
8314   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
8315                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
8316                "                          : 3333333333333333;",
8317                Style);
8318   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8319                "       : bbbbbbbbbbbbbb ? 222222\n"
8320                "                        : 333333;",
8321                Style);
8322   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8323                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8324                "       : cccccccccccccc ? 3333333333333333\n"
8325                "                        : 4444444444444444;",
8326                Style);
8327   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
8328                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8329                "                        : 3333333333333333;",
8330                Style);
8331   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8332                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8333                "                        : (aaa ? bbb : ccc);",
8334                Style);
8335   verifyFormat(
8336       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8337       "                                             : cccccccccccccccccc)\n"
8338       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8339       "                        : 3333333333333333;",
8340       Style);
8341   verifyFormat(
8342       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8343       "                                             : cccccccccccccccccc)\n"
8344       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8345       "                        : 3333333333333333;",
8346       Style);
8347   verifyFormat(
8348       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8349       "                                             : dddddddddddddddddd)\n"
8350       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8351       "                        : 3333333333333333;",
8352       Style);
8353   verifyFormat(
8354       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8355       "                                             : dddddddddddddddddd)\n"
8356       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8357       "                        : 3333333333333333;",
8358       Style);
8359   verifyFormat(
8360       "return aaaaaaaaa        ? 1111111111111111\n"
8361       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8362       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8363       "                                             : dddddddddddddddddd)\n",
8364       Style);
8365   verifyFormat(
8366       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
8367       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8368       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8369       "                                             : cccccccccccccccccc);",
8370       Style);
8371   verifyFormat(
8372       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8373       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8374       "                                             : eeeeeeeeeeeeeeeeee)\n"
8375       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8376       "                        : 3333333333333333;",
8377       Style);
8378   verifyFormat(
8379       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
8380       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
8381       "                                             : eeeeeeeeeeeeeeeeee)\n"
8382       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8383       "                        : 3333333333333333;",
8384       Style);
8385   verifyFormat(
8386       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8387       "                           : cccccccccccc    ? dddddddddddddddddd\n"
8388       "                                             : eeeeeeeeeeeeeeeeee)\n"
8389       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8390       "                        : 3333333333333333;",
8391       Style);
8392   verifyFormat(
8393       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8394       "                                             : cccccccccccccccccc\n"
8395       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8396       "                        : 3333333333333333;",
8397       Style);
8398   verifyFormat(
8399       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8400       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
8401       "                                             : eeeeeeeeeeeeeeeeee\n"
8402       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
8403       "                        : 3333333333333333;",
8404       Style);
8405   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
8406                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
8407                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
8408                "                                   : eeeeeeeeeeeeeeeeee)\n"
8409                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8410                "                             : 3333333333333333;",
8411                Style);
8412   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
8413                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
8414                "             : cccccccccccccccc ? dddddddddddddddddd\n"
8415                "                                : eeeeeeeeeeeeeeeeee\n"
8416                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
8417                "                                 : 3333333333333333;",
8418                Style);
8419 
8420   Style.AlignOperands = FormatStyle::OAS_DontAlign;
8421   Style.BreakBeforeTernaryOperators = false;
8422   // FIXME: Aligning the question marks is weird given DontAlign.
8423   // Consider disabling this alignment in this case. Also check whether this
8424   // will render the adjustment from https://reviews.llvm.org/D82199
8425   // unnecessary.
8426   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
8427                "    bbbb                ? cccccccccccccccccc :\n"
8428                "                          ddddd;\n",
8429                Style);
8430 
8431   EXPECT_EQ(
8432       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8433       "    /*\n"
8434       "     */\n"
8435       "    function() {\n"
8436       "      try {\n"
8437       "        return JJJJJJJJJJJJJJ(\n"
8438       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8439       "      }\n"
8440       "    } :\n"
8441       "    function() {};",
8442       format(
8443           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
8444           "     /*\n"
8445           "      */\n"
8446           "     function() {\n"
8447           "      try {\n"
8448           "        return JJJJJJJJJJJJJJ(\n"
8449           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
8450           "      }\n"
8451           "    } :\n"
8452           "    function() {};",
8453           getGoogleStyle(FormatStyle::LK_JavaScript)));
8454 }
8455 
8456 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
8457   FormatStyle Style = getLLVMStyleWithColumns(70);
8458   Style.BreakBeforeTernaryOperators = false;
8459   verifyFormat(
8460       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8461       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8462       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8463       Style);
8464   verifyFormat(
8465       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
8466       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8467       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8468       Style);
8469   verifyFormat(
8470       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8471       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8472       Style);
8473   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
8474                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8475                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8476                Style);
8477   verifyFormat(
8478       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
8479       "                                                      aaaaaaaaaaaaa);",
8480       Style);
8481   verifyFormat(
8482       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8483       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8484       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8485       "                   aaaaaaaaaaaaa);",
8486       Style);
8487   verifyFormat(
8488       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8489       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8490       "                   aaaaaaaaaaaaa);",
8491       Style);
8492   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8493                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8494                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8495                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8496                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8497                Style);
8498   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8499                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8500                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8501                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
8502                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8503                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8504                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8505                Style);
8506   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8507                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
8508                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8509                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
8510                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8511                Style);
8512   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8513                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8514                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8515                Style);
8516   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
8517                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8518                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
8519                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8520                Style);
8521   verifyFormat(
8522       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8523       "    aaaaaaaaaaaaaaa :\n"
8524       "    aaaaaaaaaaaaaaa;",
8525       Style);
8526   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
8527                "          aaaaaaaaa ?\n"
8528                "      b :\n"
8529                "      c);",
8530                Style);
8531   verifyFormat("unsigned Indent =\n"
8532                "    format(TheLine.First,\n"
8533                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
8534                "               IndentForLevel[TheLine.Level] :\n"
8535                "               TheLine * 2,\n"
8536                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
8537                Style);
8538   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8539                "                  aaaaaaaaaaaaaaa :\n"
8540                "                  bbbbbbbbbbbbbbb ? //\n"
8541                "                      ccccccccccccccc :\n"
8542                "                      ddddddddddddddd;",
8543                Style);
8544   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
8545                "                  aaaaaaaaaaaaaaa :\n"
8546                "                  (bbbbbbbbbbbbbbb ? //\n"
8547                "                       ccccccccccccccc :\n"
8548                "                       ddddddddddddddd);",
8549                Style);
8550   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8551                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
8552                "            ccccccccccccccccccccccccccc;",
8553                Style);
8554   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
8555                "           aaaaa :\n"
8556                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
8557                Style);
8558 
8559   // Chained conditionals
8560   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8561                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8562                "                          3333333333333333;",
8563                Style);
8564   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8565                "       bbbbbbbbbb       ? 2222222222222222 :\n"
8566                "                          3333333333333333;",
8567                Style);
8568   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
8569                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8570                "                          3333333333333333;",
8571                Style);
8572   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8573                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
8574                "                          333333;",
8575                Style);
8576   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8577                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8578                "       cccccccccccccccc ? 3333333333333333 :\n"
8579                "                          4444444444444444;",
8580                Style);
8581   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
8582                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8583                "                          3333333333333333;",
8584                Style);
8585   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8586                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8587                "                          (aaa ? bbb : ccc);",
8588                Style);
8589   verifyFormat(
8590       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8591       "                                               cccccccccccccccccc) :\n"
8592       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8593       "                          3333333333333333;",
8594       Style);
8595   verifyFormat(
8596       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8597       "                                               cccccccccccccccccc) :\n"
8598       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8599       "                          3333333333333333;",
8600       Style);
8601   verifyFormat(
8602       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8603       "                                               dddddddddddddddddd) :\n"
8604       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8605       "                          3333333333333333;",
8606       Style);
8607   verifyFormat(
8608       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8609       "                                               dddddddddddddddddd) :\n"
8610       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8611       "                          3333333333333333;",
8612       Style);
8613   verifyFormat(
8614       "return aaaaaaaaa        ? 1111111111111111 :\n"
8615       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8616       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8617       "                                               dddddddddddddddddd)\n",
8618       Style);
8619   verifyFormat(
8620       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
8621       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8622       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8623       "                                               cccccccccccccccccc);",
8624       Style);
8625   verifyFormat(
8626       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8627       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8628       "                                               eeeeeeeeeeeeeeeeee) :\n"
8629       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8630       "                          3333333333333333;",
8631       Style);
8632   verifyFormat(
8633       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8634       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
8635       "                                               eeeeeeeeeeeeeeeeee) :\n"
8636       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8637       "                          3333333333333333;",
8638       Style);
8639   verifyFormat(
8640       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
8641       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
8642       "                                               eeeeeeeeeeeeeeeeee) :\n"
8643       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8644       "                          3333333333333333;",
8645       Style);
8646   verifyFormat(
8647       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8648       "                                               cccccccccccccccccc :\n"
8649       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8650       "                          3333333333333333;",
8651       Style);
8652   verifyFormat(
8653       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8654       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
8655       "                                               eeeeeeeeeeeeeeeeee :\n"
8656       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8657       "                          3333333333333333;",
8658       Style);
8659   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8660                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8661                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
8662                "                                 eeeeeeeeeeeeeeeeee) :\n"
8663                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8664                "                               3333333333333333;",
8665                Style);
8666   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
8667                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
8668                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
8669                "                                  eeeeeeeeeeeeeeeeee :\n"
8670                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
8671                "                               3333333333333333;",
8672                Style);
8673 }
8674 
8675 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
8676   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
8677                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
8678   verifyFormat("bool a = true, b = false;");
8679 
8680   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8681                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
8682                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
8683                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
8684   verifyFormat(
8685       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
8686       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
8687       "     d = e && f;");
8688   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
8689                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
8690   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8691                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
8692   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
8693                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
8694 
8695   FormatStyle Style = getGoogleStyle();
8696   Style.PointerAlignment = FormatStyle::PAS_Left;
8697   Style.DerivePointerAlignment = false;
8698   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8699                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
8700                "    *b = bbbbbbbbbbbbbbbbbbb;",
8701                Style);
8702   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
8703                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
8704                Style);
8705   verifyFormat("vector<int*> a, b;", Style);
8706   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8707   verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
8708   verifyFormat("if (int *p, *q; p != q) {\n  p = p->next;\n}", Style);
8709   verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n  p = p->next;\n}",
8710                Style);
8711   verifyFormat("switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8712                Style);
8713   verifyFormat(
8714       "/*comment*/ switch (int *p, *q; p != q) {\n  default:\n    break;\n}",
8715       Style);
8716 
8717   verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
8718   verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
8719   verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
8720   verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
8721   verifyFormat("switch ([](int* p, int* q) {}()) {\n  default:\n    break;\n}",
8722                Style);
8723 }
8724 
8725 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
8726   verifyFormat("arr[foo ? bar : baz];");
8727   verifyFormat("f()[foo ? bar : baz];");
8728   verifyFormat("(a + b)[foo ? bar : baz];");
8729   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
8730 }
8731 
8732 TEST_F(FormatTest, AlignsStringLiterals) {
8733   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
8734                "                                      \"short literal\");");
8735   verifyFormat(
8736       "looooooooooooooooooooooooongFunction(\n"
8737       "    \"short literal\"\n"
8738       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
8739   verifyFormat("someFunction(\"Always break between multi-line\"\n"
8740                "             \" string literals\",\n"
8741                "             and, other, parameters);");
8742   EXPECT_EQ("fun + \"1243\" /* comment */\n"
8743             "      \"5678\";",
8744             format("fun + \"1243\" /* comment */\n"
8745                    "    \"5678\";",
8746                    getLLVMStyleWithColumns(28)));
8747   EXPECT_EQ(
8748       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8749       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
8750       "         \"aaaaaaaaaaaaaaaa\";",
8751       format("aaaaaa ="
8752              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8753              "aaaaaaaaaaaaaaaaaaaaa\" "
8754              "\"aaaaaaaaaaaaaaaa\";"));
8755   verifyFormat("a = a + \"a\"\n"
8756                "        \"a\"\n"
8757                "        \"a\";");
8758   verifyFormat("f(\"a\", \"b\"\n"
8759                "       \"c\");");
8760 
8761   verifyFormat(
8762       "#define LL_FORMAT \"ll\"\n"
8763       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
8764       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
8765 
8766   verifyFormat("#define A(X)          \\\n"
8767                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
8768                "  \"ccccc\"",
8769                getLLVMStyleWithColumns(23));
8770   verifyFormat("#define A \"def\"\n"
8771                "f(\"abc\" A \"ghi\"\n"
8772                "  \"jkl\");");
8773 
8774   verifyFormat("f(L\"a\"\n"
8775                "  L\"b\");");
8776   verifyFormat("#define A(X)            \\\n"
8777                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
8778                "  L\"ccccc\"",
8779                getLLVMStyleWithColumns(25));
8780 
8781   verifyFormat("f(@\"a\"\n"
8782                "  @\"b\");");
8783   verifyFormat("NSString s = @\"a\"\n"
8784                "             @\"b\"\n"
8785                "             @\"c\";");
8786   verifyFormat("NSString s = @\"a\"\n"
8787                "              \"b\"\n"
8788                "              \"c\";");
8789 }
8790 
8791 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8792   FormatStyle Style = getLLVMStyle();
8793   // No declarations or definitions should be moved to own line.
8794   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8795   verifyFormat("class A {\n"
8796                "  int f() { return 1; }\n"
8797                "  int g();\n"
8798                "};\n"
8799                "int f() { return 1; }\n"
8800                "int g();\n",
8801                Style);
8802 
8803   // All declarations and definitions should have the return type moved to its
8804   // own line.
8805   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8806   Style.TypenameMacros = {"LIST"};
8807   verifyFormat("SomeType\n"
8808                "funcdecl(LIST(uint64_t));",
8809                Style);
8810   verifyFormat("class E {\n"
8811                "  int\n"
8812                "  f() {\n"
8813                "    return 1;\n"
8814                "  }\n"
8815                "  int\n"
8816                "  g();\n"
8817                "};\n"
8818                "int\n"
8819                "f() {\n"
8820                "  return 1;\n"
8821                "}\n"
8822                "int\n"
8823                "g();\n",
8824                Style);
8825 
8826   // Top-level definitions, and no kinds of declarations should have the
8827   // return type moved to its own line.
8828   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8829   verifyFormat("class B {\n"
8830                "  int f() { return 1; }\n"
8831                "  int g();\n"
8832                "};\n"
8833                "int\n"
8834                "f() {\n"
8835                "  return 1;\n"
8836                "}\n"
8837                "int g();\n",
8838                Style);
8839 
8840   // Top-level definitions and declarations should have the return type moved
8841   // to its own line.
8842   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8843   verifyFormat("class C {\n"
8844                "  int f() { return 1; }\n"
8845                "  int g();\n"
8846                "};\n"
8847                "int\n"
8848                "f() {\n"
8849                "  return 1;\n"
8850                "}\n"
8851                "int\n"
8852                "g();\n",
8853                Style);
8854 
8855   // All definitions should have the return type moved to its own line, but no
8856   // kinds of declarations.
8857   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8858   verifyFormat("class D {\n"
8859                "  int\n"
8860                "  f() {\n"
8861                "    return 1;\n"
8862                "  }\n"
8863                "  int g();\n"
8864                "};\n"
8865                "int\n"
8866                "f() {\n"
8867                "  return 1;\n"
8868                "}\n"
8869                "int g();\n",
8870                Style);
8871   verifyFormat("const char *\n"
8872                "f(void) {\n" // Break here.
8873                "  return \"\";\n"
8874                "}\n"
8875                "const char *bar(void);\n", // No break here.
8876                Style);
8877   verifyFormat("template <class T>\n"
8878                "T *\n"
8879                "f(T &c) {\n" // Break here.
8880                "  return NULL;\n"
8881                "}\n"
8882                "template <class T> T *f(T &c);\n", // No break here.
8883                Style);
8884   verifyFormat("class C {\n"
8885                "  int\n"
8886                "  operator+() {\n"
8887                "    return 1;\n"
8888                "  }\n"
8889                "  int\n"
8890                "  operator()() {\n"
8891                "    return 1;\n"
8892                "  }\n"
8893                "};\n",
8894                Style);
8895   verifyFormat("void\n"
8896                "A::operator()() {}\n"
8897                "void\n"
8898                "A::operator>>() {}\n"
8899                "void\n"
8900                "A::operator+() {}\n"
8901                "void\n"
8902                "A::operator*() {}\n"
8903                "void\n"
8904                "A::operator->() {}\n"
8905                "void\n"
8906                "A::operator void *() {}\n"
8907                "void\n"
8908                "A::operator void &() {}\n"
8909                "void\n"
8910                "A::operator void &&() {}\n"
8911                "void\n"
8912                "A::operator char *() {}\n"
8913                "void\n"
8914                "A::operator[]() {}\n"
8915                "void\n"
8916                "A::operator!() {}\n"
8917                "void\n"
8918                "A::operator**() {}\n"
8919                "void\n"
8920                "A::operator<Foo> *() {}\n"
8921                "void\n"
8922                "A::operator<Foo> **() {}\n"
8923                "void\n"
8924                "A::operator<Foo> &() {}\n"
8925                "void\n"
8926                "A::operator void **() {}\n",
8927                Style);
8928   verifyFormat("constexpr auto\n"
8929                "operator()() const -> reference {}\n"
8930                "constexpr auto\n"
8931                "operator>>() const -> reference {}\n"
8932                "constexpr auto\n"
8933                "operator+() const -> reference {}\n"
8934                "constexpr auto\n"
8935                "operator*() const -> reference {}\n"
8936                "constexpr auto\n"
8937                "operator->() const -> reference {}\n"
8938                "constexpr auto\n"
8939                "operator++() const -> reference {}\n"
8940                "constexpr auto\n"
8941                "operator void *() const -> reference {}\n"
8942                "constexpr auto\n"
8943                "operator void **() const -> reference {}\n"
8944                "constexpr auto\n"
8945                "operator void *() const -> reference {}\n"
8946                "constexpr auto\n"
8947                "operator void &() const -> reference {}\n"
8948                "constexpr auto\n"
8949                "operator void &&() const -> reference {}\n"
8950                "constexpr auto\n"
8951                "operator char *() const -> reference {}\n"
8952                "constexpr auto\n"
8953                "operator!() const -> reference {}\n"
8954                "constexpr auto\n"
8955                "operator[]() const -> reference {}\n",
8956                Style);
8957   verifyFormat("void *operator new(std::size_t s);", // No break here.
8958                Style);
8959   verifyFormat("void *\n"
8960                "operator new(std::size_t s) {}",
8961                Style);
8962   verifyFormat("void *\n"
8963                "operator delete[](void *ptr) {}",
8964                Style);
8965   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8966   verifyFormat("const char *\n"
8967                "f(void)\n" // Break here.
8968                "{\n"
8969                "  return \"\";\n"
8970                "}\n"
8971                "const char *bar(void);\n", // No break here.
8972                Style);
8973   verifyFormat("template <class T>\n"
8974                "T *\n"     // Problem here: no line break
8975                "f(T &c)\n" // Break here.
8976                "{\n"
8977                "  return NULL;\n"
8978                "}\n"
8979                "template <class T> T *f(T &c);\n", // No break here.
8980                Style);
8981   verifyFormat("int\n"
8982                "foo(A<bool> a)\n"
8983                "{\n"
8984                "  return a;\n"
8985                "}\n",
8986                Style);
8987   verifyFormat("int\n"
8988                "foo(A<8> a)\n"
8989                "{\n"
8990                "  return a;\n"
8991                "}\n",
8992                Style);
8993   verifyFormat("int\n"
8994                "foo(A<B<bool>, 8> a)\n"
8995                "{\n"
8996                "  return a;\n"
8997                "}\n",
8998                Style);
8999   verifyFormat("int\n"
9000                "foo(A<B<8>, bool> a)\n"
9001                "{\n"
9002                "  return a;\n"
9003                "}\n",
9004                Style);
9005   verifyFormat("int\n"
9006                "foo(A<B<bool>, bool> a)\n"
9007                "{\n"
9008                "  return a;\n"
9009                "}\n",
9010                Style);
9011   verifyFormat("int\n"
9012                "foo(A<B<8>, 8> a)\n"
9013                "{\n"
9014                "  return a;\n"
9015                "}\n",
9016                Style);
9017 
9018   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9019   Style.BraceWrapping.AfterFunction = true;
9020   verifyFormat("int f(i);\n" // No break here.
9021                "int\n"       // Break here.
9022                "f(i)\n"
9023                "{\n"
9024                "  return i + 1;\n"
9025                "}\n"
9026                "int\n" // Break here.
9027                "f(i)\n"
9028                "{\n"
9029                "  return i + 1;\n"
9030                "};",
9031                Style);
9032   verifyFormat("int f(a, b, c);\n" // No break here.
9033                "int\n"             // Break here.
9034                "f(a, b, c)\n"      // Break here.
9035                "short a, b;\n"
9036                "float c;\n"
9037                "{\n"
9038                "  return a + b < c;\n"
9039                "}\n"
9040                "int\n"        // Break here.
9041                "f(a, b, c)\n" // Break here.
9042                "short a, b;\n"
9043                "float c;\n"
9044                "{\n"
9045                "  return a + b < c;\n"
9046                "};",
9047                Style);
9048   verifyFormat("byte *\n" // Break here.
9049                "f(a)\n"   // Break here.
9050                "byte a[];\n"
9051                "{\n"
9052                "  return a;\n"
9053                "}",
9054                Style);
9055   verifyFormat("bool f(int a, int) override;\n"
9056                "Bar g(int a, Bar) final;\n"
9057                "Bar h(a, Bar) final;",
9058                Style);
9059   verifyFormat("int\n"
9060                "f(a)",
9061                Style);
9062   verifyFormat("bool\n"
9063                "f(size_t = 0, bool b = false)\n"
9064                "{\n"
9065                "  return !b;\n"
9066                "}",
9067                Style);
9068 
9069   // The return breaking style doesn't affect:
9070   // * function and object definitions with attribute-like macros
9071   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9072                "    ABSL_GUARDED_BY(mutex) = {};",
9073                getGoogleStyleWithColumns(40));
9074   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9075                "    ABSL_GUARDED_BY(mutex);  // comment",
9076                getGoogleStyleWithColumns(40));
9077   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
9078                "    ABSL_GUARDED_BY(mutex1)\n"
9079                "        ABSL_GUARDED_BY(mutex2);",
9080                getGoogleStyleWithColumns(40));
9081   verifyFormat("Tttttt f(int a, int b)\n"
9082                "    ABSL_GUARDED_BY(mutex1)\n"
9083                "        ABSL_GUARDED_BY(mutex2);",
9084                getGoogleStyleWithColumns(40));
9085   // * typedefs
9086   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
9087 
9088   Style = getGNUStyle();
9089 
9090   // Test for comments at the end of function declarations.
9091   verifyFormat("void\n"
9092                "foo (int a, /*abc*/ int b) // def\n"
9093                "{\n"
9094                "}\n",
9095                Style);
9096 
9097   verifyFormat("void\n"
9098                "foo (int a, /* abc */ int b) /* def */\n"
9099                "{\n"
9100                "}\n",
9101                Style);
9102 
9103   // Definitions that should not break after return type
9104   verifyFormat("void foo (int a, int b); // def\n", Style);
9105   verifyFormat("void foo (int a, int b); /* def */\n", Style);
9106   verifyFormat("void foo (int a, int b);\n", Style);
9107 }
9108 
9109 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
9110   FormatStyle NoBreak = getLLVMStyle();
9111   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
9112   FormatStyle Break = getLLVMStyle();
9113   Break.AlwaysBreakBeforeMultilineStrings = true;
9114   verifyFormat("aaaa = \"bbbb\"\n"
9115                "       \"cccc\";",
9116                NoBreak);
9117   verifyFormat("aaaa =\n"
9118                "    \"bbbb\"\n"
9119                "    \"cccc\";",
9120                Break);
9121   verifyFormat("aaaa(\"bbbb\"\n"
9122                "     \"cccc\");",
9123                NoBreak);
9124   verifyFormat("aaaa(\n"
9125                "    \"bbbb\"\n"
9126                "    \"cccc\");",
9127                Break);
9128   verifyFormat("aaaa(qqq, \"bbbb\"\n"
9129                "          \"cccc\");",
9130                NoBreak);
9131   verifyFormat("aaaa(qqq,\n"
9132                "     \"bbbb\"\n"
9133                "     \"cccc\");",
9134                Break);
9135   verifyFormat("aaaa(qqq,\n"
9136                "     L\"bbbb\"\n"
9137                "     L\"cccc\");",
9138                Break);
9139   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
9140                "                      \"bbbb\"));",
9141                Break);
9142   verifyFormat("string s = someFunction(\n"
9143                "    \"abc\"\n"
9144                "    \"abc\");",
9145                Break);
9146 
9147   // As we break before unary operators, breaking right after them is bad.
9148   verifyFormat("string foo = abc ? \"x\"\n"
9149                "                   \"blah blah blah blah blah blah\"\n"
9150                "                 : \"y\";",
9151                Break);
9152 
9153   // Don't break if there is no column gain.
9154   verifyFormat("f(\"aaaa\"\n"
9155                "  \"bbbb\");",
9156                Break);
9157 
9158   // Treat literals with escaped newlines like multi-line string literals.
9159   EXPECT_EQ("x = \"a\\\n"
9160             "b\\\n"
9161             "c\";",
9162             format("x = \"a\\\n"
9163                    "b\\\n"
9164                    "c\";",
9165                    NoBreak));
9166   EXPECT_EQ("xxxx =\n"
9167             "    \"a\\\n"
9168             "b\\\n"
9169             "c\";",
9170             format("xxxx = \"a\\\n"
9171                    "b\\\n"
9172                    "c\";",
9173                    Break));
9174 
9175   EXPECT_EQ("NSString *const kString =\n"
9176             "    @\"aaaa\"\n"
9177             "    @\"bbbb\";",
9178             format("NSString *const kString = @\"aaaa\"\n"
9179                    "@\"bbbb\";",
9180                    Break));
9181 
9182   Break.ColumnLimit = 0;
9183   verifyFormat("const char *hello = \"hello llvm\";", Break);
9184 }
9185 
9186 TEST_F(FormatTest, AlignsPipes) {
9187   verifyFormat(
9188       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9189       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9190       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9191   verifyFormat(
9192       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
9193       "                     << aaaaaaaaaaaaaaaaaaaa;");
9194   verifyFormat(
9195       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9196       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9197   verifyFormat(
9198       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
9199       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9200   verifyFormat(
9201       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
9202       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
9203       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
9204   verifyFormat(
9205       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9206       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9207       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9208   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9209                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9210                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9211                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9212   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
9213                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
9214   verifyFormat(
9215       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9216       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9217   verifyFormat(
9218       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
9219       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
9220 
9221   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
9222                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
9223   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9224                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9225                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
9226                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
9227   verifyFormat("LOG_IF(aaa == //\n"
9228                "       bbb)\n"
9229                "    << a << b;");
9230 
9231   // But sometimes, breaking before the first "<<" is desirable.
9232   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9233                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
9234   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
9235                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9236                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9237   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
9238                "    << BEF << IsTemplate << Description << E->getType();");
9239   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9240                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9241                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9242   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
9243                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9244                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9245                "    << aaa;");
9246 
9247   verifyFormat(
9248       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9249       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9250 
9251   // Incomplete string literal.
9252   EXPECT_EQ("llvm::errs() << \"\n"
9253             "             << a;",
9254             format("llvm::errs() << \"\n<<a;"));
9255 
9256   verifyFormat("void f() {\n"
9257                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
9258                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
9259                "}");
9260 
9261   // Handle 'endl'.
9262   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
9263                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9264   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
9265 
9266   // Handle '\n'.
9267   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
9268                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9269   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
9270                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
9271   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
9272                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
9273   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
9274 }
9275 
9276 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
9277   verifyFormat("return out << \"somepacket = {\\n\"\n"
9278                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
9279                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
9280                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
9281                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
9282                "           << \"}\";");
9283 
9284   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9285                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
9286                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
9287   verifyFormat(
9288       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
9289       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
9290       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
9291       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
9292       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
9293   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
9294                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9295   verifyFormat(
9296       "void f() {\n"
9297       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
9298       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
9299       "}");
9300 
9301   // Breaking before the first "<<" is generally not desirable.
9302   verifyFormat(
9303       "llvm::errs()\n"
9304       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9305       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9306       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9307       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9308       getLLVMStyleWithColumns(70));
9309   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9310                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9311                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9312                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9313                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
9314                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
9315                getLLVMStyleWithColumns(70));
9316 
9317   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9318                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
9319                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
9320   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9321                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
9322                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
9323   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
9324                "           (aaaa + aaaa);",
9325                getLLVMStyleWithColumns(40));
9326   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
9327                "                  (aaaaaaa + aaaaa));",
9328                getLLVMStyleWithColumns(40));
9329   verifyFormat(
9330       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
9331       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
9332       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
9333 }
9334 
9335 TEST_F(FormatTest, UnderstandsEquals) {
9336   verifyFormat(
9337       "aaaaaaaaaaaaaaaaa =\n"
9338       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9339   verifyFormat(
9340       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9341       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9342   verifyFormat(
9343       "if (a) {\n"
9344       "  f();\n"
9345       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9346       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
9347       "}");
9348 
9349   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9350                "        100000000 + 10000000) {\n}");
9351 }
9352 
9353 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
9354   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9355                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
9356 
9357   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
9358                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
9359 
9360   verifyFormat(
9361       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
9362       "                                                          Parameter2);");
9363 
9364   verifyFormat(
9365       "ShortObject->shortFunction(\n"
9366       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
9367       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
9368 
9369   verifyFormat("loooooooooooooongFunction(\n"
9370                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
9371 
9372   verifyFormat(
9373       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
9374       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
9375 
9376   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9377                "    .WillRepeatedly(Return(SomeValue));");
9378   verifyFormat("void f() {\n"
9379                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
9380                "      .Times(2)\n"
9381                "      .WillRepeatedly(Return(SomeValue));\n"
9382                "}");
9383   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
9384                "    ccccccccccccccccccccccc);");
9385   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9386                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9387                "          .aaaaa(aaaaa),\n"
9388                "      aaaaaaaaaaaaaaaaaaaaa);");
9389   verifyFormat("void f() {\n"
9390                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9391                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
9392                "}");
9393   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9394                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9395                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9396                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9397                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9398   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9399                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9400                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9401                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
9402                "}");
9403 
9404   // Here, it is not necessary to wrap at "." or "->".
9405   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
9406                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
9407   verifyFormat(
9408       "aaaaaaaaaaa->aaaaaaaaa(\n"
9409       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9410       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
9411 
9412   verifyFormat(
9413       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9414       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
9415   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
9416                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9417   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
9418                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
9419 
9420   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9421                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9422                "    .a();");
9423 
9424   FormatStyle NoBinPacking = getLLVMStyle();
9425   NoBinPacking.BinPackParameters = false;
9426   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9427                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
9428                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
9429                "                         aaaaaaaaaaaaaaaaaaa,\n"
9430                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
9431                NoBinPacking);
9432 
9433   // If there is a subsequent call, change to hanging indentation.
9434   verifyFormat(
9435       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9436       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
9437       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9438   verifyFormat(
9439       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9440       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
9441   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9442                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9443                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9444   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9445                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9446                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9447 }
9448 
9449 TEST_F(FormatTest, WrapsTemplateDeclarations) {
9450   verifyFormat("template <typename T>\n"
9451                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9452   verifyFormat("template <typename T>\n"
9453                "// T should be one of {A, B}.\n"
9454                "virtual void loooooooooooongFunction(int Param1, int Param2);");
9455   verifyFormat(
9456       "template <typename T>\n"
9457       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
9458   verifyFormat("template <typename T>\n"
9459                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
9460                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
9461   verifyFormat(
9462       "template <typename T>\n"
9463       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
9464       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
9465   verifyFormat(
9466       "template <typename T>\n"
9467       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
9468       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
9469       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9470   verifyFormat("template <typename T>\n"
9471                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9472                "    int aaaaaaaaaaaaaaaaaaaaaa);");
9473   verifyFormat(
9474       "template <typename T1, typename T2 = char, typename T3 = char,\n"
9475       "          typename T4 = char>\n"
9476       "void f();");
9477   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
9478                "          template <typename> class cccccccccccccccccccccc,\n"
9479                "          typename ddddddddddddd>\n"
9480                "class C {};");
9481   verifyFormat(
9482       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
9483       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9484 
9485   verifyFormat("void f() {\n"
9486                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
9487                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
9488                "}");
9489 
9490   verifyFormat("template <typename T> class C {};");
9491   verifyFormat("template <typename T> void f();");
9492   verifyFormat("template <typename T> void f() {}");
9493   verifyFormat(
9494       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9495       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9496       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
9497       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
9498       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9499       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
9500       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
9501       getLLVMStyleWithColumns(72));
9502   EXPECT_EQ("static_cast<A< //\n"
9503             "    B> *>(\n"
9504             "\n"
9505             ");",
9506             format("static_cast<A<//\n"
9507                    "    B>*>(\n"
9508                    "\n"
9509                    "    );"));
9510   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9511                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
9512 
9513   FormatStyle AlwaysBreak = getLLVMStyle();
9514   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9515   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
9516   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
9517   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
9518   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9519                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9520                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
9521   verifyFormat("template <template <typename> class Fooooooo,\n"
9522                "          template <typename> class Baaaaaaar>\n"
9523                "struct C {};",
9524                AlwaysBreak);
9525   verifyFormat("template <typename T> // T can be A, B or C.\n"
9526                "struct C {};",
9527                AlwaysBreak);
9528   verifyFormat("template <enum E> class A {\n"
9529                "public:\n"
9530                "  E *f();\n"
9531                "};");
9532 
9533   FormatStyle NeverBreak = getLLVMStyle();
9534   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
9535   verifyFormat("template <typename T> class C {};", NeverBreak);
9536   verifyFormat("template <typename T> void f();", NeverBreak);
9537   verifyFormat("template <typename T> void f() {}", NeverBreak);
9538   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9539                "bbbbbbbbbbbbbbbbbbbb) {}",
9540                NeverBreak);
9541   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9542                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
9543                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
9544                NeverBreak);
9545   verifyFormat("template <template <typename> class Fooooooo,\n"
9546                "          template <typename> class Baaaaaaar>\n"
9547                "struct C {};",
9548                NeverBreak);
9549   verifyFormat("template <typename T> // T can be A, B or C.\n"
9550                "struct C {};",
9551                NeverBreak);
9552   verifyFormat("template <enum E> class A {\n"
9553                "public:\n"
9554                "  E *f();\n"
9555                "};",
9556                NeverBreak);
9557   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
9558   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
9559                "bbbbbbbbbbbbbbbbbbbb) {}",
9560                NeverBreak);
9561 }
9562 
9563 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
9564   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9565   Style.ColumnLimit = 60;
9566   EXPECT_EQ("// Baseline - no comments.\n"
9567             "template <\n"
9568             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9569             "void f() {}",
9570             format("// Baseline - no comments.\n"
9571                    "template <\n"
9572                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
9573                    "void f() {}",
9574                    Style));
9575 
9576   EXPECT_EQ("template <\n"
9577             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9578             "void f() {}",
9579             format("template <\n"
9580                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9581                    "void f() {}",
9582                    Style));
9583 
9584   EXPECT_EQ(
9585       "template <\n"
9586       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
9587       "void f() {}",
9588       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
9589              "void f() {}",
9590              Style));
9591 
9592   EXPECT_EQ(
9593       "template <\n"
9594       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
9595       "                                               // multiline\n"
9596       "void f() {}",
9597       format("template <\n"
9598              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
9599              "                                              // multiline\n"
9600              "void f() {}",
9601              Style));
9602 
9603   EXPECT_EQ(
9604       "template <typename aaaaaaaaaa<\n"
9605       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
9606       "void f() {}",
9607       format(
9608           "template <\n"
9609           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
9610           "void f() {}",
9611           Style));
9612 }
9613 
9614 TEST_F(FormatTest, WrapsTemplateParameters) {
9615   FormatStyle Style = getLLVMStyle();
9616   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9617   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9618   verifyFormat(
9619       "template <typename... a> struct q {};\n"
9620       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9621       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9622       "    y;",
9623       Style);
9624   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9625   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9626   verifyFormat(
9627       "template <typename... a> struct r {};\n"
9628       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
9629       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
9630       "    y;",
9631       Style);
9632   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9633   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9634   verifyFormat("template <typename... a> struct s {};\n"
9635                "extern s<\n"
9636                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9637                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9638                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9639                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9640                "    y;",
9641                Style);
9642   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9643   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9644   verifyFormat("template <typename... a> struct t {};\n"
9645                "extern t<\n"
9646                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9647                "aaaaaaaaaaaaaaaaaaaaaa,\n"
9648                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
9649                "aaaaaaaaaaaaaaaaaaaaaa>\n"
9650                "    y;",
9651                Style);
9652 }
9653 
9654 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
9655   verifyFormat(
9656       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9657       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9658   verifyFormat(
9659       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9660       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9661       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
9662 
9663   // FIXME: Should we have the extra indent after the second break?
9664   verifyFormat(
9665       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9666       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9667       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9668 
9669   verifyFormat(
9670       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
9671       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
9672 
9673   // Breaking at nested name specifiers is generally not desirable.
9674   verifyFormat(
9675       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9676       "    aaaaaaaaaaaaaaaaaaaaaaa);");
9677 
9678   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
9679                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9680                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9681                "                   aaaaaaaaaaaaaaaaaaaaa);",
9682                getLLVMStyleWithColumns(74));
9683 
9684   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
9685                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9686                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
9687 }
9688 
9689 TEST_F(FormatTest, UnderstandsTemplateParameters) {
9690   verifyFormat("A<int> a;");
9691   verifyFormat("A<A<A<int>>> a;");
9692   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
9693   verifyFormat("bool x = a < 1 || 2 > a;");
9694   verifyFormat("bool x = 5 < f<int>();");
9695   verifyFormat("bool x = f<int>() > 5;");
9696   verifyFormat("bool x = 5 < a<int>::x;");
9697   verifyFormat("bool x = a < 4 ? a > 2 : false;");
9698   verifyFormat("bool x = f() ? a < 2 : a > 2;");
9699 
9700   verifyGoogleFormat("A<A<int>> a;");
9701   verifyGoogleFormat("A<A<A<int>>> a;");
9702   verifyGoogleFormat("A<A<A<A<int>>>> a;");
9703   verifyGoogleFormat("A<A<int> > a;");
9704   verifyGoogleFormat("A<A<A<int> > > a;");
9705   verifyGoogleFormat("A<A<A<A<int> > > > a;");
9706   verifyGoogleFormat("A<::A<int>> a;");
9707   verifyGoogleFormat("A<::A> a;");
9708   verifyGoogleFormat("A< ::A> a;");
9709   verifyGoogleFormat("A< ::A<int> > a;");
9710   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
9711   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
9712   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
9713   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
9714   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
9715             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
9716 
9717   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
9718 
9719   // template closer followed by a token that starts with > or =
9720   verifyFormat("bool b = a<1> > 1;");
9721   verifyFormat("bool b = a<1> >= 1;");
9722   verifyFormat("int i = a<1> >> 1;");
9723   FormatStyle Style = getLLVMStyle();
9724   Style.SpaceBeforeAssignmentOperators = false;
9725   verifyFormat("bool b= a<1> == 1;", Style);
9726   verifyFormat("a<int> = 1;", Style);
9727   verifyFormat("a<int> >>= 1;", Style);
9728 
9729   verifyFormat("test < a | b >> c;");
9730   verifyFormat("test<test<a | b>> c;");
9731   verifyFormat("test >> a >> b;");
9732   verifyFormat("test << a >> b;");
9733 
9734   verifyFormat("f<int>();");
9735   verifyFormat("template <typename T> void f() {}");
9736   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
9737   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
9738                "sizeof(char)>::type>;");
9739   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
9740   verifyFormat("f(a.operator()<A>());");
9741   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9742                "      .template operator()<A>());",
9743                getLLVMStyleWithColumns(35));
9744   verifyFormat("bool_constant<a && noexcept(f())>");
9745   verifyFormat("bool_constant<a || noexcept(f())>");
9746 
9747   // Not template parameters.
9748   verifyFormat("return a < b && c > d;");
9749   verifyFormat("void f() {\n"
9750                "  while (a < b && c > d) {\n"
9751                "  }\n"
9752                "}");
9753   verifyFormat("template <typename... Types>\n"
9754                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
9755 
9756   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9757                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
9758                getLLVMStyleWithColumns(60));
9759   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
9760   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
9761   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
9762   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
9763 }
9764 
9765 TEST_F(FormatTest, UnderstandsShiftOperators) {
9766   verifyFormat("if (i < x >> 1)");
9767   verifyFormat("while (i < x >> 1)");
9768   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
9769   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
9770   verifyFormat(
9771       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
9772   verifyFormat("Foo.call<Bar<Function>>()");
9773   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
9774   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
9775                "++i, v = v >> 1)");
9776   verifyFormat("if (w<u<v<x>>, 1>::t)");
9777 }
9778 
9779 TEST_F(FormatTest, BitshiftOperatorWidth) {
9780   EXPECT_EQ("int a = 1 << 2; /* foo\n"
9781             "                   bar */",
9782             format("int    a=1<<2;  /* foo\n"
9783                    "                   bar */"));
9784 
9785   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9786             "                     bar */",
9787             format("int  b  =256>>1 ;  /* foo\n"
9788                    "                      bar */"));
9789 }
9790 
9791 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9792   verifyFormat("COMPARE(a, ==, b);");
9793   verifyFormat("auto s = sizeof...(Ts) - 1;");
9794 }
9795 
9796 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9797   verifyFormat("int A::*x;");
9798   verifyFormat("int (S::*func)(void *);");
9799   verifyFormat("void f() { int (S::*func)(void *); }");
9800   verifyFormat("typedef bool *(Class::*Member)() const;");
9801   verifyFormat("void f() {\n"
9802                "  (a->*f)();\n"
9803                "  a->*x;\n"
9804                "  (a.*f)();\n"
9805                "  ((*a).*f)();\n"
9806                "  a.*x;\n"
9807                "}");
9808   verifyFormat("void f() {\n"
9809                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9810                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9811                "}");
9812   verifyFormat(
9813       "(aaaaaaaaaa->*bbbbbbb)(\n"
9814       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9815   FormatStyle Style = getLLVMStyle();
9816   Style.PointerAlignment = FormatStyle::PAS_Left;
9817   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9818 }
9819 
9820 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9821   verifyFormat("int a = -2;");
9822   verifyFormat("f(-1, -2, -3);");
9823   verifyFormat("a[-1] = 5;");
9824   verifyFormat("int a = 5 + -2;");
9825   verifyFormat("if (i == -1) {\n}");
9826   verifyFormat("if (i != -1) {\n}");
9827   verifyFormat("if (i > -1) {\n}");
9828   verifyFormat("if (i < -1) {\n}");
9829   verifyFormat("++(a->f());");
9830   verifyFormat("--(a->f());");
9831   verifyFormat("(a->f())++;");
9832   verifyFormat("a[42]++;");
9833   verifyFormat("if (!(a->f())) {\n}");
9834   verifyFormat("if (!+i) {\n}");
9835   verifyFormat("~&a;");
9836   verifyFormat("for (x = 0; -10 < x; --x) {\n}");
9837   verifyFormat("sizeof -x");
9838   verifyFormat("sizeof +x");
9839   verifyFormat("sizeof *x");
9840   verifyFormat("sizeof &x");
9841   verifyFormat("delete +x;");
9842   verifyFormat("co_await +x;");
9843   verifyFormat("case *x:");
9844   verifyFormat("case &x:");
9845 
9846   verifyFormat("a-- > b;");
9847   verifyFormat("b ? -a : c;");
9848   verifyFormat("n * sizeof char16;");
9849   verifyFormat("n * alignof char16;", getGoogleStyle());
9850   verifyFormat("sizeof(char);");
9851   verifyFormat("alignof(char);", getGoogleStyle());
9852 
9853   verifyFormat("return -1;");
9854   verifyFormat("throw -1;");
9855   verifyFormat("switch (a) {\n"
9856                "case -1:\n"
9857                "  break;\n"
9858                "}");
9859   verifyFormat("#define X -1");
9860   verifyFormat("#define X -kConstant");
9861 
9862   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9863   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9864 
9865   verifyFormat("int a = /* confusing comment */ -1;");
9866   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9867   verifyFormat("int a = i /* confusing comment */++;");
9868 
9869   verifyFormat("co_yield -1;");
9870   verifyFormat("co_return -1;");
9871 
9872   // Check that * is not treated as a binary operator when we set
9873   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9874   FormatStyle PASLeftStyle = getLLVMStyle();
9875   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9876   verifyFormat("co_return *a;", PASLeftStyle);
9877   verifyFormat("co_await *a;", PASLeftStyle);
9878   verifyFormat("co_yield *a", PASLeftStyle);
9879   verifyFormat("return *a;", PASLeftStyle);
9880 }
9881 
9882 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9883   verifyFormat("if (!aaaaaaaaaa( // break\n"
9884                "        aaaaa)) {\n"
9885                "}");
9886   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9887                "    aaaaa));");
9888   verifyFormat("*aaa = aaaaaaa( // break\n"
9889                "    bbbbbb);");
9890 }
9891 
9892 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9893   verifyFormat("bool operator<();");
9894   verifyFormat("bool operator>();");
9895   verifyFormat("bool operator=();");
9896   verifyFormat("bool operator==();");
9897   verifyFormat("bool operator!=();");
9898   verifyFormat("int operator+();");
9899   verifyFormat("int operator++();");
9900   verifyFormat("int operator++(int) volatile noexcept;");
9901   verifyFormat("bool operator,();");
9902   verifyFormat("bool operator();");
9903   verifyFormat("bool operator()();");
9904   verifyFormat("bool operator[]();");
9905   verifyFormat("operator bool();");
9906   verifyFormat("operator int();");
9907   verifyFormat("operator void *();");
9908   verifyFormat("operator SomeType<int>();");
9909   verifyFormat("operator SomeType<int, int>();");
9910   verifyFormat("operator SomeType<SomeType<int>>();");
9911   verifyFormat("operator< <>();");
9912   verifyFormat("operator<< <>();");
9913   verifyFormat("< <>");
9914 
9915   verifyFormat("void *operator new(std::size_t size);");
9916   verifyFormat("void *operator new[](std::size_t size);");
9917   verifyFormat("void operator delete(void *ptr);");
9918   verifyFormat("void operator delete[](void *ptr);");
9919   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9920                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9921   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9922                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9923 
9924   verifyFormat(
9925       "ostream &operator<<(ostream &OutputStream,\n"
9926       "                    SomeReallyLongType WithSomeReallyLongValue);");
9927   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9928                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9929                "  return left.group < right.group;\n"
9930                "}");
9931   verifyFormat("SomeType &operator=(const SomeType &S);");
9932   verifyFormat("f.template operator()<int>();");
9933 
9934   verifyGoogleFormat("operator void*();");
9935   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9936   verifyGoogleFormat("operator ::A();");
9937 
9938   verifyFormat("using A::operator+;");
9939   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9940                "int i;");
9941 
9942   // Calling an operator as a member function.
9943   verifyFormat("void f() { a.operator*(); }");
9944   verifyFormat("void f() { a.operator*(b & b); }");
9945   verifyFormat("void f() { a->operator&(a * b); }");
9946   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9947   // TODO: Calling an operator as a non-member function is hard to distinguish.
9948   // https://llvm.org/PR50629
9949   // verifyFormat("void f() { operator*(a & a); }");
9950   // verifyFormat("void f() { operator&(a, b * b); }");
9951 
9952   verifyFormat("::operator delete(foo);");
9953   verifyFormat("::operator new(n * sizeof(foo));");
9954   verifyFormat("foo() { ::operator delete(foo); }");
9955   verifyFormat("foo() { ::operator new(n * sizeof(foo)); }");
9956 }
9957 
9958 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9959   verifyFormat("void A::b() && {}");
9960   verifyFormat("void A::b() &&noexcept {}");
9961   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9962   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9963   verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
9964   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9965   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9966   verifyFormat("Deleted &operator=(const Deleted &) &;");
9967   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9968   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9969   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9970   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9971   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9972   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9973   verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
9974   verifyFormat("void Fn(T const &) const &;");
9975   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9976   verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
9977   verifyFormat("template <typename T>\n"
9978                "void F(T) && = delete;",
9979                getGoogleStyle());
9980   verifyFormat("template <typename T> void operator=(T) &;");
9981   verifyFormat("template <typename T> void operator=(T) const &;");
9982   verifyFormat("template <typename T> void operator=(T) &noexcept;");
9983   verifyFormat("template <typename T> void operator=(T) & = default;");
9984   verifyFormat("template <typename T> void operator=(T) &&;");
9985   verifyFormat("template <typename T> void operator=(T) && = delete;");
9986   verifyFormat("template <typename T> void operator=(T) & {}");
9987   verifyFormat("template <typename T> void operator=(T) && {}");
9988 
9989   FormatStyle AlignLeft = getLLVMStyle();
9990   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9991   verifyFormat("void A::b() && {}", AlignLeft);
9992   verifyFormat("void A::b() && noexcept {}", AlignLeft);
9993   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9994   verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
9995                AlignLeft);
9996   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9997                AlignLeft);
9998   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9999   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
10000   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
10001   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
10002   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
10003   verifyFormat("auto Function(T) & -> void;", AlignLeft);
10004   verifyFormat("void Fn(T const&) const&;", AlignLeft);
10005   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
10006   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
10007                AlignLeft);
10008   verifyFormat("template <typename T> void operator=(T) &;", AlignLeft);
10009   verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft);
10010   verifyFormat("template <typename T> void operator=(T) & noexcept;",
10011                AlignLeft);
10012   verifyFormat("template <typename T> void operator=(T) & = default;",
10013                AlignLeft);
10014   verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft);
10015   verifyFormat("template <typename T> void operator=(T) && = delete;",
10016                AlignLeft);
10017   verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft);
10018   verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft);
10019 
10020   FormatStyle AlignMiddle = getLLVMStyle();
10021   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10022   verifyFormat("void A::b() && {}", AlignMiddle);
10023   verifyFormat("void A::b() && noexcept {}", AlignMiddle);
10024   verifyFormat("Deleted & operator=(const Deleted &) & = default;",
10025                AlignMiddle);
10026   verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
10027                AlignMiddle);
10028   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
10029                AlignMiddle);
10030   verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
10031   verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
10032   verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
10033   verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
10034   verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
10035   verifyFormat("auto Function(T) & -> void;", AlignMiddle);
10036   verifyFormat("void Fn(T const &) const &;", AlignMiddle);
10037   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
10038   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
10039                AlignMiddle);
10040   verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle);
10041   verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle);
10042   verifyFormat("template <typename T> void operator=(T) & noexcept;",
10043                AlignMiddle);
10044   verifyFormat("template <typename T> void operator=(T) & = default;",
10045                AlignMiddle);
10046   verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle);
10047   verifyFormat("template <typename T> void operator=(T) && = delete;",
10048                AlignMiddle);
10049   verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle);
10050   verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle);
10051 
10052   FormatStyle Spaces = getLLVMStyle();
10053   Spaces.SpacesInCStyleCastParentheses = true;
10054   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
10055   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
10056   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
10057   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
10058 
10059   Spaces.SpacesInCStyleCastParentheses = false;
10060   Spaces.SpacesInParentheses = true;
10061   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
10062   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
10063                Spaces);
10064   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
10065   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
10066 
10067   FormatStyle BreakTemplate = getLLVMStyle();
10068   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
10069 
10070   verifyFormat("struct f {\n"
10071                "  template <class T>\n"
10072                "  int &foo(const std::string &str) &noexcept {}\n"
10073                "};",
10074                BreakTemplate);
10075 
10076   verifyFormat("struct f {\n"
10077                "  template <class T>\n"
10078                "  int &foo(const std::string &str) &&noexcept {}\n"
10079                "};",
10080                BreakTemplate);
10081 
10082   verifyFormat("struct f {\n"
10083                "  template <class T>\n"
10084                "  int &foo(const std::string &str) const &noexcept {}\n"
10085                "};",
10086                BreakTemplate);
10087 
10088   verifyFormat("struct f {\n"
10089                "  template <class T>\n"
10090                "  int &foo(const std::string &str) const &noexcept {}\n"
10091                "};",
10092                BreakTemplate);
10093 
10094   verifyFormat("struct f {\n"
10095                "  template <class T>\n"
10096                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
10097                "};",
10098                BreakTemplate);
10099 
10100   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
10101   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
10102       FormatStyle::BTDS_Yes;
10103   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
10104 
10105   verifyFormat("struct f {\n"
10106                "  template <class T>\n"
10107                "  int& foo(const std::string& str) & noexcept {}\n"
10108                "};",
10109                AlignLeftBreakTemplate);
10110 
10111   verifyFormat("struct f {\n"
10112                "  template <class T>\n"
10113                "  int& foo(const std::string& str) && noexcept {}\n"
10114                "};",
10115                AlignLeftBreakTemplate);
10116 
10117   verifyFormat("struct f {\n"
10118                "  template <class T>\n"
10119                "  int& foo(const std::string& str) const& noexcept {}\n"
10120                "};",
10121                AlignLeftBreakTemplate);
10122 
10123   verifyFormat("struct f {\n"
10124                "  template <class T>\n"
10125                "  int& foo(const std::string& str) const&& noexcept {}\n"
10126                "};",
10127                AlignLeftBreakTemplate);
10128 
10129   verifyFormat("struct f {\n"
10130                "  template <class T>\n"
10131                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
10132                "};",
10133                AlignLeftBreakTemplate);
10134 
10135   // The `&` in `Type&` should not be confused with a trailing `&` of
10136   // DEPRECATED(reason) member function.
10137   verifyFormat("struct f {\n"
10138                "  template <class T>\n"
10139                "  DEPRECATED(reason)\n"
10140                "  Type &foo(arguments) {}\n"
10141                "};",
10142                BreakTemplate);
10143 
10144   verifyFormat("struct f {\n"
10145                "  template <class T>\n"
10146                "  DEPRECATED(reason)\n"
10147                "  Type& foo(arguments) {}\n"
10148                "};",
10149                AlignLeftBreakTemplate);
10150 
10151   verifyFormat("void (*foopt)(int) = &func;");
10152 
10153   FormatStyle DerivePointerAlignment = getLLVMStyle();
10154   DerivePointerAlignment.DerivePointerAlignment = true;
10155   // There's always a space between the function and its trailing qualifiers.
10156   // This isn't evidence for PAS_Right (or for PAS_Left).
10157   std::string Prefix = "void a() &;\n"
10158                        "void b() &;\n";
10159   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10160   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10161   // Same if the function is an overloaded operator, and with &&.
10162   Prefix = "void operator()() &&;\n"
10163            "void operator()() &&;\n";
10164   verifyFormat(Prefix + "int* x;", DerivePointerAlignment);
10165   verifyFormat(Prefix + "int *x;", DerivePointerAlignment);
10166   // However a space between cv-qualifiers and ref-qualifiers *is* evidence.
10167   Prefix = "void a() const &;\n"
10168            "void b() const &;\n";
10169   EXPECT_EQ(Prefix + "int *x;",
10170             format(Prefix + "int* x;", DerivePointerAlignment));
10171 }
10172 
10173 TEST_F(FormatTest, UnderstandsNewAndDelete) {
10174   verifyFormat("void f() {\n"
10175                "  A *a = new A;\n"
10176                "  A *a = new (placement) A;\n"
10177                "  delete a;\n"
10178                "  delete (A *)a;\n"
10179                "}");
10180   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10181                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10182   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10183                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
10184                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
10185   verifyFormat("delete[] h->p;");
10186   verifyFormat("delete[] (void *)p;");
10187 
10188   verifyFormat("void operator delete(void *foo) ATTRIB;");
10189   verifyFormat("void operator new(void *foo) ATTRIB;");
10190   verifyFormat("void operator delete[](void *foo) ATTRIB;");
10191   verifyFormat("void operator delete(void *ptr) noexcept;");
10192 
10193   EXPECT_EQ("void new(link p);\n"
10194             "void delete(link p);\n",
10195             format("void new (link p);\n"
10196                    "void delete (link p);\n"));
10197 }
10198 
10199 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
10200   verifyFormat("int *f(int *a) {}");
10201   verifyFormat("int main(int argc, char **argv) {}");
10202   verifyFormat("Test::Test(int b) : a(b * b) {}");
10203   verifyIndependentOfContext("f(a, *a);");
10204   verifyFormat("void g() { f(*a); }");
10205   verifyIndependentOfContext("int a = b * 10;");
10206   verifyIndependentOfContext("int a = 10 * b;");
10207   verifyIndependentOfContext("int a = b * c;");
10208   verifyIndependentOfContext("int a += b * c;");
10209   verifyIndependentOfContext("int a -= b * c;");
10210   verifyIndependentOfContext("int a *= b * c;");
10211   verifyIndependentOfContext("int a /= b * c;");
10212   verifyIndependentOfContext("int a = *b;");
10213   verifyIndependentOfContext("int a = *b * c;");
10214   verifyIndependentOfContext("int a = b * *c;");
10215   verifyIndependentOfContext("int a = b * (10);");
10216   verifyIndependentOfContext("S << b * (10);");
10217   verifyIndependentOfContext("return 10 * b;");
10218   verifyIndependentOfContext("return *b * *c;");
10219   verifyIndependentOfContext("return a & ~b;");
10220   verifyIndependentOfContext("f(b ? *c : *d);");
10221   verifyIndependentOfContext("int a = b ? *c : *d;");
10222   verifyIndependentOfContext("*b = a;");
10223   verifyIndependentOfContext("a * ~b;");
10224   verifyIndependentOfContext("a * !b;");
10225   verifyIndependentOfContext("a * +b;");
10226   verifyIndependentOfContext("a * -b;");
10227   verifyIndependentOfContext("a * ++b;");
10228   verifyIndependentOfContext("a * --b;");
10229   verifyIndependentOfContext("a[4] * b;");
10230   verifyIndependentOfContext("a[a * a] = 1;");
10231   verifyIndependentOfContext("f() * b;");
10232   verifyIndependentOfContext("a * [self dostuff];");
10233   verifyIndependentOfContext("int x = a * (a + b);");
10234   verifyIndependentOfContext("(a *)(a + b);");
10235   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
10236   verifyIndependentOfContext("int *pa = (int *)&a;");
10237   verifyIndependentOfContext("return sizeof(int **);");
10238   verifyIndependentOfContext("return sizeof(int ******);");
10239   verifyIndependentOfContext("return (int **&)a;");
10240   verifyIndependentOfContext("f((*PointerToArray)[10]);");
10241   verifyFormat("void f(Type (*parameter)[10]) {}");
10242   verifyFormat("void f(Type (&parameter)[10]) {}");
10243   verifyGoogleFormat("return sizeof(int**);");
10244   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
10245   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
10246   verifyFormat("auto a = [](int **&, int ***) {};");
10247   verifyFormat("auto PointerBinding = [](const char *S) {};");
10248   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
10249   verifyFormat("[](const decltype(*a) &value) {}");
10250   verifyFormat("[](const typeof(*a) &value) {}");
10251   verifyFormat("[](const _Atomic(a *) &value) {}");
10252   verifyFormat("[](const __underlying_type(a) &value) {}");
10253   verifyFormat("decltype(a * b) F();");
10254   verifyFormat("typeof(a * b) F();");
10255   verifyFormat("#define MACRO() [](A *a) { return 1; }");
10256   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
10257   verifyIndependentOfContext("typedef void (*f)(int *a);");
10258   verifyIndependentOfContext("int i{a * b};");
10259   verifyIndependentOfContext("aaa && aaa->f();");
10260   verifyIndependentOfContext("int x = ~*p;");
10261   verifyFormat("Constructor() : a(a), area(width * height) {}");
10262   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
10263   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
10264   verifyFormat("void f() { f(a, c * d); }");
10265   verifyFormat("void f() { f(new a(), c * d); }");
10266   verifyFormat("void f(const MyOverride &override);");
10267   verifyFormat("void f(const MyFinal &final);");
10268   verifyIndependentOfContext("bool a = f() && override.f();");
10269   verifyIndependentOfContext("bool a = f() && final.f();");
10270 
10271   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
10272 
10273   verifyIndependentOfContext("A<int *> a;");
10274   verifyIndependentOfContext("A<int **> a;");
10275   verifyIndependentOfContext("A<int *, int *> a;");
10276   verifyIndependentOfContext("A<int *[]> a;");
10277   verifyIndependentOfContext(
10278       "const char *const p = reinterpret_cast<const char *const>(q);");
10279   verifyIndependentOfContext("A<int **, int **> a;");
10280   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
10281   verifyFormat("for (char **a = b; *a; ++a) {\n}");
10282   verifyFormat("for (; a && b;) {\n}");
10283   verifyFormat("bool foo = true && [] { return false; }();");
10284 
10285   verifyFormat(
10286       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10287       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10288 
10289   verifyGoogleFormat("int const* a = &b;");
10290   verifyGoogleFormat("**outparam = 1;");
10291   verifyGoogleFormat("*outparam = a * b;");
10292   verifyGoogleFormat("int main(int argc, char** argv) {}");
10293   verifyGoogleFormat("A<int*> a;");
10294   verifyGoogleFormat("A<int**> a;");
10295   verifyGoogleFormat("A<int*, int*> a;");
10296   verifyGoogleFormat("A<int**, int**> a;");
10297   verifyGoogleFormat("f(b ? *c : *d);");
10298   verifyGoogleFormat("int a = b ? *c : *d;");
10299   verifyGoogleFormat("Type* t = **x;");
10300   verifyGoogleFormat("Type* t = *++*x;");
10301   verifyGoogleFormat("*++*x;");
10302   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
10303   verifyGoogleFormat("Type* t = x++ * y;");
10304   verifyGoogleFormat(
10305       "const char* const p = reinterpret_cast<const char* const>(q);");
10306   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
10307   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
10308   verifyGoogleFormat("template <typename T>\n"
10309                      "void f(int i = 0, SomeType** temps = NULL);");
10310 
10311   FormatStyle Left = getLLVMStyle();
10312   Left.PointerAlignment = FormatStyle::PAS_Left;
10313   verifyFormat("x = *a(x) = *a(y);", Left);
10314   verifyFormat("for (;; *a = b) {\n}", Left);
10315   verifyFormat("return *this += 1;", Left);
10316   verifyFormat("throw *x;", Left);
10317   verifyFormat("delete *x;", Left);
10318   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
10319   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
10320   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
10321   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
10322   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
10323   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
10324   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
10325   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
10326   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
10327 
10328   verifyIndependentOfContext("a = *(x + y);");
10329   verifyIndependentOfContext("a = &(x + y);");
10330   verifyIndependentOfContext("*(x + y).call();");
10331   verifyIndependentOfContext("&(x + y)->call();");
10332   verifyFormat("void f() { &(*I).first; }");
10333 
10334   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
10335   verifyFormat("f(* /* confusing comment */ foo);");
10336   verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
10337   verifyFormat("void foo(int * // this is the first paramters\n"
10338                "         ,\n"
10339                "         int second);");
10340   verifyFormat("double term = a * // first\n"
10341                "              b;");
10342   verifyFormat(
10343       "int *MyValues = {\n"
10344       "    *A, // Operator detection might be confused by the '{'\n"
10345       "    *BB // Operator detection might be confused by previous comment\n"
10346       "};");
10347 
10348   verifyIndependentOfContext("if (int *a = &b)");
10349   verifyIndependentOfContext("if (int &a = *b)");
10350   verifyIndependentOfContext("if (a & b[i])");
10351   verifyIndependentOfContext("if constexpr (a & b[i])");
10352   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
10353   verifyIndependentOfContext("if (a * (b * c))");
10354   verifyIndependentOfContext("if constexpr (a * (b * c))");
10355   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
10356   verifyIndependentOfContext("if (a::b::c::d & b[i])");
10357   verifyIndependentOfContext("if (*b[i])");
10358   verifyIndependentOfContext("if (int *a = (&b))");
10359   verifyIndependentOfContext("while (int *a = &b)");
10360   verifyIndependentOfContext("while (a * (b * c))");
10361   verifyIndependentOfContext("size = sizeof *a;");
10362   verifyIndependentOfContext("if (a && (b = c))");
10363   verifyFormat("void f() {\n"
10364                "  for (const int &v : Values) {\n"
10365                "  }\n"
10366                "}");
10367   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
10368   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
10369   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
10370 
10371   verifyFormat("#define A (!a * b)");
10372   verifyFormat("#define MACRO     \\\n"
10373                "  int *i = a * b; \\\n"
10374                "  void f(a *b);",
10375                getLLVMStyleWithColumns(19));
10376 
10377   verifyIndependentOfContext("A = new SomeType *[Length];");
10378   verifyIndependentOfContext("A = new SomeType *[Length]();");
10379   verifyIndependentOfContext("T **t = new T *;");
10380   verifyIndependentOfContext("T **t = new T *();");
10381   verifyGoogleFormat("A = new SomeType*[Length]();");
10382   verifyGoogleFormat("A = new SomeType*[Length];");
10383   verifyGoogleFormat("T** t = new T*;");
10384   verifyGoogleFormat("T** t = new T*();");
10385 
10386   verifyFormat("STATIC_ASSERT((a & b) == 0);");
10387   verifyFormat("STATIC_ASSERT(0 == (a & b));");
10388   verifyFormat("template <bool a, bool b> "
10389                "typename t::if<x && y>::type f() {}");
10390   verifyFormat("template <int *y> f() {}");
10391   verifyFormat("vector<int *> v;");
10392   verifyFormat("vector<int *const> v;");
10393   verifyFormat("vector<int *const **const *> v;");
10394   verifyFormat("vector<int *volatile> v;");
10395   verifyFormat("vector<a *_Nonnull> v;");
10396   verifyFormat("vector<a *_Nullable> v;");
10397   verifyFormat("vector<a *_Null_unspecified> v;");
10398   verifyFormat("vector<a *__ptr32> v;");
10399   verifyFormat("vector<a *__ptr64> v;");
10400   verifyFormat("vector<a *__capability> v;");
10401   FormatStyle TypeMacros = getLLVMStyle();
10402   TypeMacros.TypenameMacros = {"LIST"};
10403   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
10404   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
10405   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
10406   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
10407   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
10408 
10409   FormatStyle CustomQualifier = getLLVMStyle();
10410   // Add identifiers that should not be parsed as a qualifier by default.
10411   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10412   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
10413   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
10414   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
10415   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
10416   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
10417   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
10418   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
10419   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
10420   verifyFormat("vector<a * _NotAQualifier> v;");
10421   verifyFormat("vector<a * __not_a_qualifier> v;");
10422   verifyFormat("vector<a * b> v;");
10423   verifyFormat("foo<b && false>();");
10424   verifyFormat("foo<b & 1>();");
10425   verifyFormat("foo<b & (1)>();");
10426   verifyFormat("foo<b & (~0)>();");
10427   verifyFormat("foo<b & (true)>();");
10428   verifyFormat("foo<b & ((1))>();");
10429   verifyFormat("foo<b & (/*comment*/ 1)>();");
10430   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
10431   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
10432   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
10433   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
10434   verifyFormat(
10435       "template <class T, class = typename std::enable_if<\n"
10436       "                       std::is_integral<T>::value &&\n"
10437       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
10438       "void F();",
10439       getLLVMStyleWithColumns(70));
10440   verifyFormat("template <class T,\n"
10441                "          class = typename std::enable_if<\n"
10442                "              std::is_integral<T>::value &&\n"
10443                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
10444                "          class U>\n"
10445                "void F();",
10446                getLLVMStyleWithColumns(70));
10447   verifyFormat(
10448       "template <class T,\n"
10449       "          class = typename ::std::enable_if<\n"
10450       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
10451       "void F();",
10452       getGoogleStyleWithColumns(68));
10453 
10454   FormatStyle Style = getLLVMStyle();
10455   Style.PointerAlignment = FormatStyle::PAS_Left;
10456   verifyFormat("struct {\n"
10457                "}* ptr;",
10458                Style);
10459   verifyFormat("union {\n"
10460                "}* ptr;",
10461                Style);
10462   verifyFormat("class {\n"
10463                "}* ptr;",
10464                Style);
10465   // Don't confuse a multiplication after a brace-initialized expression with
10466   // a class pointer.
10467   verifyFormat("int i = int{42} * 34;", Style);
10468   verifyFormat("struct {\n"
10469                "}&& ptr = {};",
10470                Style);
10471   verifyFormat("union {\n"
10472                "}&& ptr = {};",
10473                Style);
10474   verifyFormat("class {\n"
10475                "}&& ptr = {};",
10476                Style);
10477 
10478   Style.PointerAlignment = FormatStyle::PAS_Middle;
10479   verifyFormat("struct {\n"
10480                "} * ptr;",
10481                Style);
10482   verifyFormat("union {\n"
10483                "} * ptr;",
10484                Style);
10485   verifyFormat("class {\n"
10486                "} * ptr;",
10487                Style);
10488   verifyFormat("struct {\n"
10489                "} && ptr = {};",
10490                Style);
10491   verifyFormat("union {\n"
10492                "} && ptr = {};",
10493                Style);
10494   verifyFormat("class {\n"
10495                "} && ptr = {};",
10496                Style);
10497 
10498   Style.PointerAlignment = FormatStyle::PAS_Right;
10499   verifyFormat("struct {\n"
10500                "} *ptr;",
10501                Style);
10502   verifyFormat("union {\n"
10503                "} *ptr;",
10504                Style);
10505   verifyFormat("class {\n"
10506                "} *ptr;",
10507                Style);
10508   verifyFormat("struct {\n"
10509                "} &&ptr = {};",
10510                Style);
10511   verifyFormat("union {\n"
10512                "} &&ptr = {};",
10513                Style);
10514   verifyFormat("class {\n"
10515                "} &&ptr = {};",
10516                Style);
10517 
10518   verifyIndependentOfContext("MACRO(int *i);");
10519   verifyIndependentOfContext("MACRO(auto *a);");
10520   verifyIndependentOfContext("MACRO(const A *a);");
10521   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10522   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10523   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10524   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10525   verifyIndependentOfContext("MACRO(A *const a);");
10526   verifyIndependentOfContext("MACRO(A *restrict a);");
10527   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10528   verifyIndependentOfContext("MACRO(A *__restrict a);");
10529   verifyIndependentOfContext("MACRO(A *volatile a);");
10530   verifyIndependentOfContext("MACRO(A *__volatile a);");
10531   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10532   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10533   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10534   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10535   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10536   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10537   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10538   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10539   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10540   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10541   verifyIndependentOfContext("MACRO(A *__capability);");
10542   verifyIndependentOfContext("MACRO(A &__capability);");
10543   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10544   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10545   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10546   // a type declaration:
10547   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10548   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10549   // Also check that TypenameMacros prevents parsing it as multiplication:
10550   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10551   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10552 
10553   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10554   verifyFormat("void f() { f(float{1}, a * a); }");
10555   verifyFormat("void f() { f(float(1), a * a); }");
10556 
10557   verifyFormat("f((void (*)(int))g);");
10558   verifyFormat("f((void (&)(int))g);");
10559   verifyFormat("f((void (^)(int))g);");
10560 
10561   // FIXME: Is there a way to make this work?
10562   // verifyIndependentOfContext("MACRO(A *a);");
10563   verifyFormat("MACRO(A &B);");
10564   verifyFormat("MACRO(A *B);");
10565   verifyFormat("void f() { MACRO(A * B); }");
10566   verifyFormat("void f() { MACRO(A & B); }");
10567 
10568   // This lambda was mis-formatted after D88956 (treating it as a binop):
10569   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10570   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10571   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10572   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10573 
10574   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10575   verifyFormat("return options != nullptr && operator==(*options);");
10576 
10577   EXPECT_EQ("#define OP(x)                                    \\\n"
10578             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10579             "    return s << a.DebugString();                 \\\n"
10580             "  }",
10581             format("#define OP(x) \\\n"
10582                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10583                    "    return s << a.DebugString(); \\\n"
10584                    "  }",
10585                    getLLVMStyleWithColumns(50)));
10586 
10587   // FIXME: We cannot handle this case yet; we might be able to figure out that
10588   // foo<x> d > v; doesn't make sense.
10589   verifyFormat("foo<a<b && c> d> v;");
10590 
10591   FormatStyle PointerMiddle = getLLVMStyle();
10592   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10593   verifyFormat("delete *x;", PointerMiddle);
10594   verifyFormat("int * x;", PointerMiddle);
10595   verifyFormat("int *[] x;", PointerMiddle);
10596   verifyFormat("template <int * y> f() {}", PointerMiddle);
10597   verifyFormat("int * f(int * a) {}", PointerMiddle);
10598   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10599   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10600   verifyFormat("A<int *> a;", PointerMiddle);
10601   verifyFormat("A<int **> a;", PointerMiddle);
10602   verifyFormat("A<int *, int *> a;", PointerMiddle);
10603   verifyFormat("A<int *[]> a;", PointerMiddle);
10604   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10605   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10606   verifyFormat("T ** t = new T *;", PointerMiddle);
10607 
10608   // Member function reference qualifiers aren't binary operators.
10609   verifyFormat("string // break\n"
10610                "operator()() & {}");
10611   verifyFormat("string // break\n"
10612                "operator()() && {}");
10613   verifyGoogleFormat("template <typename T>\n"
10614                      "auto x() & -> int {}");
10615 
10616   // Should be binary operators when used as an argument expression (overloaded
10617   // operator invoked as a member function).
10618   verifyFormat("void f() { a.operator()(a * a); }");
10619   verifyFormat("void f() { a->operator()(a & a); }");
10620   verifyFormat("void f() { a.operator()(*a & *a); }");
10621   verifyFormat("void f() { a->operator()(*a * *a); }");
10622 
10623   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10624   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10625 }
10626 
10627 TEST_F(FormatTest, UnderstandsAttributes) {
10628   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10629   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10630                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10631   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10632   FormatStyle AfterType = getLLVMStyle();
10633   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10634   verifyFormat("__attribute__((nodebug)) void\n"
10635                "foo() {}\n",
10636                AfterType);
10637   verifyFormat("__unused void\n"
10638                "foo() {}",
10639                AfterType);
10640 
10641   FormatStyle CustomAttrs = getLLVMStyle();
10642   CustomAttrs.AttributeMacros.push_back("__unused");
10643   CustomAttrs.AttributeMacros.push_back("__attr1");
10644   CustomAttrs.AttributeMacros.push_back("__attr2");
10645   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10646   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10647   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10648   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10649   // Check that it is parsed as a multiplication without AttributeMacros and
10650   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10651   verifyFormat("vector<SomeType * __attr1> v;");
10652   verifyFormat("vector<SomeType __attr1 *> v;");
10653   verifyFormat("vector<SomeType __attr1 *const> v;");
10654   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10655   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10656   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10657   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10658   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10659   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10660   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10661   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10662 
10663   // Check that these are not parsed as function declarations:
10664   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10665   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10666   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10667   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10668   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10669   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10670   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10671   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10672   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10673   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10674 }
10675 
10676 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10677   // Check that qualifiers on pointers don't break parsing of casts.
10678   verifyFormat("x = (foo *const)*v;");
10679   verifyFormat("x = (foo *volatile)*v;");
10680   verifyFormat("x = (foo *restrict)*v;");
10681   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10682   verifyFormat("x = (foo *_Nonnull)*v;");
10683   verifyFormat("x = (foo *_Nullable)*v;");
10684   verifyFormat("x = (foo *_Null_unspecified)*v;");
10685   verifyFormat("x = (foo *_Nonnull)*v;");
10686   verifyFormat("x = (foo *[[clang::attr]])*v;");
10687   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10688   verifyFormat("x = (foo *__ptr32)*v;");
10689   verifyFormat("x = (foo *__ptr64)*v;");
10690   verifyFormat("x = (foo *__capability)*v;");
10691 
10692   // Check that we handle multiple trailing qualifiers and skip them all to
10693   // determine that the expression is a cast to a pointer type.
10694   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10695   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10696   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10697   StringRef AllQualifiers =
10698       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10699       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10700   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10701   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10702 
10703   // Also check that address-of is not parsed as a binary bitwise-and:
10704   verifyFormat("x = (foo *const)&v;");
10705   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10706   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10707 
10708   // Check custom qualifiers:
10709   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10710   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10711   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10712   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10713   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10714                CustomQualifier);
10715   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10716                CustomQualifier);
10717 
10718   // Check that unknown identifiers result in binary operator parsing:
10719   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10720   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10721 }
10722 
10723 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10724   verifyFormat("SomeType s [[unused]] (InitValue);");
10725   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10726   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10727   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10728   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10729   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10730                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10731   verifyFormat("[[nodiscard]] bool f() { return false; }");
10732   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10733   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10734   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10735   verifyFormat("[[nodiscard]] ::qualified_type f();");
10736 
10737   // Make sure we do not mistake attributes for array subscripts.
10738   verifyFormat("int a() {}\n"
10739                "[[unused]] int b() {}\n");
10740   verifyFormat("NSArray *arr;\n"
10741                "arr[[Foo() bar]];");
10742 
10743   // On the other hand, we still need to correctly find array subscripts.
10744   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10745 
10746   // Make sure that we do not mistake Objective-C method inside array literals
10747   // as attributes, even if those method names are also keywords.
10748   verifyFormat("@[ [foo bar] ];");
10749   verifyFormat("@[ [NSArray class] ];");
10750   verifyFormat("@[ [foo enum] ];");
10751 
10752   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10753 
10754   // Make sure we do not parse attributes as lambda introducers.
10755   FormatStyle MultiLineFunctions = getLLVMStyle();
10756   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10757   verifyFormat("[[unused]] int b() {\n"
10758                "  return 42;\n"
10759                "}\n",
10760                MultiLineFunctions);
10761 }
10762 
10763 TEST_F(FormatTest, AttributeClass) {
10764   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10765   verifyFormat("class S {\n"
10766                "  S(S&&) = default;\n"
10767                "};",
10768                Style);
10769   verifyFormat("class [[nodiscard]] S {\n"
10770                "  S(S&&) = default;\n"
10771                "};",
10772                Style);
10773   verifyFormat("class __attribute((maybeunused)) S {\n"
10774                "  S(S&&) = default;\n"
10775                "};",
10776                Style);
10777   verifyFormat("struct S {\n"
10778                "  S(S&&) = default;\n"
10779                "};",
10780                Style);
10781   verifyFormat("struct [[nodiscard]] S {\n"
10782                "  S(S&&) = default;\n"
10783                "};",
10784                Style);
10785 }
10786 
10787 TEST_F(FormatTest, AttributesAfterMacro) {
10788   FormatStyle Style = getLLVMStyle();
10789   verifyFormat("MACRO;\n"
10790                "__attribute__((maybe_unused)) int foo() {\n"
10791                "  //...\n"
10792                "}");
10793 
10794   verifyFormat("MACRO;\n"
10795                "[[nodiscard]] int foo() {\n"
10796                "  //...\n"
10797                "}");
10798 
10799   EXPECT_EQ("MACRO\n\n"
10800             "__attribute__((maybe_unused)) int foo() {\n"
10801             "  //...\n"
10802             "}",
10803             format("MACRO\n\n"
10804                    "__attribute__((maybe_unused)) int foo() {\n"
10805                    "  //...\n"
10806                    "}"));
10807 
10808   EXPECT_EQ("MACRO\n\n"
10809             "[[nodiscard]] int foo() {\n"
10810             "  //...\n"
10811             "}",
10812             format("MACRO\n\n"
10813                    "[[nodiscard]] int foo() {\n"
10814                    "  //...\n"
10815                    "}"));
10816 }
10817 
10818 TEST_F(FormatTest, AttributePenaltyBreaking) {
10819   FormatStyle Style = getLLVMStyle();
10820   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10821                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10822                Style);
10823   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10824                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10825                Style);
10826   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10827                "shared_ptr<ALongTypeName> &C d) {\n}",
10828                Style);
10829 }
10830 
10831 TEST_F(FormatTest, UnderstandsEllipsis) {
10832   FormatStyle Style = getLLVMStyle();
10833   verifyFormat("int printf(const char *fmt, ...);");
10834   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10835   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10836 
10837   verifyFormat("template <int *...PP> a;", Style);
10838 
10839   Style.PointerAlignment = FormatStyle::PAS_Left;
10840   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10841 
10842   verifyFormat("template <int*... PP> a;", Style);
10843 
10844   Style.PointerAlignment = FormatStyle::PAS_Middle;
10845   verifyFormat("template <int *... PP> a;", Style);
10846 }
10847 
10848 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10849   EXPECT_EQ("int *a;\n"
10850             "int *a;\n"
10851             "int *a;",
10852             format("int *a;\n"
10853                    "int* a;\n"
10854                    "int *a;",
10855                    getGoogleStyle()));
10856   EXPECT_EQ("int* a;\n"
10857             "int* a;\n"
10858             "int* a;",
10859             format("int* a;\n"
10860                    "int* a;\n"
10861                    "int *a;",
10862                    getGoogleStyle()));
10863   EXPECT_EQ("int *a;\n"
10864             "int *a;\n"
10865             "int *a;",
10866             format("int *a;\n"
10867                    "int * a;\n"
10868                    "int *  a;",
10869                    getGoogleStyle()));
10870   EXPECT_EQ("auto x = [] {\n"
10871             "  int *a;\n"
10872             "  int *a;\n"
10873             "  int *a;\n"
10874             "};",
10875             format("auto x=[]{int *a;\n"
10876                    "int * a;\n"
10877                    "int *  a;};",
10878                    getGoogleStyle()));
10879 }
10880 
10881 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10882   verifyFormat("int f(int &&a) {}");
10883   verifyFormat("int f(int a, char &&b) {}");
10884   verifyFormat("void f() { int &&a = b; }");
10885   verifyGoogleFormat("int f(int a, char&& b) {}");
10886   verifyGoogleFormat("void f() { int&& a = b; }");
10887 
10888   verifyIndependentOfContext("A<int &&> a;");
10889   verifyIndependentOfContext("A<int &&, int &&> a;");
10890   verifyGoogleFormat("A<int&&> a;");
10891   verifyGoogleFormat("A<int&&, int&&> a;");
10892 
10893   // Not rvalue references:
10894   verifyFormat("template <bool B, bool C> class A {\n"
10895                "  static_assert(B && C, \"Something is wrong\");\n"
10896                "};");
10897   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10898   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10899   verifyFormat("#define A(a, b) (a && b)");
10900 }
10901 
10902 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10903   verifyFormat("void f() {\n"
10904                "  x[aaaaaaaaa -\n"
10905                "    b] = 23;\n"
10906                "}",
10907                getLLVMStyleWithColumns(15));
10908 }
10909 
10910 TEST_F(FormatTest, FormatsCasts) {
10911   verifyFormat("Type *A = static_cast<Type *>(P);");
10912   verifyFormat("static_cast<Type *>(P);");
10913   verifyFormat("static_cast<Type &>(Fun)(Args);");
10914   verifyFormat("static_cast<Type &>(*Fun)(Args);");
10915   verifyFormat("if (static_cast<int>(A) + B >= 0)\n  ;");
10916   // Check that static_cast<...>(...) does not require the next token to be on
10917   // the same line.
10918   verifyFormat("some_loooong_output << something_something__ << "
10919                "static_cast<const void *>(R)\n"
10920                "                    << something;");
10921   verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
10922   verifyFormat("const_cast<Type &>(*Fun)(Args);");
10923   verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
10924   verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
10925   verifyFormat("Type *A = (Type *)P;");
10926   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10927   verifyFormat("int a = (int)(2.0f);");
10928   verifyFormat("int a = (int)2.0f;");
10929   verifyFormat("x[(int32)y];");
10930   verifyFormat("x = (int32)y;");
10931   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10932   verifyFormat("int a = (int)*b;");
10933   verifyFormat("int a = (int)2.0f;");
10934   verifyFormat("int a = (int)~0;");
10935   verifyFormat("int a = (int)++a;");
10936   verifyFormat("int a = (int)sizeof(int);");
10937   verifyFormat("int a = (int)+2;");
10938   verifyFormat("my_int a = (my_int)2.0f;");
10939   verifyFormat("my_int a = (my_int)sizeof(int);");
10940   verifyFormat("return (my_int)aaa;");
10941   verifyFormat("#define x ((int)-1)");
10942   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10943   verifyFormat("#define p(q) ((int *)&q)");
10944   verifyFormat("fn(a)(b) + 1;");
10945 
10946   verifyFormat("void f() { my_int a = (my_int)*b; }");
10947   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10948   verifyFormat("my_int a = (my_int)~0;");
10949   verifyFormat("my_int a = (my_int)++a;");
10950   verifyFormat("my_int a = (my_int)-2;");
10951   verifyFormat("my_int a = (my_int)1;");
10952   verifyFormat("my_int a = (my_int *)1;");
10953   verifyFormat("my_int a = (const my_int)-1;");
10954   verifyFormat("my_int a = (const my_int *)-1;");
10955   verifyFormat("my_int a = (my_int)(my_int)-1;");
10956   verifyFormat("my_int a = (ns::my_int)-2;");
10957   verifyFormat("case (my_int)ONE:");
10958   verifyFormat("auto x = (X)this;");
10959   // Casts in Obj-C style calls used to not be recognized as such.
10960   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10961 
10962   // FIXME: single value wrapped with paren will be treated as cast.
10963   verifyFormat("void f(int i = (kValue)*kMask) {}");
10964 
10965   verifyFormat("{ (void)F; }");
10966 
10967   // Don't break after a cast's
10968   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10969                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10970                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10971 
10972   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10973   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10974   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10975   verifyFormat("bool *y = (bool *)(void *)(x);");
10976   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10977   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10978   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10979   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10980 
10981   // These are not casts.
10982   verifyFormat("void f(int *) {}");
10983   verifyFormat("f(foo)->b;");
10984   verifyFormat("f(foo).b;");
10985   verifyFormat("f(foo)(b);");
10986   verifyFormat("f(foo)[b];");
10987   verifyFormat("[](foo) { return 4; }(bar);");
10988   verifyFormat("(*funptr)(foo)[4];");
10989   verifyFormat("funptrs[4](foo)[4];");
10990   verifyFormat("void f(int *);");
10991   verifyFormat("void f(int *) = 0;");
10992   verifyFormat("void f(SmallVector<int>) {}");
10993   verifyFormat("void f(SmallVector<int>);");
10994   verifyFormat("void f(SmallVector<int>) = 0;");
10995   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10996   verifyFormat("int a = sizeof(int) * b;");
10997   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10998   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10999   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
11000   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
11001 
11002   // These are not casts, but at some point were confused with casts.
11003   verifyFormat("virtual void foo(int *) override;");
11004   verifyFormat("virtual void foo(char &) const;");
11005   verifyFormat("virtual void foo(int *a, char *) const;");
11006   verifyFormat("int a = sizeof(int *) + b;");
11007   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
11008   verifyFormat("bool b = f(g<int>) && c;");
11009   verifyFormat("typedef void (*f)(int i) func;");
11010   verifyFormat("void operator++(int) noexcept;");
11011   verifyFormat("void operator++(int &) noexcept;");
11012   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
11013                "&) noexcept;");
11014   verifyFormat(
11015       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
11016   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
11017   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
11018   verifyFormat("void operator delete(nothrow_t &) noexcept;");
11019   verifyFormat("void operator delete(foo &) noexcept;");
11020   verifyFormat("void operator delete(foo) noexcept;");
11021   verifyFormat("void operator delete(int) noexcept;");
11022   verifyFormat("void operator delete(int &) noexcept;");
11023   verifyFormat("void operator delete(int &) volatile noexcept;");
11024   verifyFormat("void operator delete(int &) const");
11025   verifyFormat("void operator delete(int &) = default");
11026   verifyFormat("void operator delete(int &) = delete");
11027   verifyFormat("void operator delete(int &) [[noreturn]]");
11028   verifyFormat("void operator delete(int &) throw();");
11029   verifyFormat("void operator delete(int &) throw(int);");
11030   verifyFormat("auto operator delete(int &) -> int;");
11031   verifyFormat("auto operator delete(int &) override");
11032   verifyFormat("auto operator delete(int &) final");
11033 
11034   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
11035                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
11036   // FIXME: The indentation here is not ideal.
11037   verifyFormat(
11038       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11039       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
11040       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
11041 }
11042 
11043 TEST_F(FormatTest, FormatsFunctionTypes) {
11044   verifyFormat("A<bool()> a;");
11045   verifyFormat("A<SomeType()> a;");
11046   verifyFormat("A<void (*)(int, std::string)> a;");
11047   verifyFormat("A<void *(int)>;");
11048   verifyFormat("void *(*a)(int *, SomeType *);");
11049   verifyFormat("int (*func)(void *);");
11050   verifyFormat("void f() { int (*func)(void *); }");
11051   verifyFormat("template <class CallbackClass>\n"
11052                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
11053 
11054   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
11055   verifyGoogleFormat("void* (*a)(int);");
11056   verifyGoogleFormat(
11057       "template <class CallbackClass>\n"
11058       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
11059 
11060   // Other constructs can look somewhat like function types:
11061   verifyFormat("A<sizeof(*x)> a;");
11062   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
11063   verifyFormat("some_var = function(*some_pointer_var)[0];");
11064   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
11065   verifyFormat("int x = f(&h)();");
11066   verifyFormat("returnsFunction(&param1, &param2)(param);");
11067   verifyFormat("std::function<\n"
11068                "    LooooooooooongTemplatedType<\n"
11069                "        SomeType>*(\n"
11070                "        LooooooooooooooooongType type)>\n"
11071                "    function;",
11072                getGoogleStyleWithColumns(40));
11073 }
11074 
11075 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
11076   verifyFormat("A (*foo_)[6];");
11077   verifyFormat("vector<int> (*foo_)[6];");
11078 }
11079 
11080 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
11081   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11082                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
11083   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
11084                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
11085   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11086                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
11087 
11088   // Different ways of ()-initializiation.
11089   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11090                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
11091   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11092                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
11093   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11094                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
11095   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11096                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
11097 
11098   // Lambdas should not confuse the variable declaration heuristic.
11099   verifyFormat("LooooooooooooooooongType\n"
11100                "    variable(nullptr, [](A *a) {});",
11101                getLLVMStyleWithColumns(40));
11102 }
11103 
11104 TEST_F(FormatTest, BreaksLongDeclarations) {
11105   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
11106                "    AnotherNameForTheLongType;");
11107   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
11108                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
11109   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11110                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
11111   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
11112                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
11113   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11114                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11115   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
11116                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11117   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
11118                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11119   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
11120                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11121   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
11122                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11123   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
11124                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11125   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
11126                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11127   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11128                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
11129   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11130                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
11131   FormatStyle Indented = getLLVMStyle();
11132   Indented.IndentWrappedFunctionNames = true;
11133   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11134                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
11135                Indented);
11136   verifyFormat(
11137       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11138       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11139       Indented);
11140   verifyFormat(
11141       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
11142       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11143       Indented);
11144   verifyFormat(
11145       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
11146       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11147       Indented);
11148 
11149   // FIXME: Without the comment, this breaks after "(".
11150   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
11151                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
11152                getGoogleStyle());
11153 
11154   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
11155                "                  int LoooooooooooooooooooongParam2) {}");
11156   verifyFormat(
11157       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
11158       "                                   SourceLocation L, IdentifierIn *II,\n"
11159       "                                   Type *T) {}");
11160   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
11161                "ReallyReaaallyLongFunctionName(\n"
11162                "    const std::string &SomeParameter,\n"
11163                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11164                "        &ReallyReallyLongParameterName,\n"
11165                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11166                "        &AnotherLongParameterName) {}");
11167   verifyFormat("template <typename A>\n"
11168                "SomeLoooooooooooooooooooooongType<\n"
11169                "    typename some_namespace::SomeOtherType<A>::Type>\n"
11170                "Function() {}");
11171 
11172   verifyGoogleFormat(
11173       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
11174       "    aaaaaaaaaaaaaaaaaaaaaaa;");
11175   verifyGoogleFormat(
11176       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
11177       "                                   SourceLocation L) {}");
11178   verifyGoogleFormat(
11179       "some_namespace::LongReturnType\n"
11180       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
11181       "    int first_long_parameter, int second_parameter) {}");
11182 
11183   verifyGoogleFormat("template <typename T>\n"
11184                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11185                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
11186   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11187                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
11188 
11189   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
11190                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11191                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11192   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11193                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11194                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
11195   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11196                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
11197                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
11198                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11199 
11200   verifyFormat("template <typename T> // Templates on own line.\n"
11201                "static int            // Some comment.\n"
11202                "MyFunction(int a);",
11203                getLLVMStyle());
11204 }
11205 
11206 TEST_F(FormatTest, FormatsAccessModifiers) {
11207   FormatStyle Style = getLLVMStyle();
11208   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
11209             FormatStyle::ELBAMS_LogicalBlock);
11210   verifyFormat("struct foo {\n"
11211                "private:\n"
11212                "  void f() {}\n"
11213                "\n"
11214                "private:\n"
11215                "  int i;\n"
11216                "\n"
11217                "protected:\n"
11218                "  int j;\n"
11219                "};\n",
11220                Style);
11221   verifyFormat("struct foo {\n"
11222                "private:\n"
11223                "  void f() {}\n"
11224                "\n"
11225                "private:\n"
11226                "  int i;\n"
11227                "\n"
11228                "protected:\n"
11229                "  int j;\n"
11230                "};\n",
11231                "struct foo {\n"
11232                "private:\n"
11233                "  void f() {}\n"
11234                "private:\n"
11235                "  int i;\n"
11236                "protected:\n"
11237                "  int j;\n"
11238                "};\n",
11239                Style);
11240   verifyFormat("struct foo { /* comment */\n"
11241                "private:\n"
11242                "  int i;\n"
11243                "  // comment\n"
11244                "private:\n"
11245                "  int j;\n"
11246                "};\n",
11247                Style);
11248   verifyFormat("struct foo {\n"
11249                "#ifdef FOO\n"
11250                "#endif\n"
11251                "private:\n"
11252                "  int i;\n"
11253                "#ifdef FOO\n"
11254                "private:\n"
11255                "#endif\n"
11256                "  int j;\n"
11257                "};\n",
11258                Style);
11259   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11260   verifyFormat("struct foo {\n"
11261                "private:\n"
11262                "  void f() {}\n"
11263                "private:\n"
11264                "  int i;\n"
11265                "protected:\n"
11266                "  int j;\n"
11267                "};\n",
11268                Style);
11269   verifyFormat("struct foo {\n"
11270                "private:\n"
11271                "  void f() {}\n"
11272                "private:\n"
11273                "  int i;\n"
11274                "protected:\n"
11275                "  int j;\n"
11276                "};\n",
11277                "struct foo {\n"
11278                "\n"
11279                "private:\n"
11280                "  void f() {}\n"
11281                "\n"
11282                "private:\n"
11283                "  int i;\n"
11284                "\n"
11285                "protected:\n"
11286                "  int j;\n"
11287                "};\n",
11288                Style);
11289   verifyFormat("struct foo { /* comment */\n"
11290                "private:\n"
11291                "  int i;\n"
11292                "  // comment\n"
11293                "private:\n"
11294                "  int j;\n"
11295                "};\n",
11296                "struct foo { /* comment */\n"
11297                "\n"
11298                "private:\n"
11299                "  int i;\n"
11300                "  // comment\n"
11301                "\n"
11302                "private:\n"
11303                "  int j;\n"
11304                "};\n",
11305                Style);
11306   verifyFormat("struct foo {\n"
11307                "#ifdef FOO\n"
11308                "#endif\n"
11309                "private:\n"
11310                "  int i;\n"
11311                "#ifdef FOO\n"
11312                "private:\n"
11313                "#endif\n"
11314                "  int j;\n"
11315                "};\n",
11316                "struct foo {\n"
11317                "#ifdef FOO\n"
11318                "#endif\n"
11319                "\n"
11320                "private:\n"
11321                "  int i;\n"
11322                "#ifdef FOO\n"
11323                "\n"
11324                "private:\n"
11325                "#endif\n"
11326                "  int j;\n"
11327                "};\n",
11328                Style);
11329   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11330   verifyFormat("struct foo {\n"
11331                "private:\n"
11332                "  void f() {}\n"
11333                "\n"
11334                "private:\n"
11335                "  int i;\n"
11336                "\n"
11337                "protected:\n"
11338                "  int j;\n"
11339                "};\n",
11340                Style);
11341   verifyFormat("struct foo {\n"
11342                "private:\n"
11343                "  void f() {}\n"
11344                "\n"
11345                "private:\n"
11346                "  int i;\n"
11347                "\n"
11348                "protected:\n"
11349                "  int j;\n"
11350                "};\n",
11351                "struct foo {\n"
11352                "private:\n"
11353                "  void f() {}\n"
11354                "private:\n"
11355                "  int i;\n"
11356                "protected:\n"
11357                "  int j;\n"
11358                "};\n",
11359                Style);
11360   verifyFormat("struct foo { /* comment */\n"
11361                "private:\n"
11362                "  int i;\n"
11363                "  // comment\n"
11364                "\n"
11365                "private:\n"
11366                "  int j;\n"
11367                "};\n",
11368                "struct foo { /* comment */\n"
11369                "private:\n"
11370                "  int i;\n"
11371                "  // comment\n"
11372                "\n"
11373                "private:\n"
11374                "  int j;\n"
11375                "};\n",
11376                Style);
11377   verifyFormat("struct foo {\n"
11378                "#ifdef FOO\n"
11379                "#endif\n"
11380                "\n"
11381                "private:\n"
11382                "  int i;\n"
11383                "#ifdef FOO\n"
11384                "\n"
11385                "private:\n"
11386                "#endif\n"
11387                "  int j;\n"
11388                "};\n",
11389                "struct foo {\n"
11390                "#ifdef FOO\n"
11391                "#endif\n"
11392                "private:\n"
11393                "  int i;\n"
11394                "#ifdef FOO\n"
11395                "private:\n"
11396                "#endif\n"
11397                "  int j;\n"
11398                "};\n",
11399                Style);
11400   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11401   EXPECT_EQ("struct foo {\n"
11402             "\n"
11403             "private:\n"
11404             "  void f() {}\n"
11405             "\n"
11406             "private:\n"
11407             "  int i;\n"
11408             "\n"
11409             "protected:\n"
11410             "  int j;\n"
11411             "};\n",
11412             format("struct foo {\n"
11413                    "\n"
11414                    "private:\n"
11415                    "  void f() {}\n"
11416                    "\n"
11417                    "private:\n"
11418                    "  int i;\n"
11419                    "\n"
11420                    "protected:\n"
11421                    "  int j;\n"
11422                    "};\n",
11423                    Style));
11424   verifyFormat("struct foo {\n"
11425                "private:\n"
11426                "  void f() {}\n"
11427                "private:\n"
11428                "  int i;\n"
11429                "protected:\n"
11430                "  int j;\n"
11431                "};\n",
11432                Style);
11433   EXPECT_EQ("struct foo { /* comment */\n"
11434             "\n"
11435             "private:\n"
11436             "  int i;\n"
11437             "  // comment\n"
11438             "\n"
11439             "private:\n"
11440             "  int j;\n"
11441             "};\n",
11442             format("struct foo { /* comment */\n"
11443                    "\n"
11444                    "private:\n"
11445                    "  int i;\n"
11446                    "  // comment\n"
11447                    "\n"
11448                    "private:\n"
11449                    "  int j;\n"
11450                    "};\n",
11451                    Style));
11452   verifyFormat("struct foo { /* comment */\n"
11453                "private:\n"
11454                "  int i;\n"
11455                "  // comment\n"
11456                "private:\n"
11457                "  int j;\n"
11458                "};\n",
11459                Style);
11460   EXPECT_EQ("struct foo {\n"
11461             "#ifdef FOO\n"
11462             "#endif\n"
11463             "\n"
11464             "private:\n"
11465             "  int i;\n"
11466             "#ifdef FOO\n"
11467             "\n"
11468             "private:\n"
11469             "#endif\n"
11470             "  int j;\n"
11471             "};\n",
11472             format("struct foo {\n"
11473                    "#ifdef FOO\n"
11474                    "#endif\n"
11475                    "\n"
11476                    "private:\n"
11477                    "  int i;\n"
11478                    "#ifdef FOO\n"
11479                    "\n"
11480                    "private:\n"
11481                    "#endif\n"
11482                    "  int j;\n"
11483                    "};\n",
11484                    Style));
11485   verifyFormat("struct foo {\n"
11486                "#ifdef FOO\n"
11487                "#endif\n"
11488                "private:\n"
11489                "  int i;\n"
11490                "#ifdef FOO\n"
11491                "private:\n"
11492                "#endif\n"
11493                "  int j;\n"
11494                "};\n",
11495                Style);
11496 
11497   FormatStyle NoEmptyLines = getLLVMStyle();
11498   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11499   verifyFormat("struct foo {\n"
11500                "private:\n"
11501                "  void f() {}\n"
11502                "\n"
11503                "private:\n"
11504                "  int i;\n"
11505                "\n"
11506                "public:\n"
11507                "protected:\n"
11508                "  int j;\n"
11509                "};\n",
11510                NoEmptyLines);
11511 
11512   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11513   verifyFormat("struct foo {\n"
11514                "private:\n"
11515                "  void f() {}\n"
11516                "private:\n"
11517                "  int i;\n"
11518                "public:\n"
11519                "protected:\n"
11520                "  int j;\n"
11521                "};\n",
11522                NoEmptyLines);
11523 
11524   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11525   verifyFormat("struct foo {\n"
11526                "private:\n"
11527                "  void f() {}\n"
11528                "\n"
11529                "private:\n"
11530                "  int i;\n"
11531                "\n"
11532                "public:\n"
11533                "\n"
11534                "protected:\n"
11535                "  int j;\n"
11536                "};\n",
11537                NoEmptyLines);
11538 }
11539 
11540 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11541 
11542   FormatStyle Style = getLLVMStyle();
11543   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11544   verifyFormat("struct foo {\n"
11545                "private:\n"
11546                "  void f() {}\n"
11547                "\n"
11548                "private:\n"
11549                "  int i;\n"
11550                "\n"
11551                "protected:\n"
11552                "  int j;\n"
11553                "};\n",
11554                Style);
11555 
11556   // Check if lines are removed.
11557   verifyFormat("struct foo {\n"
11558                "private:\n"
11559                "  void f() {}\n"
11560                "\n"
11561                "private:\n"
11562                "  int i;\n"
11563                "\n"
11564                "protected:\n"
11565                "  int j;\n"
11566                "};\n",
11567                "struct foo {\n"
11568                "private:\n"
11569                "\n"
11570                "  void f() {}\n"
11571                "\n"
11572                "private:\n"
11573                "\n"
11574                "  int i;\n"
11575                "\n"
11576                "protected:\n"
11577                "\n"
11578                "  int j;\n"
11579                "};\n",
11580                Style);
11581 
11582   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11583   verifyFormat("struct foo {\n"
11584                "private:\n"
11585                "\n"
11586                "  void f() {}\n"
11587                "\n"
11588                "private:\n"
11589                "\n"
11590                "  int i;\n"
11591                "\n"
11592                "protected:\n"
11593                "\n"
11594                "  int j;\n"
11595                "};\n",
11596                Style);
11597 
11598   // Check if lines are added.
11599   verifyFormat("struct foo {\n"
11600                "private:\n"
11601                "\n"
11602                "  void f() {}\n"
11603                "\n"
11604                "private:\n"
11605                "\n"
11606                "  int i;\n"
11607                "\n"
11608                "protected:\n"
11609                "\n"
11610                "  int j;\n"
11611                "};\n",
11612                "struct foo {\n"
11613                "private:\n"
11614                "  void f() {}\n"
11615                "\n"
11616                "private:\n"
11617                "  int i;\n"
11618                "\n"
11619                "protected:\n"
11620                "  int j;\n"
11621                "};\n",
11622                Style);
11623 
11624   // Leave tests rely on the code layout, test::messUp can not be used.
11625   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11626   Style.MaxEmptyLinesToKeep = 0u;
11627   verifyFormat("struct foo {\n"
11628                "private:\n"
11629                "  void f() {}\n"
11630                "\n"
11631                "private:\n"
11632                "  int i;\n"
11633                "\n"
11634                "protected:\n"
11635                "  int j;\n"
11636                "};\n",
11637                Style);
11638 
11639   // Check if MaxEmptyLinesToKeep is respected.
11640   EXPECT_EQ("struct foo {\n"
11641             "private:\n"
11642             "  void f() {}\n"
11643             "\n"
11644             "private:\n"
11645             "  int i;\n"
11646             "\n"
11647             "protected:\n"
11648             "  int j;\n"
11649             "};\n",
11650             format("struct foo {\n"
11651                    "private:\n"
11652                    "\n\n\n"
11653                    "  void f() {}\n"
11654                    "\n"
11655                    "private:\n"
11656                    "\n\n\n"
11657                    "  int i;\n"
11658                    "\n"
11659                    "protected:\n"
11660                    "\n\n\n"
11661                    "  int j;\n"
11662                    "};\n",
11663                    Style));
11664 
11665   Style.MaxEmptyLinesToKeep = 1u;
11666   EXPECT_EQ("struct foo {\n"
11667             "private:\n"
11668             "\n"
11669             "  void f() {}\n"
11670             "\n"
11671             "private:\n"
11672             "\n"
11673             "  int i;\n"
11674             "\n"
11675             "protected:\n"
11676             "\n"
11677             "  int j;\n"
11678             "};\n",
11679             format("struct foo {\n"
11680                    "private:\n"
11681                    "\n"
11682                    "  void f() {}\n"
11683                    "\n"
11684                    "private:\n"
11685                    "\n"
11686                    "  int i;\n"
11687                    "\n"
11688                    "protected:\n"
11689                    "\n"
11690                    "  int j;\n"
11691                    "};\n",
11692                    Style));
11693   // Check if no lines are kept.
11694   EXPECT_EQ("struct foo {\n"
11695             "private:\n"
11696             "  void f() {}\n"
11697             "\n"
11698             "private:\n"
11699             "  int i;\n"
11700             "\n"
11701             "protected:\n"
11702             "  int j;\n"
11703             "};\n",
11704             format("struct foo {\n"
11705                    "private:\n"
11706                    "  void f() {}\n"
11707                    "\n"
11708                    "private:\n"
11709                    "  int i;\n"
11710                    "\n"
11711                    "protected:\n"
11712                    "  int j;\n"
11713                    "};\n",
11714                    Style));
11715   // Check if MaxEmptyLinesToKeep is respected.
11716   EXPECT_EQ("struct foo {\n"
11717             "private:\n"
11718             "\n"
11719             "  void f() {}\n"
11720             "\n"
11721             "private:\n"
11722             "\n"
11723             "  int i;\n"
11724             "\n"
11725             "protected:\n"
11726             "\n"
11727             "  int j;\n"
11728             "};\n",
11729             format("struct foo {\n"
11730                    "private:\n"
11731                    "\n\n\n"
11732                    "  void f() {}\n"
11733                    "\n"
11734                    "private:\n"
11735                    "\n\n\n"
11736                    "  int i;\n"
11737                    "\n"
11738                    "protected:\n"
11739                    "\n\n\n"
11740                    "  int j;\n"
11741                    "};\n",
11742                    Style));
11743 
11744   Style.MaxEmptyLinesToKeep = 10u;
11745   EXPECT_EQ("struct foo {\n"
11746             "private:\n"
11747             "\n\n\n"
11748             "  void f() {}\n"
11749             "\n"
11750             "private:\n"
11751             "\n\n\n"
11752             "  int i;\n"
11753             "\n"
11754             "protected:\n"
11755             "\n\n\n"
11756             "  int j;\n"
11757             "};\n",
11758             format("struct foo {\n"
11759                    "private:\n"
11760                    "\n\n\n"
11761                    "  void f() {}\n"
11762                    "\n"
11763                    "private:\n"
11764                    "\n\n\n"
11765                    "  int i;\n"
11766                    "\n"
11767                    "protected:\n"
11768                    "\n\n\n"
11769                    "  int j;\n"
11770                    "};\n",
11771                    Style));
11772 
11773   // Test with comments.
11774   Style = getLLVMStyle();
11775   verifyFormat("struct foo {\n"
11776                "private:\n"
11777                "  // comment\n"
11778                "  void f() {}\n"
11779                "\n"
11780                "private: /* comment */\n"
11781                "  int i;\n"
11782                "};\n",
11783                Style);
11784   verifyFormat("struct foo {\n"
11785                "private:\n"
11786                "  // comment\n"
11787                "  void f() {}\n"
11788                "\n"
11789                "private: /* comment */\n"
11790                "  int i;\n"
11791                "};\n",
11792                "struct foo {\n"
11793                "private:\n"
11794                "\n"
11795                "  // comment\n"
11796                "  void f() {}\n"
11797                "\n"
11798                "private: /* comment */\n"
11799                "\n"
11800                "  int i;\n"
11801                "};\n",
11802                Style);
11803 
11804   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11805   verifyFormat("struct foo {\n"
11806                "private:\n"
11807                "\n"
11808                "  // comment\n"
11809                "  void f() {}\n"
11810                "\n"
11811                "private: /* comment */\n"
11812                "\n"
11813                "  int i;\n"
11814                "};\n",
11815                "struct foo {\n"
11816                "private:\n"
11817                "  // comment\n"
11818                "  void f() {}\n"
11819                "\n"
11820                "private: /* comment */\n"
11821                "  int i;\n"
11822                "};\n",
11823                Style);
11824   verifyFormat("struct foo {\n"
11825                "private:\n"
11826                "\n"
11827                "  // comment\n"
11828                "  void f() {}\n"
11829                "\n"
11830                "private: /* comment */\n"
11831                "\n"
11832                "  int i;\n"
11833                "};\n",
11834                Style);
11835 
11836   // Test with preprocessor defines.
11837   Style = getLLVMStyle();
11838   verifyFormat("struct foo {\n"
11839                "private:\n"
11840                "#ifdef FOO\n"
11841                "#endif\n"
11842                "  void f() {}\n"
11843                "};\n",
11844                Style);
11845   verifyFormat("struct foo {\n"
11846                "private:\n"
11847                "#ifdef FOO\n"
11848                "#endif\n"
11849                "  void f() {}\n"
11850                "};\n",
11851                "struct foo {\n"
11852                "private:\n"
11853                "\n"
11854                "#ifdef FOO\n"
11855                "#endif\n"
11856                "  void f() {}\n"
11857                "};\n",
11858                Style);
11859 
11860   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11861   verifyFormat("struct foo {\n"
11862                "private:\n"
11863                "\n"
11864                "#ifdef FOO\n"
11865                "#endif\n"
11866                "  void f() {}\n"
11867                "};\n",
11868                "struct foo {\n"
11869                "private:\n"
11870                "#ifdef FOO\n"
11871                "#endif\n"
11872                "  void f() {}\n"
11873                "};\n",
11874                Style);
11875   verifyFormat("struct foo {\n"
11876                "private:\n"
11877                "\n"
11878                "#ifdef FOO\n"
11879                "#endif\n"
11880                "  void f() {}\n"
11881                "};\n",
11882                Style);
11883 }
11884 
11885 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11886   // Combined tests of EmptyLineAfterAccessModifier and
11887   // EmptyLineBeforeAccessModifier.
11888   FormatStyle Style = getLLVMStyle();
11889   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11890   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11891   verifyFormat("struct foo {\n"
11892                "private:\n"
11893                "\n"
11894                "protected:\n"
11895                "};\n",
11896                Style);
11897 
11898   Style.MaxEmptyLinesToKeep = 10u;
11899   // Both remove all new lines.
11900   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11901   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11902   verifyFormat("struct foo {\n"
11903                "private:\n"
11904                "protected:\n"
11905                "};\n",
11906                "struct foo {\n"
11907                "private:\n"
11908                "\n\n\n"
11909                "protected:\n"
11910                "};\n",
11911                Style);
11912 
11913   // Leave tests rely on the code layout, test::messUp can not be used.
11914   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11915   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11916   Style.MaxEmptyLinesToKeep = 10u;
11917   EXPECT_EQ("struct foo {\n"
11918             "private:\n"
11919             "\n\n\n"
11920             "protected:\n"
11921             "};\n",
11922             format("struct foo {\n"
11923                    "private:\n"
11924                    "\n\n\n"
11925                    "protected:\n"
11926                    "};\n",
11927                    Style));
11928   Style.MaxEmptyLinesToKeep = 3u;
11929   EXPECT_EQ("struct foo {\n"
11930             "private:\n"
11931             "\n\n\n"
11932             "protected:\n"
11933             "};\n",
11934             format("struct foo {\n"
11935                    "private:\n"
11936                    "\n\n\n"
11937                    "protected:\n"
11938                    "};\n",
11939                    Style));
11940   Style.MaxEmptyLinesToKeep = 1u;
11941   EXPECT_EQ("struct foo {\n"
11942             "private:\n"
11943             "\n\n\n"
11944             "protected:\n"
11945             "};\n",
11946             format("struct foo {\n"
11947                    "private:\n"
11948                    "\n\n\n"
11949                    "protected:\n"
11950                    "};\n",
11951                    Style)); // Based on new lines in original document and not
11952                             // on the setting.
11953 
11954   Style.MaxEmptyLinesToKeep = 10u;
11955   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11956   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11957   // Newlines are kept if they are greater than zero,
11958   // test::messUp removes all new lines which changes the logic
11959   EXPECT_EQ("struct foo {\n"
11960             "private:\n"
11961             "\n\n\n"
11962             "protected:\n"
11963             "};\n",
11964             format("struct foo {\n"
11965                    "private:\n"
11966                    "\n\n\n"
11967                    "protected:\n"
11968                    "};\n",
11969                    Style));
11970 
11971   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11972   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11973   // test::messUp removes all new lines which changes the logic
11974   EXPECT_EQ("struct foo {\n"
11975             "private:\n"
11976             "\n\n\n"
11977             "protected:\n"
11978             "};\n",
11979             format("struct foo {\n"
11980                    "private:\n"
11981                    "\n\n\n"
11982                    "protected:\n"
11983                    "};\n",
11984                    Style));
11985 
11986   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11987   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11988   EXPECT_EQ("struct foo {\n"
11989             "private:\n"
11990             "\n\n\n"
11991             "protected:\n"
11992             "};\n",
11993             format("struct foo {\n"
11994                    "private:\n"
11995                    "\n\n\n"
11996                    "protected:\n"
11997                    "};\n",
11998                    Style)); // test::messUp removes all new lines which changes
11999                             // the logic.
12000 
12001   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
12002   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
12003   verifyFormat("struct foo {\n"
12004                "private:\n"
12005                "protected:\n"
12006                "};\n",
12007                "struct foo {\n"
12008                "private:\n"
12009                "\n\n\n"
12010                "protected:\n"
12011                "};\n",
12012                Style);
12013 
12014   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
12015   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
12016   EXPECT_EQ("struct foo {\n"
12017             "private:\n"
12018             "\n\n\n"
12019             "protected:\n"
12020             "};\n",
12021             format("struct foo {\n"
12022                    "private:\n"
12023                    "\n\n\n"
12024                    "protected:\n"
12025                    "};\n",
12026                    Style)); // test::messUp removes all new lines which changes
12027                             // the logic.
12028 
12029   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
12030   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
12031   verifyFormat("struct foo {\n"
12032                "private:\n"
12033                "protected:\n"
12034                "};\n",
12035                "struct foo {\n"
12036                "private:\n"
12037                "\n\n\n"
12038                "protected:\n"
12039                "};\n",
12040                Style);
12041 
12042   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
12043   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
12044   verifyFormat("struct foo {\n"
12045                "private:\n"
12046                "protected:\n"
12047                "};\n",
12048                "struct foo {\n"
12049                "private:\n"
12050                "\n\n\n"
12051                "protected:\n"
12052                "};\n",
12053                Style);
12054 
12055   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
12056   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
12057   verifyFormat("struct foo {\n"
12058                "private:\n"
12059                "protected:\n"
12060                "};\n",
12061                "struct foo {\n"
12062                "private:\n"
12063                "\n\n\n"
12064                "protected:\n"
12065                "};\n",
12066                Style);
12067 
12068   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
12069   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
12070   verifyFormat("struct foo {\n"
12071                "private:\n"
12072                "protected:\n"
12073                "};\n",
12074                "struct foo {\n"
12075                "private:\n"
12076                "\n\n\n"
12077                "protected:\n"
12078                "};\n",
12079                Style);
12080 }
12081 
12082 TEST_F(FormatTest, FormatsArrays) {
12083   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
12084                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
12085   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
12086                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
12087   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
12088                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
12089   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12090                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
12091   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12092                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
12093   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12094                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
12095                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
12096   verifyFormat(
12097       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
12098       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
12099       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
12100   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
12101                "    .aaaaaaaaaaaaaaaaaaaaaa();");
12102 
12103   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
12104                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
12105   verifyFormat(
12106       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
12107       "                                  .aaaaaaa[0]\n"
12108       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
12109   verifyFormat("a[::b::c];");
12110 
12111   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
12112 
12113   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12114   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
12115 }
12116 
12117 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
12118   verifyFormat("(a)->b();");
12119   verifyFormat("--a;");
12120 }
12121 
12122 TEST_F(FormatTest, HandlesIncludeDirectives) {
12123   verifyFormat("#include <string>\n"
12124                "#include <a/b/c.h>\n"
12125                "#include \"a/b/string\"\n"
12126                "#include \"string.h\"\n"
12127                "#include \"string.h\"\n"
12128                "#include <a-a>\n"
12129                "#include < path with space >\n"
12130                "#include_next <test.h>"
12131                "#include \"abc.h\" // this is included for ABC\n"
12132                "#include \"some long include\" // with a comment\n"
12133                "#include \"some very long include path\"\n"
12134                "#include <some/very/long/include/path>\n",
12135                getLLVMStyleWithColumns(35));
12136   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
12137   EXPECT_EQ("#include <a>", format("#include<a>"));
12138 
12139   verifyFormat("#import <string>");
12140   verifyFormat("#import <a/b/c.h>");
12141   verifyFormat("#import \"a/b/string\"");
12142   verifyFormat("#import \"string.h\"");
12143   verifyFormat("#import \"string.h\"");
12144   verifyFormat("#if __has_include(<strstream>)\n"
12145                "#include <strstream>\n"
12146                "#endif");
12147 
12148   verifyFormat("#define MY_IMPORT <a/b>");
12149 
12150   verifyFormat("#if __has_include(<a/b>)");
12151   verifyFormat("#if __has_include_next(<a/b>)");
12152   verifyFormat("#define F __has_include(<a/b>)");
12153   verifyFormat("#define F __has_include_next(<a/b>)");
12154 
12155   // Protocol buffer definition or missing "#".
12156   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
12157                getLLVMStyleWithColumns(30));
12158 
12159   FormatStyle Style = getLLVMStyle();
12160   Style.AlwaysBreakBeforeMultilineStrings = true;
12161   Style.ColumnLimit = 0;
12162   verifyFormat("#import \"abc.h\"", Style);
12163 
12164   // But 'import' might also be a regular C++ namespace.
12165   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12166                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
12167 }
12168 
12169 //===----------------------------------------------------------------------===//
12170 // Error recovery tests.
12171 //===----------------------------------------------------------------------===//
12172 
12173 TEST_F(FormatTest, IncompleteParameterLists) {
12174   FormatStyle NoBinPacking = getLLVMStyle();
12175   NoBinPacking.BinPackParameters = false;
12176   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
12177                "                        double *min_x,\n"
12178                "                        double *max_x,\n"
12179                "                        double *min_y,\n"
12180                "                        double *max_y,\n"
12181                "                        double *min_z,\n"
12182                "                        double *max_z, ) {}",
12183                NoBinPacking);
12184 }
12185 
12186 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
12187   verifyFormat("void f() { return; }\n42");
12188   verifyFormat("void f() {\n"
12189                "  if (0)\n"
12190                "    return;\n"
12191                "}\n"
12192                "42");
12193   verifyFormat("void f() { return }\n42");
12194   verifyFormat("void f() {\n"
12195                "  if (0)\n"
12196                "    return\n"
12197                "}\n"
12198                "42");
12199 }
12200 
12201 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
12202   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
12203   EXPECT_EQ("void f() {\n"
12204             "  if (a)\n"
12205             "    return\n"
12206             "}",
12207             format("void  f  (  )  {  if  ( a )  return  }"));
12208   EXPECT_EQ("namespace N {\n"
12209             "void f()\n"
12210             "}",
12211             format("namespace  N  {  void f()  }"));
12212   EXPECT_EQ("namespace N {\n"
12213             "void f() {}\n"
12214             "void g()\n"
12215             "} // namespace N",
12216             format("namespace N  { void f( ) { } void g( ) }"));
12217 }
12218 
12219 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
12220   verifyFormat("int aaaaaaaa =\n"
12221                "    // Overlylongcomment\n"
12222                "    b;",
12223                getLLVMStyleWithColumns(20));
12224   verifyFormat("function(\n"
12225                "    ShortArgument,\n"
12226                "    LoooooooooooongArgument);\n",
12227                getLLVMStyleWithColumns(20));
12228 }
12229 
12230 TEST_F(FormatTest, IncorrectAccessSpecifier) {
12231   verifyFormat("public:");
12232   verifyFormat("class A {\n"
12233                "public\n"
12234                "  void f() {}\n"
12235                "};");
12236   verifyFormat("public\n"
12237                "int qwerty;");
12238   verifyFormat("public\n"
12239                "B {}");
12240   verifyFormat("public\n"
12241                "{}");
12242   verifyFormat("public\n"
12243                "B { int x; }");
12244 }
12245 
12246 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
12247   verifyFormat("{");
12248   verifyFormat("#})");
12249   verifyNoCrash("(/**/[:!] ?[).");
12250 }
12251 
12252 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
12253   // Found by oss-fuzz:
12254   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
12255   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
12256   Style.ColumnLimit = 60;
12257   verifyNoCrash(
12258       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
12259       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
12260       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
12261       Style);
12262 }
12263 
12264 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
12265   verifyFormat("do {\n}");
12266   verifyFormat("do {\n}\n"
12267                "f();");
12268   verifyFormat("do {\n}\n"
12269                "wheeee(fun);");
12270   verifyFormat("do {\n"
12271                "  f();\n"
12272                "}");
12273 }
12274 
12275 TEST_F(FormatTest, IncorrectCodeMissingParens) {
12276   verifyFormat("if {\n  foo;\n  foo();\n}");
12277   verifyFormat("switch {\n  foo;\n  foo();\n}");
12278   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
12279   verifyIncompleteFormat("ERROR: for target;");
12280   verifyFormat("while {\n  foo;\n  foo();\n}");
12281   verifyFormat("do {\n  foo;\n  foo();\n} while;");
12282 }
12283 
12284 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
12285   verifyIncompleteFormat("namespace {\n"
12286                          "class Foo { Foo (\n"
12287                          "};\n"
12288                          "} // namespace");
12289 }
12290 
12291 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
12292   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
12293   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
12294   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
12295   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
12296 
12297   EXPECT_EQ("{\n"
12298             "  {\n"
12299             "    breakme(\n"
12300             "        qwe);\n"
12301             "  }\n",
12302             format("{\n"
12303                    "    {\n"
12304                    " breakme(qwe);\n"
12305                    "}\n",
12306                    getLLVMStyleWithColumns(10)));
12307 }
12308 
12309 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
12310   verifyFormat("int x = {\n"
12311                "    avariable,\n"
12312                "    b(alongervariable)};",
12313                getLLVMStyleWithColumns(25));
12314 }
12315 
12316 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
12317   verifyFormat("return (a)(b){1, 2, 3};");
12318 }
12319 
12320 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
12321   verifyFormat("vector<int> x{1, 2, 3, 4};");
12322   verifyFormat("vector<int> x{\n"
12323                "    1,\n"
12324                "    2,\n"
12325                "    3,\n"
12326                "    4,\n"
12327                "};");
12328   verifyFormat("vector<T> x{{}, {}, {}, {}};");
12329   verifyFormat("f({1, 2});");
12330   verifyFormat("auto v = Foo{-1};");
12331   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
12332   verifyFormat("Class::Class : member{1, 2, 3} {}");
12333   verifyFormat("new vector<int>{1, 2, 3};");
12334   verifyFormat("new int[3]{1, 2, 3};");
12335   verifyFormat("new int{1};");
12336   verifyFormat("return {arg1, arg2};");
12337   verifyFormat("return {arg1, SomeType{parameter}};");
12338   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
12339   verifyFormat("new T{arg1, arg2};");
12340   verifyFormat("f(MyMap[{composite, key}]);");
12341   verifyFormat("class Class {\n"
12342                "  T member = {arg1, arg2};\n"
12343                "};");
12344   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
12345   verifyFormat("const struct A a = {.a = 1, .b = 2};");
12346   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
12347   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
12348   verifyFormat("int a = std::is_integral<int>{} + 0;");
12349 
12350   verifyFormat("int foo(int i) { return fo1{}(i); }");
12351   verifyFormat("int foo(int i) { return fo1{}(i); }");
12352   verifyFormat("auto i = decltype(x){};");
12353   verifyFormat("auto i = typeof(x){};");
12354   verifyFormat("auto i = _Atomic(x){};");
12355   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
12356   verifyFormat("Node n{1, Node{1000}, //\n"
12357                "       2};");
12358   verifyFormat("Aaaa aaaaaaa{\n"
12359                "    {\n"
12360                "        aaaa,\n"
12361                "    },\n"
12362                "};");
12363   verifyFormat("class C : public D {\n"
12364                "  SomeClass SC{2};\n"
12365                "};");
12366   verifyFormat("class C : public A {\n"
12367                "  class D : public B {\n"
12368                "    void f() { int i{2}; }\n"
12369                "  };\n"
12370                "};");
12371   verifyFormat("#define A {a, a},");
12372   // Don't confuse braced list initializers with compound statements.
12373   verifyFormat(
12374       "class A {\n"
12375       "  A() : a{} {}\n"
12376       "  A(int b) : b(b) {}\n"
12377       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12378       "  int a, b;\n"
12379       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12380       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12381       "{}\n"
12382       "};");
12383 
12384   // Avoid breaking between equal sign and opening brace
12385   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12386   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12387   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12388                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12389                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12390                "     {\"ccccccccccccccccccccc\", 2}};",
12391                AvoidBreakingFirstArgument);
12392 
12393   // Binpacking only if there is no trailing comma
12394   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12395                "                      cccccccccc, dddddddddd};",
12396                getLLVMStyleWithColumns(50));
12397   verifyFormat("const Aaaaaa aaaaa = {\n"
12398                "    aaaaaaaaaaa,\n"
12399                "    bbbbbbbbbbb,\n"
12400                "    ccccccccccc,\n"
12401                "    ddddddddddd,\n"
12402                "};",
12403                getLLVMStyleWithColumns(50));
12404 
12405   // Cases where distinguising braced lists and blocks is hard.
12406   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12407   verifyFormat("void f() {\n"
12408                "  return; // comment\n"
12409                "}\n"
12410                "SomeType t;");
12411   verifyFormat("void f() {\n"
12412                "  if (a) {\n"
12413                "    f();\n"
12414                "  }\n"
12415                "}\n"
12416                "SomeType t;");
12417 
12418   // In combination with BinPackArguments = false.
12419   FormatStyle NoBinPacking = getLLVMStyle();
12420   NoBinPacking.BinPackArguments = false;
12421   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12422                "                      bbbbb,\n"
12423                "                      ccccc,\n"
12424                "                      ddddd,\n"
12425                "                      eeeee,\n"
12426                "                      ffffff,\n"
12427                "                      ggggg,\n"
12428                "                      hhhhhh,\n"
12429                "                      iiiiii,\n"
12430                "                      jjjjjj,\n"
12431                "                      kkkkkk};",
12432                NoBinPacking);
12433   verifyFormat("const Aaaaaa aaaaa = {\n"
12434                "    aaaaa,\n"
12435                "    bbbbb,\n"
12436                "    ccccc,\n"
12437                "    ddddd,\n"
12438                "    eeeee,\n"
12439                "    ffffff,\n"
12440                "    ggggg,\n"
12441                "    hhhhhh,\n"
12442                "    iiiiii,\n"
12443                "    jjjjjj,\n"
12444                "    kkkkkk,\n"
12445                "};",
12446                NoBinPacking);
12447   verifyFormat(
12448       "const Aaaaaa aaaaa = {\n"
12449       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12450       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12451       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12452       "};",
12453       NoBinPacking);
12454 
12455   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12456   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12457             "    CDDDP83848_BMCR_REGISTER,\n"
12458             "    CDDDP83848_BMSR_REGISTER,\n"
12459             "    CDDDP83848_RBR_REGISTER};",
12460             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12461                    "                                CDDDP83848_BMSR_REGISTER,\n"
12462                    "                                CDDDP83848_RBR_REGISTER};",
12463                    NoBinPacking));
12464 
12465   // FIXME: The alignment of these trailing comments might be bad. Then again,
12466   // this might be utterly useless in real code.
12467   verifyFormat("Constructor::Constructor()\n"
12468                "    : some_value{         //\n"
12469                "                 aaaaaaa, //\n"
12470                "                 bbbbbbb} {}");
12471 
12472   // In braced lists, the first comment is always assumed to belong to the
12473   // first element. Thus, it can be moved to the next or previous line as
12474   // appropriate.
12475   EXPECT_EQ("function({// First element:\n"
12476             "          1,\n"
12477             "          // Second element:\n"
12478             "          2});",
12479             format("function({\n"
12480                    "    // First element:\n"
12481                    "    1,\n"
12482                    "    // Second element:\n"
12483                    "    2});"));
12484   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12485             "    // First element:\n"
12486             "    1,\n"
12487             "    // Second element:\n"
12488             "    2};",
12489             format("std::vector<int> MyNumbers{// First element:\n"
12490                    "                           1,\n"
12491                    "                           // Second element:\n"
12492                    "                           2};",
12493                    getLLVMStyleWithColumns(30)));
12494   // A trailing comma should still lead to an enforced line break and no
12495   // binpacking.
12496   EXPECT_EQ("vector<int> SomeVector = {\n"
12497             "    // aaa\n"
12498             "    1,\n"
12499             "    2,\n"
12500             "};",
12501             format("vector<int> SomeVector = { // aaa\n"
12502                    "    1, 2, };"));
12503 
12504   // C++11 brace initializer list l-braces should not be treated any differently
12505   // when breaking before lambda bodies is enabled
12506   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12507   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12508   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12509   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12510   verifyFormat(
12511       "std::runtime_error{\n"
12512       "    \"Long string which will force a break onto the next line...\"};",
12513       BreakBeforeLambdaBody);
12514 
12515   FormatStyle ExtraSpaces = getLLVMStyle();
12516   ExtraSpaces.Cpp11BracedListStyle = false;
12517   ExtraSpaces.ColumnLimit = 75;
12518   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12519   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12520   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12521   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12522   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12523   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12524   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12525   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12526   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12527   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12528   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12529   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12530   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12531   verifyFormat("class Class {\n"
12532                "  T member = { arg1, arg2 };\n"
12533                "};",
12534                ExtraSpaces);
12535   verifyFormat(
12536       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12537       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12538       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12539       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12540       ExtraSpaces);
12541   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12542   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12543                ExtraSpaces);
12544   verifyFormat(
12545       "someFunction(OtherParam,\n"
12546       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12547       "                         param1, param2,\n"
12548       "                         // comment 2\n"
12549       "                         param3, param4 });",
12550       ExtraSpaces);
12551   verifyFormat(
12552       "std::this_thread::sleep_for(\n"
12553       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12554       ExtraSpaces);
12555   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12556                "    aaaaaaa,\n"
12557                "    aaaaaaaaaa,\n"
12558                "    aaaaa,\n"
12559                "    aaaaaaaaaaaaaaa,\n"
12560                "    aaa,\n"
12561                "    aaaaaaaaaa,\n"
12562                "    a,\n"
12563                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12564                "    aaaaaaaaaaaa,\n"
12565                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12566                "    aaaaaaa,\n"
12567                "    a};");
12568   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12569   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12570   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12571 
12572   // Avoid breaking between initializer/equal sign and opening brace
12573   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12574   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12575                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12576                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12577                "  { \"ccccccccccccccccccccc\", 2 }\n"
12578                "};",
12579                ExtraSpaces);
12580   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12581                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12582                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12583                "  { \"ccccccccccccccccccccc\", 2 }\n"
12584                "};",
12585                ExtraSpaces);
12586 
12587   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12588   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12589   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12590   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12591 
12592   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12593   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12594   SpaceBetweenBraces.SpacesInParentheses = true;
12595   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12596   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12597   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12598   verifyFormat("vector< int > x{ // comment 1\n"
12599                "                 1, 2, 3, 4 };",
12600                SpaceBetweenBraces);
12601   SpaceBetweenBraces.ColumnLimit = 20;
12602   EXPECT_EQ("vector< int > x{\n"
12603             "    1, 2, 3, 4 };",
12604             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12605   SpaceBetweenBraces.ColumnLimit = 24;
12606   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12607             "                 3, 4 };",
12608             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12609   EXPECT_EQ("vector< int > x{\n"
12610             "    1,\n"
12611             "    2,\n"
12612             "    3,\n"
12613             "    4,\n"
12614             "};",
12615             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12616   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12617   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12618   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12619 }
12620 
12621 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12622   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12623                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12624                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12625                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12626                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12627                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12628   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12629                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12630                "                 1, 22, 333, 4444, 55555, //\n"
12631                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12632                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12633   verifyFormat(
12634       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12635       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12636       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12637       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12638       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12639       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12640       "                 7777777};");
12641   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12642                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12643                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12644   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12645                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12646                "    // Separating comment.\n"
12647                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12648   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12649                "    // Leading comment\n"
12650                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12651                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12652   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12653                "                 1, 1, 1, 1};",
12654                getLLVMStyleWithColumns(39));
12655   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12656                "                 1, 1, 1, 1};",
12657                getLLVMStyleWithColumns(38));
12658   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12659                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12660                getLLVMStyleWithColumns(43));
12661   verifyFormat(
12662       "static unsigned SomeValues[10][3] = {\n"
12663       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12664       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12665   verifyFormat("static auto fields = new vector<string>{\n"
12666                "    \"aaaaaaaaaaaaa\",\n"
12667                "    \"aaaaaaaaaaaaa\",\n"
12668                "    \"aaaaaaaaaaaa\",\n"
12669                "    \"aaaaaaaaaaaaaa\",\n"
12670                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12671                "    \"aaaaaaaaaaaa\",\n"
12672                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12673                "};");
12674   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12675   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12676                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12677                "                 3, cccccccccccccccccccccc};",
12678                getLLVMStyleWithColumns(60));
12679 
12680   // Trailing commas.
12681   verifyFormat("vector<int> x = {\n"
12682                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12683                "};",
12684                getLLVMStyleWithColumns(39));
12685   verifyFormat("vector<int> x = {\n"
12686                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12687                "};",
12688                getLLVMStyleWithColumns(39));
12689   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12690                "                 1, 1, 1, 1,\n"
12691                "                 /**/ /**/};",
12692                getLLVMStyleWithColumns(39));
12693 
12694   // Trailing comment in the first line.
12695   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12696                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12697                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12698                "    11111111,   22222222,   333333333,   44444444};");
12699   // Trailing comment in the last line.
12700   verifyFormat("int aaaaa[] = {\n"
12701                "    1, 2, 3, // comment\n"
12702                "    4, 5, 6  // comment\n"
12703                "};");
12704 
12705   // With nested lists, we should either format one item per line or all nested
12706   // lists one on line.
12707   // FIXME: For some nested lists, we can do better.
12708   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12709                "        {aaaaaaaaaaaaaaaaaaa},\n"
12710                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12711                "        {aaaaaaaaaaaaaaaaa}};",
12712                getLLVMStyleWithColumns(60));
12713   verifyFormat(
12714       "SomeStruct my_struct_array = {\n"
12715       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12716       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12717       "    {aaa, aaa},\n"
12718       "    {aaa, aaa},\n"
12719       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12720       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12721       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12722 
12723   // No column layout should be used here.
12724   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12725                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12726 
12727   verifyNoCrash("a<,");
12728 
12729   // No braced initializer here.
12730   verifyFormat("void f() {\n"
12731                "  struct Dummy {};\n"
12732                "  f(v);\n"
12733                "}");
12734 
12735   // Long lists should be formatted in columns even if they are nested.
12736   verifyFormat(
12737       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12738       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12739       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12740       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12741       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12742       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12743 
12744   // Allow "single-column" layout even if that violates the column limit. There
12745   // isn't going to be a better way.
12746   verifyFormat("std::vector<int> a = {\n"
12747                "    aaaaaaaa,\n"
12748                "    aaaaaaaa,\n"
12749                "    aaaaaaaa,\n"
12750                "    aaaaaaaa,\n"
12751                "    aaaaaaaaaa,\n"
12752                "    aaaaaaaa,\n"
12753                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12754                getLLVMStyleWithColumns(30));
12755   verifyFormat("vector<int> aaaa = {\n"
12756                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12757                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12758                "    aaaaaa.aaaaaaa,\n"
12759                "    aaaaaa.aaaaaaa,\n"
12760                "    aaaaaa.aaaaaaa,\n"
12761                "    aaaaaa.aaaaaaa,\n"
12762                "};");
12763 
12764   // Don't create hanging lists.
12765   verifyFormat("someFunction(Param, {List1, List2,\n"
12766                "                     List3});",
12767                getLLVMStyleWithColumns(35));
12768   verifyFormat("someFunction(Param, Param,\n"
12769                "             {List1, List2,\n"
12770                "              List3});",
12771                getLLVMStyleWithColumns(35));
12772   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12773                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12774 }
12775 
12776 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12777   FormatStyle DoNotMerge = getLLVMStyle();
12778   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12779 
12780   verifyFormat("void f() { return 42; }");
12781   verifyFormat("void f() {\n"
12782                "  return 42;\n"
12783                "}",
12784                DoNotMerge);
12785   verifyFormat("void f() {\n"
12786                "  // Comment\n"
12787                "}");
12788   verifyFormat("{\n"
12789                "#error {\n"
12790                "  int a;\n"
12791                "}");
12792   verifyFormat("{\n"
12793                "  int a;\n"
12794                "#error {\n"
12795                "}");
12796   verifyFormat("void f() {} // comment");
12797   verifyFormat("void f() { int a; } // comment");
12798   verifyFormat("void f() {\n"
12799                "} // comment",
12800                DoNotMerge);
12801   verifyFormat("void f() {\n"
12802                "  int a;\n"
12803                "} // comment",
12804                DoNotMerge);
12805   verifyFormat("void f() {\n"
12806                "} // comment",
12807                getLLVMStyleWithColumns(15));
12808 
12809   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12810   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12811 
12812   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12813   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12814   verifyFormat("class C {\n"
12815                "  C()\n"
12816                "      : iiiiiiii(nullptr),\n"
12817                "        kkkkkkk(nullptr),\n"
12818                "        mmmmmmm(nullptr),\n"
12819                "        nnnnnnn(nullptr) {}\n"
12820                "};",
12821                getGoogleStyle());
12822 
12823   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12824   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12825   EXPECT_EQ("class C {\n"
12826             "  A() : b(0) {}\n"
12827             "};",
12828             format("class C{A():b(0){}};", NoColumnLimit));
12829   EXPECT_EQ("A()\n"
12830             "    : b(0) {\n"
12831             "}",
12832             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12833 
12834   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12835   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12836       FormatStyle::SFS_None;
12837   EXPECT_EQ("A()\n"
12838             "    : b(0) {\n"
12839             "}",
12840             format("A():b(0){}", DoNotMergeNoColumnLimit));
12841   EXPECT_EQ("A()\n"
12842             "    : b(0) {\n"
12843             "}",
12844             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12845 
12846   verifyFormat("#define A          \\\n"
12847                "  void f() {       \\\n"
12848                "    int i;         \\\n"
12849                "  }",
12850                getLLVMStyleWithColumns(20));
12851   verifyFormat("#define A           \\\n"
12852                "  void f() { int i; }",
12853                getLLVMStyleWithColumns(21));
12854   verifyFormat("#define A            \\\n"
12855                "  void f() {         \\\n"
12856                "    int i;           \\\n"
12857                "  }                  \\\n"
12858                "  int j;",
12859                getLLVMStyleWithColumns(22));
12860   verifyFormat("#define A             \\\n"
12861                "  void f() { int i; } \\\n"
12862                "  int j;",
12863                getLLVMStyleWithColumns(23));
12864 }
12865 
12866 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12867   FormatStyle MergeEmptyOnly = getLLVMStyle();
12868   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12869   verifyFormat("class C {\n"
12870                "  int f() {}\n"
12871                "};",
12872                MergeEmptyOnly);
12873   verifyFormat("class C {\n"
12874                "  int f() {\n"
12875                "    return 42;\n"
12876                "  }\n"
12877                "};",
12878                MergeEmptyOnly);
12879   verifyFormat("int f() {}", MergeEmptyOnly);
12880   verifyFormat("int f() {\n"
12881                "  return 42;\n"
12882                "}",
12883                MergeEmptyOnly);
12884 
12885   // Also verify behavior when BraceWrapping.AfterFunction = true
12886   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12887   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12888   verifyFormat("int f() {}", MergeEmptyOnly);
12889   verifyFormat("class C {\n"
12890                "  int f() {}\n"
12891                "};",
12892                MergeEmptyOnly);
12893 }
12894 
12895 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12896   FormatStyle MergeInlineOnly = getLLVMStyle();
12897   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12898   verifyFormat("class C {\n"
12899                "  int f() { return 42; }\n"
12900                "};",
12901                MergeInlineOnly);
12902   verifyFormat("int f() {\n"
12903                "  return 42;\n"
12904                "}",
12905                MergeInlineOnly);
12906 
12907   // SFS_Inline implies SFS_Empty
12908   verifyFormat("class C {\n"
12909                "  int f() {}\n"
12910                "};",
12911                MergeInlineOnly);
12912   verifyFormat("int f() {}", MergeInlineOnly);
12913   // https://llvm.org/PR54147
12914   verifyFormat("auto lambda = []() {\n"
12915                "  // comment\n"
12916                "  f();\n"
12917                "  g();\n"
12918                "};",
12919                MergeInlineOnly);
12920 
12921   verifyFormat("class C {\n"
12922                "#ifdef A\n"
12923                "  int f() { return 42; }\n"
12924                "#endif\n"
12925                "};",
12926                MergeInlineOnly);
12927 
12928   verifyFormat("struct S {\n"
12929                "// comment\n"
12930                "#ifdef FOO\n"
12931                "  int foo() { bar(); }\n"
12932                "#endif\n"
12933                "};",
12934                MergeInlineOnly);
12935 
12936   // Also verify behavior when BraceWrapping.AfterFunction = true
12937   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12938   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12939   verifyFormat("class C {\n"
12940                "  int f() { return 42; }\n"
12941                "};",
12942                MergeInlineOnly);
12943   verifyFormat("int f()\n"
12944                "{\n"
12945                "  return 42;\n"
12946                "}",
12947                MergeInlineOnly);
12948 
12949   // SFS_Inline implies SFS_Empty
12950   verifyFormat("int f() {}", MergeInlineOnly);
12951   verifyFormat("class C {\n"
12952                "  int f() {}\n"
12953                "};",
12954                MergeInlineOnly);
12955 
12956   MergeInlineOnly.BraceWrapping.AfterClass = true;
12957   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12958   verifyFormat("class C\n"
12959                "{\n"
12960                "  int f() { return 42; }\n"
12961                "};",
12962                MergeInlineOnly);
12963   verifyFormat("struct C\n"
12964                "{\n"
12965                "  int f() { return 42; }\n"
12966                "};",
12967                MergeInlineOnly);
12968   verifyFormat("int f()\n"
12969                "{\n"
12970                "  return 42;\n"
12971                "}",
12972                MergeInlineOnly);
12973   verifyFormat("int f() {}", MergeInlineOnly);
12974   verifyFormat("class C\n"
12975                "{\n"
12976                "  int f() { return 42; }\n"
12977                "};",
12978                MergeInlineOnly);
12979   verifyFormat("struct C\n"
12980                "{\n"
12981                "  int f() { return 42; }\n"
12982                "};",
12983                MergeInlineOnly);
12984   verifyFormat("struct C\n"
12985                "// comment\n"
12986                "/* comment */\n"
12987                "// comment\n"
12988                "{\n"
12989                "  int f() { return 42; }\n"
12990                "};",
12991                MergeInlineOnly);
12992   verifyFormat("/* comment */ struct C\n"
12993                "{\n"
12994                "  int f() { return 42; }\n"
12995                "};",
12996                MergeInlineOnly);
12997 }
12998 
12999 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
13000   FormatStyle MergeInlineOnly = getLLVMStyle();
13001   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
13002       FormatStyle::SFS_InlineOnly;
13003   verifyFormat("class C {\n"
13004                "  int f() { return 42; }\n"
13005                "};",
13006                MergeInlineOnly);
13007   verifyFormat("int f() {\n"
13008                "  return 42;\n"
13009                "}",
13010                MergeInlineOnly);
13011 
13012   // SFS_InlineOnly does not imply SFS_Empty
13013   verifyFormat("class C {\n"
13014                "  int f() {}\n"
13015                "};",
13016                MergeInlineOnly);
13017   verifyFormat("int f() {\n"
13018                "}",
13019                MergeInlineOnly);
13020 
13021   // Also verify behavior when BraceWrapping.AfterFunction = true
13022   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
13023   MergeInlineOnly.BraceWrapping.AfterFunction = true;
13024   verifyFormat("class C {\n"
13025                "  int f() { return 42; }\n"
13026                "};",
13027                MergeInlineOnly);
13028   verifyFormat("int f()\n"
13029                "{\n"
13030                "  return 42;\n"
13031                "}",
13032                MergeInlineOnly);
13033 
13034   // SFS_InlineOnly does not imply SFS_Empty
13035   verifyFormat("int f()\n"
13036                "{\n"
13037                "}",
13038                MergeInlineOnly);
13039   verifyFormat("class C {\n"
13040                "  int f() {}\n"
13041                "};",
13042                MergeInlineOnly);
13043 }
13044 
13045 TEST_F(FormatTest, SplitEmptyFunction) {
13046   FormatStyle Style = getLLVMStyleWithColumns(40);
13047   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
13048   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13049   Style.BraceWrapping.AfterFunction = true;
13050   Style.BraceWrapping.SplitEmptyFunction = false;
13051 
13052   verifyFormat("int f()\n"
13053                "{}",
13054                Style);
13055   verifyFormat("int f()\n"
13056                "{\n"
13057                "  return 42;\n"
13058                "}",
13059                Style);
13060   verifyFormat("int f()\n"
13061                "{\n"
13062                "  // some comment\n"
13063                "}",
13064                Style);
13065 
13066   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
13067   verifyFormat("int f() {}", Style);
13068   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13069                "{}",
13070                Style);
13071   verifyFormat("int f()\n"
13072                "{\n"
13073                "  return 0;\n"
13074                "}",
13075                Style);
13076 
13077   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
13078   verifyFormat("class Foo {\n"
13079                "  int f() {}\n"
13080                "};\n",
13081                Style);
13082   verifyFormat("class Foo {\n"
13083                "  int f() { return 0; }\n"
13084                "};\n",
13085                Style);
13086   verifyFormat("class Foo {\n"
13087                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13088                "  {}\n"
13089                "};\n",
13090                Style);
13091   verifyFormat("class Foo {\n"
13092                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13093                "  {\n"
13094                "    return 0;\n"
13095                "  }\n"
13096                "};\n",
13097                Style);
13098 
13099   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13100   verifyFormat("int f() {}", Style);
13101   verifyFormat("int f() { return 0; }", Style);
13102   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13103                "{}",
13104                Style);
13105   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13106                "{\n"
13107                "  return 0;\n"
13108                "}",
13109                Style);
13110 }
13111 
13112 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
13113   FormatStyle Style = getLLVMStyleWithColumns(40);
13114   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
13115   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13116   Style.BraceWrapping.AfterFunction = true;
13117   Style.BraceWrapping.SplitEmptyFunction = true;
13118   Style.BraceWrapping.SplitEmptyRecord = false;
13119 
13120   verifyFormat("class C {};", Style);
13121   verifyFormat("struct C {};", Style);
13122   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
13123                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
13124                "{\n"
13125                "}",
13126                Style);
13127   verifyFormat("class C {\n"
13128                "  C()\n"
13129                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
13130                "        bbbbbbbbbbbbbbbbbbb()\n"
13131                "  {\n"
13132                "  }\n"
13133                "  void\n"
13134                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
13135                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
13136                "  {\n"
13137                "  }\n"
13138                "};",
13139                Style);
13140 }
13141 
13142 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
13143   FormatStyle Style = getLLVMStyle();
13144   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13145   verifyFormat("#ifdef A\n"
13146                "int f() {}\n"
13147                "#else\n"
13148                "int g() {}\n"
13149                "#endif",
13150                Style);
13151 }
13152 
13153 TEST_F(FormatTest, SplitEmptyClass) {
13154   FormatStyle Style = getLLVMStyle();
13155   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13156   Style.BraceWrapping.AfterClass = true;
13157   Style.BraceWrapping.SplitEmptyRecord = false;
13158 
13159   verifyFormat("class Foo\n"
13160                "{};",
13161                Style);
13162   verifyFormat("/* something */ class Foo\n"
13163                "{};",
13164                Style);
13165   verifyFormat("template <typename X> class Foo\n"
13166                "{};",
13167                Style);
13168   verifyFormat("class Foo\n"
13169                "{\n"
13170                "  Foo();\n"
13171                "};",
13172                Style);
13173   verifyFormat("typedef class Foo\n"
13174                "{\n"
13175                "} Foo_t;",
13176                Style);
13177 
13178   Style.BraceWrapping.SplitEmptyRecord = true;
13179   Style.BraceWrapping.AfterStruct = true;
13180   verifyFormat("class rep\n"
13181                "{\n"
13182                "};",
13183                Style);
13184   verifyFormat("struct rep\n"
13185                "{\n"
13186                "};",
13187                Style);
13188   verifyFormat("template <typename T> class rep\n"
13189                "{\n"
13190                "};",
13191                Style);
13192   verifyFormat("template <typename T> struct rep\n"
13193                "{\n"
13194                "};",
13195                Style);
13196   verifyFormat("class rep\n"
13197                "{\n"
13198                "  int x;\n"
13199                "};",
13200                Style);
13201   verifyFormat("struct rep\n"
13202                "{\n"
13203                "  int x;\n"
13204                "};",
13205                Style);
13206   verifyFormat("template <typename T> class rep\n"
13207                "{\n"
13208                "  int x;\n"
13209                "};",
13210                Style);
13211   verifyFormat("template <typename T> struct rep\n"
13212                "{\n"
13213                "  int x;\n"
13214                "};",
13215                Style);
13216   verifyFormat("template <typename T> class rep // Foo\n"
13217                "{\n"
13218                "  int x;\n"
13219                "};",
13220                Style);
13221   verifyFormat("template <typename T> struct rep // Bar\n"
13222                "{\n"
13223                "  int x;\n"
13224                "};",
13225                Style);
13226 
13227   verifyFormat("template <typename T> class rep<T>\n"
13228                "{\n"
13229                "  int x;\n"
13230                "};",
13231                Style);
13232 
13233   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13234                "{\n"
13235                "  int x;\n"
13236                "};",
13237                Style);
13238   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13239                "{\n"
13240                "};",
13241                Style);
13242 
13243   verifyFormat("#include \"stdint.h\"\n"
13244                "namespace rep {}",
13245                Style);
13246   verifyFormat("#include <stdint.h>\n"
13247                "namespace rep {}",
13248                Style);
13249   verifyFormat("#include <stdint.h>\n"
13250                "namespace rep {}",
13251                "#include <stdint.h>\n"
13252                "namespace rep {\n"
13253                "\n"
13254                "\n"
13255                "}",
13256                Style);
13257 }
13258 
13259 TEST_F(FormatTest, SplitEmptyStruct) {
13260   FormatStyle Style = getLLVMStyle();
13261   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13262   Style.BraceWrapping.AfterStruct = true;
13263   Style.BraceWrapping.SplitEmptyRecord = false;
13264 
13265   verifyFormat("struct Foo\n"
13266                "{};",
13267                Style);
13268   verifyFormat("/* something */ struct Foo\n"
13269                "{};",
13270                Style);
13271   verifyFormat("template <typename X> struct Foo\n"
13272                "{};",
13273                Style);
13274   verifyFormat("struct Foo\n"
13275                "{\n"
13276                "  Foo();\n"
13277                "};",
13278                Style);
13279   verifyFormat("typedef struct Foo\n"
13280                "{\n"
13281                "} Foo_t;",
13282                Style);
13283   // typedef struct Bar {} Bar_t;
13284 }
13285 
13286 TEST_F(FormatTest, SplitEmptyUnion) {
13287   FormatStyle Style = getLLVMStyle();
13288   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13289   Style.BraceWrapping.AfterUnion = true;
13290   Style.BraceWrapping.SplitEmptyRecord = false;
13291 
13292   verifyFormat("union Foo\n"
13293                "{};",
13294                Style);
13295   verifyFormat("/* something */ union Foo\n"
13296                "{};",
13297                Style);
13298   verifyFormat("union Foo\n"
13299                "{\n"
13300                "  A,\n"
13301                "};",
13302                Style);
13303   verifyFormat("typedef union Foo\n"
13304                "{\n"
13305                "} Foo_t;",
13306                Style);
13307 }
13308 
13309 TEST_F(FormatTest, SplitEmptyNamespace) {
13310   FormatStyle Style = getLLVMStyle();
13311   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13312   Style.BraceWrapping.AfterNamespace = true;
13313   Style.BraceWrapping.SplitEmptyNamespace = false;
13314 
13315   verifyFormat("namespace Foo\n"
13316                "{};",
13317                Style);
13318   verifyFormat("/* something */ namespace Foo\n"
13319                "{};",
13320                Style);
13321   verifyFormat("inline namespace Foo\n"
13322                "{};",
13323                Style);
13324   verifyFormat("/* something */ inline namespace Foo\n"
13325                "{};",
13326                Style);
13327   verifyFormat("export namespace Foo\n"
13328                "{};",
13329                Style);
13330   verifyFormat("namespace Foo\n"
13331                "{\n"
13332                "void Bar();\n"
13333                "};",
13334                Style);
13335 }
13336 
13337 TEST_F(FormatTest, NeverMergeShortRecords) {
13338   FormatStyle Style = getLLVMStyle();
13339 
13340   verifyFormat("class Foo {\n"
13341                "  Foo();\n"
13342                "};",
13343                Style);
13344   verifyFormat("typedef class Foo {\n"
13345                "  Foo();\n"
13346                "} Foo_t;",
13347                Style);
13348   verifyFormat("struct Foo {\n"
13349                "  Foo();\n"
13350                "};",
13351                Style);
13352   verifyFormat("typedef struct Foo {\n"
13353                "  Foo();\n"
13354                "} Foo_t;",
13355                Style);
13356   verifyFormat("union Foo {\n"
13357                "  A,\n"
13358                "};",
13359                Style);
13360   verifyFormat("typedef union Foo {\n"
13361                "  A,\n"
13362                "} Foo_t;",
13363                Style);
13364   verifyFormat("namespace Foo {\n"
13365                "void Bar();\n"
13366                "};",
13367                Style);
13368 
13369   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13370   Style.BraceWrapping.AfterClass = true;
13371   Style.BraceWrapping.AfterStruct = true;
13372   Style.BraceWrapping.AfterUnion = true;
13373   Style.BraceWrapping.AfterNamespace = true;
13374   verifyFormat("class Foo\n"
13375                "{\n"
13376                "  Foo();\n"
13377                "};",
13378                Style);
13379   verifyFormat("typedef class Foo\n"
13380                "{\n"
13381                "  Foo();\n"
13382                "} Foo_t;",
13383                Style);
13384   verifyFormat("struct Foo\n"
13385                "{\n"
13386                "  Foo();\n"
13387                "};",
13388                Style);
13389   verifyFormat("typedef struct Foo\n"
13390                "{\n"
13391                "  Foo();\n"
13392                "} Foo_t;",
13393                Style);
13394   verifyFormat("union Foo\n"
13395                "{\n"
13396                "  A,\n"
13397                "};",
13398                Style);
13399   verifyFormat("typedef union Foo\n"
13400                "{\n"
13401                "  A,\n"
13402                "} Foo_t;",
13403                Style);
13404   verifyFormat("namespace Foo\n"
13405                "{\n"
13406                "void Bar();\n"
13407                "};",
13408                Style);
13409 }
13410 
13411 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13412   // Elaborate type variable declarations.
13413   verifyFormat("struct foo a = {bar};\nint n;");
13414   verifyFormat("class foo a = {bar};\nint n;");
13415   verifyFormat("union foo a = {bar};\nint n;");
13416 
13417   // Elaborate types inside function definitions.
13418   verifyFormat("struct foo f() {}\nint n;");
13419   verifyFormat("class foo f() {}\nint n;");
13420   verifyFormat("union foo f() {}\nint n;");
13421 
13422   // Templates.
13423   verifyFormat("template <class X> void f() {}\nint n;");
13424   verifyFormat("template <struct X> void f() {}\nint n;");
13425   verifyFormat("template <union X> void f() {}\nint n;");
13426 
13427   // Actual definitions...
13428   verifyFormat("struct {\n} n;");
13429   verifyFormat(
13430       "template <template <class T, class Y>, class Z> class X {\n} n;");
13431   verifyFormat("union Z {\n  int n;\n} x;");
13432   verifyFormat("class MACRO Z {\n} n;");
13433   verifyFormat("class MACRO(X) Z {\n} n;");
13434   verifyFormat("class __attribute__(X) Z {\n} n;");
13435   verifyFormat("class __declspec(X) Z {\n} n;");
13436   verifyFormat("class A##B##C {\n} n;");
13437   verifyFormat("class alignas(16) Z {\n} n;");
13438   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13439   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13440 
13441   // Redefinition from nested context:
13442   verifyFormat("class A::B::C {\n} n;");
13443 
13444   // Template definitions.
13445   verifyFormat(
13446       "template <typename F>\n"
13447       "Matcher(const Matcher<F> &Other,\n"
13448       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13449       "                             !is_same<F, T>::value>::type * = 0)\n"
13450       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13451 
13452   // FIXME: This is still incorrectly handled at the formatter side.
13453   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13454   verifyFormat("int i = SomeFunction(a<b, a> b);");
13455 
13456   // FIXME:
13457   // This now gets parsed incorrectly as class definition.
13458   // verifyFormat("class A<int> f() {\n}\nint n;");
13459 
13460   // Elaborate types where incorrectly parsing the structural element would
13461   // break the indent.
13462   verifyFormat("if (true)\n"
13463                "  class X x;\n"
13464                "else\n"
13465                "  f();\n");
13466 
13467   // This is simply incomplete. Formatting is not important, but must not crash.
13468   verifyFormat("class A:");
13469 }
13470 
13471 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13472   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13473             format("#error Leave     all         white!!!!! space* alone!\n"));
13474   EXPECT_EQ(
13475       "#warning Leave     all         white!!!!! space* alone!\n",
13476       format("#warning Leave     all         white!!!!! space* alone!\n"));
13477   EXPECT_EQ("#error 1", format("  #  error   1"));
13478   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13479 }
13480 
13481 TEST_F(FormatTest, FormatHashIfExpressions) {
13482   verifyFormat("#if AAAA && BBBB");
13483   verifyFormat("#if (AAAA && BBBB)");
13484   verifyFormat("#elif (AAAA && BBBB)");
13485   // FIXME: Come up with a better indentation for #elif.
13486   verifyFormat(
13487       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13488       "    defined(BBBBBBBB)\n"
13489       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13490       "    defined(BBBBBBBB)\n"
13491       "#endif",
13492       getLLVMStyleWithColumns(65));
13493 }
13494 
13495 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13496   FormatStyle AllowsMergedIf = getGoogleStyle();
13497   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13498       FormatStyle::SIS_WithoutElse;
13499   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13500   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13501   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13502   EXPECT_EQ("if (true) return 42;",
13503             format("if (true)\nreturn 42;", AllowsMergedIf));
13504   FormatStyle ShortMergedIf = AllowsMergedIf;
13505   ShortMergedIf.ColumnLimit = 25;
13506   verifyFormat("#define A \\\n"
13507                "  if (true) return 42;",
13508                ShortMergedIf);
13509   verifyFormat("#define A \\\n"
13510                "  f();    \\\n"
13511                "  if (true)\n"
13512                "#define B",
13513                ShortMergedIf);
13514   verifyFormat("#define A \\\n"
13515                "  f();    \\\n"
13516                "  if (true)\n"
13517                "g();",
13518                ShortMergedIf);
13519   verifyFormat("{\n"
13520                "#ifdef A\n"
13521                "  // Comment\n"
13522                "  if (true) continue;\n"
13523                "#endif\n"
13524                "  // Comment\n"
13525                "  if (true) continue;\n"
13526                "}",
13527                ShortMergedIf);
13528   ShortMergedIf.ColumnLimit = 33;
13529   verifyFormat("#define A \\\n"
13530                "  if constexpr (true) return 42;",
13531                ShortMergedIf);
13532   verifyFormat("#define A \\\n"
13533                "  if CONSTEXPR (true) return 42;",
13534                ShortMergedIf);
13535   ShortMergedIf.ColumnLimit = 29;
13536   verifyFormat("#define A                   \\\n"
13537                "  if (aaaaaaaaaa) return 1; \\\n"
13538                "  return 2;",
13539                ShortMergedIf);
13540   ShortMergedIf.ColumnLimit = 28;
13541   verifyFormat("#define A         \\\n"
13542                "  if (aaaaaaaaaa) \\\n"
13543                "    return 1;     \\\n"
13544                "  return 2;",
13545                ShortMergedIf);
13546   verifyFormat("#define A                \\\n"
13547                "  if constexpr (aaaaaaa) \\\n"
13548                "    return 1;            \\\n"
13549                "  return 2;",
13550                ShortMergedIf);
13551   verifyFormat("#define A                \\\n"
13552                "  if CONSTEXPR (aaaaaaa) \\\n"
13553                "    return 1;            \\\n"
13554                "  return 2;",
13555                ShortMergedIf);
13556 
13557   verifyFormat("//\n"
13558                "#define a \\\n"
13559                "  if      \\\n"
13560                "  0",
13561                getChromiumStyle(FormatStyle::LK_Cpp));
13562 }
13563 
13564 TEST_F(FormatTest, FormatStarDependingOnContext) {
13565   verifyFormat("void f(int *a);");
13566   verifyFormat("void f() { f(fint * b); }");
13567   verifyFormat("class A {\n  void f(int *a);\n};");
13568   verifyFormat("class A {\n  int *a;\n};");
13569   verifyFormat("namespace a {\n"
13570                "namespace b {\n"
13571                "class A {\n"
13572                "  void f() {}\n"
13573                "  int *a;\n"
13574                "};\n"
13575                "} // namespace b\n"
13576                "} // namespace a");
13577 }
13578 
13579 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13580   verifyFormat("while");
13581   verifyFormat("operator");
13582 }
13583 
13584 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13585   // This code would be painfully slow to format if we didn't skip it.
13586   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
13587                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13588                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13589                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13590                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13591                    "A(1, 1)\n"
13592                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
13593                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13594                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13595                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13596                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13597                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13598                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13599                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13600                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
13601                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13602   // Deeply nested part is untouched, rest is formatted.
13603   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13604             format(std::string("int    i;\n") + Code + "int    j;\n",
13605                    getLLVMStyle(), SC_ExpectIncomplete));
13606 }
13607 
13608 //===----------------------------------------------------------------------===//
13609 // Objective-C tests.
13610 //===----------------------------------------------------------------------===//
13611 
13612 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13613   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13614   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13615             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13616   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13617   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13618   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13619             format("-(NSInteger)Method3:(id)anObject;"));
13620   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13621             format("-(NSInteger)Method4:(id)anObject;"));
13622   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13623             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13624   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13625             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13626   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13627             "forAllCells:(BOOL)flag;",
13628             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13629                    "forAllCells:(BOOL)flag;"));
13630 
13631   // Very long objectiveC method declaration.
13632   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13633                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13634   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13635                "                    inRange:(NSRange)range\n"
13636                "                   outRange:(NSRange)out_range\n"
13637                "                  outRange1:(NSRange)out_range1\n"
13638                "                  outRange2:(NSRange)out_range2\n"
13639                "                  outRange3:(NSRange)out_range3\n"
13640                "                  outRange4:(NSRange)out_range4\n"
13641                "                  outRange5:(NSRange)out_range5\n"
13642                "                  outRange6:(NSRange)out_range6\n"
13643                "                  outRange7:(NSRange)out_range7\n"
13644                "                  outRange8:(NSRange)out_range8\n"
13645                "                  outRange9:(NSRange)out_range9;");
13646 
13647   // When the function name has to be wrapped.
13648   FormatStyle Style = getLLVMStyle();
13649   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13650   // and always indents instead.
13651   Style.IndentWrappedFunctionNames = false;
13652   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13653                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13654                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13655                "}",
13656                Style);
13657   Style.IndentWrappedFunctionNames = true;
13658   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13659                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13660                "               anotherName:(NSString)dddddddddddddd {\n"
13661                "}",
13662                Style);
13663 
13664   verifyFormat("- (int)sum:(vector<int>)numbers;");
13665   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13666   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13667   // protocol lists (but not for template classes):
13668   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13669 
13670   verifyFormat("- (int (*)())foo:(int (*)())f;");
13671   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13672 
13673   // If there's no return type (very rare in practice!), LLVM and Google style
13674   // agree.
13675   verifyFormat("- foo;");
13676   verifyFormat("- foo:(int)f;");
13677   verifyGoogleFormat("- foo:(int)foo;");
13678 }
13679 
13680 TEST_F(FormatTest, BreaksStringLiterals) {
13681   EXPECT_EQ("\"some text \"\n"
13682             "\"other\";",
13683             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13684   EXPECT_EQ("\"some text \"\n"
13685             "\"other\";",
13686             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13687   EXPECT_EQ(
13688       "#define A  \\\n"
13689       "  \"some \"  \\\n"
13690       "  \"text \"  \\\n"
13691       "  \"other\";",
13692       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13693   EXPECT_EQ(
13694       "#define A  \\\n"
13695       "  \"so \"    \\\n"
13696       "  \"text \"  \\\n"
13697       "  \"other\";",
13698       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13699 
13700   EXPECT_EQ("\"some text\"",
13701             format("\"some text\"", getLLVMStyleWithColumns(1)));
13702   EXPECT_EQ("\"some text\"",
13703             format("\"some text\"", getLLVMStyleWithColumns(11)));
13704   EXPECT_EQ("\"some \"\n"
13705             "\"text\"",
13706             format("\"some text\"", getLLVMStyleWithColumns(10)));
13707   EXPECT_EQ("\"some \"\n"
13708             "\"text\"",
13709             format("\"some text\"", getLLVMStyleWithColumns(7)));
13710   EXPECT_EQ("\"some\"\n"
13711             "\" tex\"\n"
13712             "\"t\"",
13713             format("\"some text\"", getLLVMStyleWithColumns(6)));
13714   EXPECT_EQ("\"some\"\n"
13715             "\" tex\"\n"
13716             "\" and\"",
13717             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13718   EXPECT_EQ("\"some\"\n"
13719             "\"/tex\"\n"
13720             "\"/and\"",
13721             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13722 
13723   EXPECT_EQ("variable =\n"
13724             "    \"long string \"\n"
13725             "    \"literal\";",
13726             format("variable = \"long string literal\";",
13727                    getLLVMStyleWithColumns(20)));
13728 
13729   EXPECT_EQ("variable = f(\n"
13730             "    \"long string \"\n"
13731             "    \"literal\",\n"
13732             "    short,\n"
13733             "    loooooooooooooooooooong);",
13734             format("variable = f(\"long string literal\", short, "
13735                    "loooooooooooooooooooong);",
13736                    getLLVMStyleWithColumns(20)));
13737 
13738   EXPECT_EQ(
13739       "f(g(\"long string \"\n"
13740       "    \"literal\"),\n"
13741       "  b);",
13742       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13743   EXPECT_EQ("f(g(\"long string \"\n"
13744             "    \"literal\",\n"
13745             "    a),\n"
13746             "  b);",
13747             format("f(g(\"long string literal\", a), b);",
13748                    getLLVMStyleWithColumns(20)));
13749   EXPECT_EQ(
13750       "f(\"one two\".split(\n"
13751       "    variable));",
13752       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13753   EXPECT_EQ("f(\"one two three four five six \"\n"
13754             "  \"seven\".split(\n"
13755             "      really_looooong_variable));",
13756             format("f(\"one two three four five six seven\"."
13757                    "split(really_looooong_variable));",
13758                    getLLVMStyleWithColumns(33)));
13759 
13760   EXPECT_EQ("f(\"some \"\n"
13761             "  \"text\",\n"
13762             "  other);",
13763             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13764 
13765   // Only break as a last resort.
13766   verifyFormat(
13767       "aaaaaaaaaaaaaaaaaaaa(\n"
13768       "    aaaaaaaaaaaaaaaaaaaa,\n"
13769       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13770 
13771   EXPECT_EQ("\"splitmea\"\n"
13772             "\"trandomp\"\n"
13773             "\"oint\"",
13774             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13775 
13776   EXPECT_EQ("\"split/\"\n"
13777             "\"pathat/\"\n"
13778             "\"slashes\"",
13779             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13780 
13781   EXPECT_EQ("\"split/\"\n"
13782             "\"pathat/\"\n"
13783             "\"slashes\"",
13784             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13785   EXPECT_EQ("\"split at \"\n"
13786             "\"spaces/at/\"\n"
13787             "\"slashes.at.any$\"\n"
13788             "\"non-alphanumeric%\"\n"
13789             "\"1111111111characte\"\n"
13790             "\"rs\"",
13791             format("\"split at "
13792                    "spaces/at/"
13793                    "slashes.at."
13794                    "any$non-"
13795                    "alphanumeric%"
13796                    "1111111111characte"
13797                    "rs\"",
13798                    getLLVMStyleWithColumns(20)));
13799 
13800   // Verify that splitting the strings understands
13801   // Style::AlwaysBreakBeforeMultilineStrings.
13802   EXPECT_EQ("aaaaaaaaaaaa(\n"
13803             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13804             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13805             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13806                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13807                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13808                    getGoogleStyle()));
13809   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13810             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13811             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13812                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13813                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13814                    getGoogleStyle()));
13815   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13816             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13817             format("llvm::outs() << "
13818                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13819                    "aaaaaaaaaaaaaaaaaaa\";"));
13820   EXPECT_EQ("ffff(\n"
13821             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13822             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13823             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13824                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13825                    getGoogleStyle()));
13826 
13827   FormatStyle Style = getLLVMStyleWithColumns(12);
13828   Style.BreakStringLiterals = false;
13829   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13830 
13831   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13832   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13833   EXPECT_EQ("#define A \\\n"
13834             "  \"some \" \\\n"
13835             "  \"text \" \\\n"
13836             "  \"other\";",
13837             format("#define A \"some text other\";", AlignLeft));
13838 }
13839 
13840 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13841   EXPECT_EQ("C a = \"some more \"\n"
13842             "      \"text\";",
13843             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13844 }
13845 
13846 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13847   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13848   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13849   EXPECT_EQ("int i = a(b());",
13850             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13851 }
13852 
13853 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13854   EXPECT_EQ(
13855       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13856       "(\n"
13857       "    \"x\t\");",
13858       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13859              "aaaaaaa("
13860              "\"x\t\");"));
13861 }
13862 
13863 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13864   EXPECT_EQ(
13865       "u8\"utf8 string \"\n"
13866       "u8\"literal\";",
13867       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13868   EXPECT_EQ(
13869       "u\"utf16 string \"\n"
13870       "u\"literal\";",
13871       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13872   EXPECT_EQ(
13873       "U\"utf32 string \"\n"
13874       "U\"literal\";",
13875       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13876   EXPECT_EQ("L\"wide string \"\n"
13877             "L\"literal\";",
13878             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13879   EXPECT_EQ("@\"NSString \"\n"
13880             "@\"literal\";",
13881             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13882   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13883 
13884   // This input makes clang-format try to split the incomplete unicode escape
13885   // sequence, which used to lead to a crasher.
13886   verifyNoCrash(
13887       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13888       getLLVMStyleWithColumns(60));
13889 }
13890 
13891 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13892   FormatStyle Style = getGoogleStyleWithColumns(15);
13893   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13894   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13895   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13896   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13897   EXPECT_EQ("u8R\"x(raw literal)x\";",
13898             format("u8R\"x(raw literal)x\";", Style));
13899 }
13900 
13901 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13902   FormatStyle Style = getLLVMStyleWithColumns(20);
13903   EXPECT_EQ(
13904       "_T(\"aaaaaaaaaaaaaa\")\n"
13905       "_T(\"aaaaaaaaaaaaaa\")\n"
13906       "_T(\"aaaaaaaaaaaa\")",
13907       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13908   EXPECT_EQ("f(x,\n"
13909             "  _T(\"aaaaaaaaaaaa\")\n"
13910             "  _T(\"aaa\"),\n"
13911             "  z);",
13912             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13913 
13914   // FIXME: Handle embedded spaces in one iteration.
13915   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13916   //            "_T(\"aaaaaaaaaaaaa\")\n"
13917   //            "_T(\"aaaaaaaaaaaaa\")\n"
13918   //            "_T(\"a\")",
13919   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13920   //                   getLLVMStyleWithColumns(20)));
13921   EXPECT_EQ(
13922       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13923       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13924   EXPECT_EQ("f(\n"
13925             "#if !TEST\n"
13926             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13927             "#endif\n"
13928             ");",
13929             format("f(\n"
13930                    "#if !TEST\n"
13931                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13932                    "#endif\n"
13933                    ");"));
13934   EXPECT_EQ("f(\n"
13935             "\n"
13936             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13937             format("f(\n"
13938                    "\n"
13939                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13940   // Regression test for accessing tokens past the end of a vector in the
13941   // TokenLexer.
13942   verifyNoCrash(R"(_T(
13943 "
13944 )
13945 )");
13946 }
13947 
13948 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13949   // In a function call with two operands, the second can be broken with no line
13950   // break before it.
13951   EXPECT_EQ(
13952       "func(a, \"long long \"\n"
13953       "        \"long long\");",
13954       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13955   // In a function call with three operands, the second must be broken with a
13956   // line break before it.
13957   EXPECT_EQ("func(a,\n"
13958             "     \"long long long \"\n"
13959             "     \"long\",\n"
13960             "     c);",
13961             format("func(a, \"long long long long\", c);",
13962                    getLLVMStyleWithColumns(24)));
13963   // In a function call with three operands, the third must be broken with a
13964   // line break before it.
13965   EXPECT_EQ("func(a, b,\n"
13966             "     \"long long long \"\n"
13967             "     \"long\");",
13968             format("func(a, b, \"long long long long\");",
13969                    getLLVMStyleWithColumns(24)));
13970   // In a function call with three operands, both the second and the third must
13971   // be broken with a line break before them.
13972   EXPECT_EQ("func(a,\n"
13973             "     \"long long long \"\n"
13974             "     \"long\",\n"
13975             "     \"long long long \"\n"
13976             "     \"long\");",
13977             format("func(a, \"long long long long\", \"long long long long\");",
13978                    getLLVMStyleWithColumns(24)));
13979   // In a chain of << with two operands, the second can be broken with no line
13980   // break before it.
13981   EXPECT_EQ("a << \"line line \"\n"
13982             "     \"line\";",
13983             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13984   // In a chain of << with three operands, the second can be broken with no line
13985   // break before it.
13986   EXPECT_EQ(
13987       "abcde << \"line \"\n"
13988       "         \"line line\"\n"
13989       "      << c;",
13990       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13991   // In a chain of << with three operands, the third must be broken with a line
13992   // break before it.
13993   EXPECT_EQ(
13994       "a << b\n"
13995       "  << \"line line \"\n"
13996       "     \"line\";",
13997       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13998   // In a chain of << with three operands, the second can be broken with no line
13999   // break before it and the third must be broken with a line break before it.
14000   EXPECT_EQ("abcd << \"line line \"\n"
14001             "        \"line\"\n"
14002             "     << \"line line \"\n"
14003             "        \"line\";",
14004             format("abcd << \"line line line\" << \"line line line\";",
14005                    getLLVMStyleWithColumns(20)));
14006   // In a chain of binary operators with two operands, the second can be broken
14007   // with no line break before it.
14008   EXPECT_EQ(
14009       "abcd + \"line line \"\n"
14010       "       \"line line\";",
14011       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
14012   // In a chain of binary operators with three operands, the second must be
14013   // broken with a line break before it.
14014   EXPECT_EQ("abcd +\n"
14015             "    \"line line \"\n"
14016             "    \"line line\" +\n"
14017             "    e;",
14018             format("abcd + \"line line line line\" + e;",
14019                    getLLVMStyleWithColumns(20)));
14020   // In a function call with two operands, with AlignAfterOpenBracket enabled,
14021   // the first must be broken with a line break before it.
14022   FormatStyle Style = getLLVMStyleWithColumns(25);
14023   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14024   EXPECT_EQ("someFunction(\n"
14025             "    \"long long long \"\n"
14026             "    \"long\",\n"
14027             "    a);",
14028             format("someFunction(\"long long long long\", a);", Style));
14029 }
14030 
14031 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
14032   EXPECT_EQ(
14033       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14034       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14035       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
14036       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14037              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14038              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
14039 }
14040 
14041 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
14042   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
14043             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
14044   EXPECT_EQ("fffffffffff(g(R\"x(\n"
14045             "multiline raw string literal xxxxxxxxxxxxxx\n"
14046             ")x\",\n"
14047             "              a),\n"
14048             "            b);",
14049             format("fffffffffff(g(R\"x(\n"
14050                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14051                    ")x\", a), b);",
14052                    getGoogleStyleWithColumns(20)));
14053   EXPECT_EQ("fffffffffff(\n"
14054             "    g(R\"x(qqq\n"
14055             "multiline raw string literal xxxxxxxxxxxxxx\n"
14056             ")x\",\n"
14057             "      a),\n"
14058             "    b);",
14059             format("fffffffffff(g(R\"x(qqq\n"
14060                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14061                    ")x\", a), b);",
14062                    getGoogleStyleWithColumns(20)));
14063 
14064   EXPECT_EQ("fffffffffff(R\"x(\n"
14065             "multiline raw string literal xxxxxxxxxxxxxx\n"
14066             ")x\");",
14067             format("fffffffffff(R\"x(\n"
14068                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14069                    ")x\");",
14070                    getGoogleStyleWithColumns(20)));
14071   EXPECT_EQ("fffffffffff(R\"x(\n"
14072             "multiline raw string literal xxxxxxxxxxxxxx\n"
14073             ")x\" + bbbbbb);",
14074             format("fffffffffff(R\"x(\n"
14075                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14076                    ")x\" +   bbbbbb);",
14077                    getGoogleStyleWithColumns(20)));
14078   EXPECT_EQ("fffffffffff(\n"
14079             "    R\"x(\n"
14080             "multiline raw string literal xxxxxxxxxxxxxx\n"
14081             ")x\" +\n"
14082             "    bbbbbb);",
14083             format("fffffffffff(\n"
14084                    " R\"x(\n"
14085                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14086                    ")x\" + bbbbbb);",
14087                    getGoogleStyleWithColumns(20)));
14088   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
14089             format("fffffffffff(\n"
14090                    " R\"(single line raw string)\" + bbbbbb);"));
14091 }
14092 
14093 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
14094   verifyFormat("string a = \"unterminated;");
14095   EXPECT_EQ("function(\"unterminated,\n"
14096             "         OtherParameter);",
14097             format("function(  \"unterminated,\n"
14098                    "    OtherParameter);"));
14099 }
14100 
14101 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
14102   FormatStyle Style = getLLVMStyle();
14103   Style.Standard = FormatStyle::LS_Cpp03;
14104   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
14105             format("#define x(_a) printf(\"foo\"_a);", Style));
14106 }
14107 
14108 TEST_F(FormatTest, CppLexVersion) {
14109   FormatStyle Style = getLLVMStyle();
14110   // Formatting of x * y differs if x is a type.
14111   verifyFormat("void foo() { MACRO(a * b); }", Style);
14112   verifyFormat("void foo() { MACRO(int *b); }", Style);
14113 
14114   // LLVM style uses latest lexer.
14115   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
14116   Style.Standard = FormatStyle::LS_Cpp17;
14117   // But in c++17, char8_t isn't a keyword.
14118   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
14119 }
14120 
14121 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
14122 
14123 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
14124   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
14125             "             \"ddeeefff\");",
14126             format("someFunction(\"aaabbbcccdddeeefff\");",
14127                    getLLVMStyleWithColumns(25)));
14128   EXPECT_EQ("someFunction1234567890(\n"
14129             "    \"aaabbbcccdddeeefff\");",
14130             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14131                    getLLVMStyleWithColumns(26)));
14132   EXPECT_EQ("someFunction1234567890(\n"
14133             "    \"aaabbbcccdddeeeff\"\n"
14134             "    \"f\");",
14135             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14136                    getLLVMStyleWithColumns(25)));
14137   EXPECT_EQ("someFunction1234567890(\n"
14138             "    \"aaabbbcccdddeeeff\"\n"
14139             "    \"f\");",
14140             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14141                    getLLVMStyleWithColumns(24)));
14142   EXPECT_EQ("someFunction(\n"
14143             "    \"aaabbbcc ddde \"\n"
14144             "    \"efff\");",
14145             format("someFunction(\"aaabbbcc ddde efff\");",
14146                    getLLVMStyleWithColumns(25)));
14147   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
14148             "             \"ddeeefff\");",
14149             format("someFunction(\"aaabbbccc ddeeefff\");",
14150                    getLLVMStyleWithColumns(25)));
14151   EXPECT_EQ("someFunction1234567890(\n"
14152             "    \"aaabb \"\n"
14153             "    \"cccdddeeefff\");",
14154             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
14155                    getLLVMStyleWithColumns(25)));
14156   EXPECT_EQ("#define A          \\\n"
14157             "  string s =       \\\n"
14158             "      \"123456789\"  \\\n"
14159             "      \"0\";         \\\n"
14160             "  int i;",
14161             format("#define A string s = \"1234567890\"; int i;",
14162                    getLLVMStyleWithColumns(20)));
14163   EXPECT_EQ("someFunction(\n"
14164             "    \"aaabbbcc \"\n"
14165             "    \"dddeeefff\");",
14166             format("someFunction(\"aaabbbcc dddeeefff\");",
14167                    getLLVMStyleWithColumns(25)));
14168 }
14169 
14170 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
14171   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
14172   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
14173   EXPECT_EQ("\"test\"\n"
14174             "\"\\n\"",
14175             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
14176   EXPECT_EQ("\"tes\\\\\"\n"
14177             "\"n\"",
14178             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
14179   EXPECT_EQ("\"\\\\\\\\\"\n"
14180             "\"\\n\"",
14181             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
14182   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
14183   EXPECT_EQ("\"\\uff01\"\n"
14184             "\"test\"",
14185             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
14186   EXPECT_EQ("\"\\Uff01ff02\"",
14187             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
14188   EXPECT_EQ("\"\\x000000000001\"\n"
14189             "\"next\"",
14190             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
14191   EXPECT_EQ("\"\\x000000000001next\"",
14192             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
14193   EXPECT_EQ("\"\\x000000000001\"",
14194             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
14195   EXPECT_EQ("\"test\"\n"
14196             "\"\\000000\"\n"
14197             "\"000001\"",
14198             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
14199   EXPECT_EQ("\"test\\000\"\n"
14200             "\"00000000\"\n"
14201             "\"1\"",
14202             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
14203 }
14204 
14205 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
14206   verifyFormat("void f() {\n"
14207                "  return g() {}\n"
14208                "  void h() {}");
14209   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
14210                "g();\n"
14211                "}");
14212 }
14213 
14214 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
14215   verifyFormat(
14216       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
14217 }
14218 
14219 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
14220   verifyFormat("class X {\n"
14221                "  void f() {\n"
14222                "  }\n"
14223                "};",
14224                getLLVMStyleWithColumns(12));
14225 }
14226 
14227 TEST_F(FormatTest, ConfigurableIndentWidth) {
14228   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
14229   EightIndent.IndentWidth = 8;
14230   EightIndent.ContinuationIndentWidth = 8;
14231   verifyFormat("void f() {\n"
14232                "        someFunction();\n"
14233                "        if (true) {\n"
14234                "                f();\n"
14235                "        }\n"
14236                "}",
14237                EightIndent);
14238   verifyFormat("class X {\n"
14239                "        void f() {\n"
14240                "        }\n"
14241                "};",
14242                EightIndent);
14243   verifyFormat("int x[] = {\n"
14244                "        call(),\n"
14245                "        call()};",
14246                EightIndent);
14247 }
14248 
14249 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
14250   verifyFormat("double\n"
14251                "f();",
14252                getLLVMStyleWithColumns(8));
14253 }
14254 
14255 TEST_F(FormatTest, ConfigurableUseOfTab) {
14256   FormatStyle Tab = getLLVMStyleWithColumns(42);
14257   Tab.IndentWidth = 8;
14258   Tab.UseTab = FormatStyle::UT_Always;
14259   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14260 
14261   EXPECT_EQ("if (aaaaaaaa && // q\n"
14262             "    bb)\t\t// w\n"
14263             "\t;",
14264             format("if (aaaaaaaa &&// q\n"
14265                    "bb)// w\n"
14266                    ";",
14267                    Tab));
14268   EXPECT_EQ("if (aaa && bbb) // w\n"
14269             "\t;",
14270             format("if(aaa&&bbb)// w\n"
14271                    ";",
14272                    Tab));
14273 
14274   verifyFormat("class X {\n"
14275                "\tvoid f() {\n"
14276                "\t\tsomeFunction(parameter1,\n"
14277                "\t\t\t     parameter2);\n"
14278                "\t}\n"
14279                "};",
14280                Tab);
14281   verifyFormat("#define A                        \\\n"
14282                "\tvoid f() {               \\\n"
14283                "\t\tsomeFunction(    \\\n"
14284                "\t\t    parameter1,  \\\n"
14285                "\t\t    parameter2); \\\n"
14286                "\t}",
14287                Tab);
14288   verifyFormat("int a;\t      // x\n"
14289                "int bbbbbbbb; // x\n",
14290                Tab);
14291 
14292   FormatStyle TabAlignment = Tab;
14293   TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
14294   TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
14295   verifyFormat("unsigned long long big;\n"
14296                "char*\t\t   ptr;",
14297                TabAlignment);
14298   TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
14299   verifyFormat("unsigned long long big;\n"
14300                "char *\t\t   ptr;",
14301                TabAlignment);
14302   TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
14303   verifyFormat("unsigned long long big;\n"
14304                "char\t\t  *ptr;",
14305                TabAlignment);
14306 
14307   Tab.TabWidth = 4;
14308   Tab.IndentWidth = 8;
14309   verifyFormat("class TabWidth4Indent8 {\n"
14310                "\t\tvoid f() {\n"
14311                "\t\t\t\tsomeFunction(parameter1,\n"
14312                "\t\t\t\t\t\t\t parameter2);\n"
14313                "\t\t}\n"
14314                "};",
14315                Tab);
14316 
14317   Tab.TabWidth = 4;
14318   Tab.IndentWidth = 4;
14319   verifyFormat("class TabWidth4Indent4 {\n"
14320                "\tvoid f() {\n"
14321                "\t\tsomeFunction(parameter1,\n"
14322                "\t\t\t\t\t parameter2);\n"
14323                "\t}\n"
14324                "};",
14325                Tab);
14326 
14327   Tab.TabWidth = 8;
14328   Tab.IndentWidth = 4;
14329   verifyFormat("class TabWidth8Indent4 {\n"
14330                "    void f() {\n"
14331                "\tsomeFunction(parameter1,\n"
14332                "\t\t     parameter2);\n"
14333                "    }\n"
14334                "};",
14335                Tab);
14336 
14337   Tab.TabWidth = 8;
14338   Tab.IndentWidth = 8;
14339   EXPECT_EQ("/*\n"
14340             "\t      a\t\tcomment\n"
14341             "\t      in multiple lines\n"
14342             "       */",
14343             format("   /*\t \t \n"
14344                    " \t \t a\t\tcomment\t \t\n"
14345                    " \t \t in multiple lines\t\n"
14346                    " \t  */",
14347                    Tab));
14348 
14349   TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
14350   TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
14351   verifyFormat("void f() {\n"
14352                "\tunsigned long long big;\n"
14353                "\tchar*              ptr;\n"
14354                "}",
14355                TabAlignment);
14356   TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
14357   verifyFormat("void f() {\n"
14358                "\tunsigned long long big;\n"
14359                "\tchar *             ptr;\n"
14360                "}",
14361                TabAlignment);
14362   TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
14363   verifyFormat("void f() {\n"
14364                "\tunsigned long long big;\n"
14365                "\tchar              *ptr;\n"
14366                "}",
14367                TabAlignment);
14368 
14369   Tab.UseTab = FormatStyle::UT_ForIndentation;
14370   verifyFormat("{\n"
14371                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14372                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14373                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14374                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14375                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14376                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14377                "};",
14378                Tab);
14379   verifyFormat("enum AA {\n"
14380                "\ta1, // Force multiple lines\n"
14381                "\ta2,\n"
14382                "\ta3\n"
14383                "};",
14384                Tab);
14385   EXPECT_EQ("if (aaaaaaaa && // q\n"
14386             "    bb)         // w\n"
14387             "\t;",
14388             format("if (aaaaaaaa &&// q\n"
14389                    "bb)// w\n"
14390                    ";",
14391                    Tab));
14392   verifyFormat("class X {\n"
14393                "\tvoid f() {\n"
14394                "\t\tsomeFunction(parameter1,\n"
14395                "\t\t             parameter2);\n"
14396                "\t}\n"
14397                "};",
14398                Tab);
14399   verifyFormat("{\n"
14400                "\tQ(\n"
14401                "\t    {\n"
14402                "\t\t    int a;\n"
14403                "\t\t    someFunction(aaaaaaaa,\n"
14404                "\t\t                 bbbbbbb);\n"
14405                "\t    },\n"
14406                "\t    p);\n"
14407                "}",
14408                Tab);
14409   EXPECT_EQ("{\n"
14410             "\t/* aaaa\n"
14411             "\t   bbbb */\n"
14412             "}",
14413             format("{\n"
14414                    "/* aaaa\n"
14415                    "   bbbb */\n"
14416                    "}",
14417                    Tab));
14418   EXPECT_EQ("{\n"
14419             "\t/*\n"
14420             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14421             "\t  bbbbbbbbbbbbb\n"
14422             "\t*/\n"
14423             "}",
14424             format("{\n"
14425                    "/*\n"
14426                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14427                    "*/\n"
14428                    "}",
14429                    Tab));
14430   EXPECT_EQ("{\n"
14431             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14432             "\t// bbbbbbbbbbbbb\n"
14433             "}",
14434             format("{\n"
14435                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14436                    "}",
14437                    Tab));
14438   EXPECT_EQ("{\n"
14439             "\t/*\n"
14440             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14441             "\t  bbbbbbbbbbbbb\n"
14442             "\t*/\n"
14443             "}",
14444             format("{\n"
14445                    "\t/*\n"
14446                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14447                    "\t*/\n"
14448                    "}",
14449                    Tab));
14450   EXPECT_EQ("{\n"
14451             "\t/*\n"
14452             "\n"
14453             "\t*/\n"
14454             "}",
14455             format("{\n"
14456                    "\t/*\n"
14457                    "\n"
14458                    "\t*/\n"
14459                    "}",
14460                    Tab));
14461   EXPECT_EQ("{\n"
14462             "\t/*\n"
14463             " asdf\n"
14464             "\t*/\n"
14465             "}",
14466             format("{\n"
14467                    "\t/*\n"
14468                    " asdf\n"
14469                    "\t*/\n"
14470                    "}",
14471                    Tab));
14472 
14473   verifyFormat("void f() {\n"
14474                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14475                "\t            : bbbbbbbbbbbbbbbbbb\n"
14476                "}",
14477                Tab);
14478   FormatStyle TabNoBreak = Tab;
14479   TabNoBreak.BreakBeforeTernaryOperators = false;
14480   verifyFormat("void f() {\n"
14481                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14482                "\t              bbbbbbbbbbbbbbbbbb\n"
14483                "}",
14484                TabNoBreak);
14485   verifyFormat("void f() {\n"
14486                "\treturn true ?\n"
14487                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14488                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14489                "}",
14490                TabNoBreak);
14491 
14492   Tab.UseTab = FormatStyle::UT_Never;
14493   EXPECT_EQ("/*\n"
14494             "              a\t\tcomment\n"
14495             "              in multiple lines\n"
14496             "       */",
14497             format("   /*\t \t \n"
14498                    " \t \t a\t\tcomment\t \t\n"
14499                    " \t \t in multiple lines\t\n"
14500                    " \t  */",
14501                    Tab));
14502   EXPECT_EQ("/* some\n"
14503             "   comment */",
14504             format(" \t \t /* some\n"
14505                    " \t \t    comment */",
14506                    Tab));
14507   EXPECT_EQ("int a; /* some\n"
14508             "   comment */",
14509             format(" \t \t int a; /* some\n"
14510                    " \t \t    comment */",
14511                    Tab));
14512 
14513   EXPECT_EQ("int a; /* some\n"
14514             "comment */",
14515             format(" \t \t int\ta; /* some\n"
14516                    " \t \t    comment */",
14517                    Tab));
14518   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14519             "    comment */",
14520             format(" \t \t f(\"\t\t\"); /* some\n"
14521                    " \t \t    comment */",
14522                    Tab));
14523   EXPECT_EQ("{\n"
14524             "        /*\n"
14525             "         * Comment\n"
14526             "         */\n"
14527             "        int i;\n"
14528             "}",
14529             format("{\n"
14530                    "\t/*\n"
14531                    "\t * Comment\n"
14532                    "\t */\n"
14533                    "\t int i;\n"
14534                    "}",
14535                    Tab));
14536 
14537   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14538   Tab.TabWidth = 8;
14539   Tab.IndentWidth = 8;
14540   EXPECT_EQ("if (aaaaaaaa && // q\n"
14541             "    bb)         // w\n"
14542             "\t;",
14543             format("if (aaaaaaaa &&// q\n"
14544                    "bb)// w\n"
14545                    ";",
14546                    Tab));
14547   EXPECT_EQ("if (aaa && bbb) // w\n"
14548             "\t;",
14549             format("if(aaa&&bbb)// w\n"
14550                    ";",
14551                    Tab));
14552   verifyFormat("class X {\n"
14553                "\tvoid f() {\n"
14554                "\t\tsomeFunction(parameter1,\n"
14555                "\t\t\t     parameter2);\n"
14556                "\t}\n"
14557                "};",
14558                Tab);
14559   verifyFormat("#define A                        \\\n"
14560                "\tvoid f() {               \\\n"
14561                "\t\tsomeFunction(    \\\n"
14562                "\t\t    parameter1,  \\\n"
14563                "\t\t    parameter2); \\\n"
14564                "\t}",
14565                Tab);
14566   Tab.TabWidth = 4;
14567   Tab.IndentWidth = 8;
14568   verifyFormat("class TabWidth4Indent8 {\n"
14569                "\t\tvoid f() {\n"
14570                "\t\t\t\tsomeFunction(parameter1,\n"
14571                "\t\t\t\t\t\t\t parameter2);\n"
14572                "\t\t}\n"
14573                "};",
14574                Tab);
14575   Tab.TabWidth = 4;
14576   Tab.IndentWidth = 4;
14577   verifyFormat("class TabWidth4Indent4 {\n"
14578                "\tvoid f() {\n"
14579                "\t\tsomeFunction(parameter1,\n"
14580                "\t\t\t\t\t parameter2);\n"
14581                "\t}\n"
14582                "};",
14583                Tab);
14584   Tab.TabWidth = 8;
14585   Tab.IndentWidth = 4;
14586   verifyFormat("class TabWidth8Indent4 {\n"
14587                "    void f() {\n"
14588                "\tsomeFunction(parameter1,\n"
14589                "\t\t     parameter2);\n"
14590                "    }\n"
14591                "};",
14592                Tab);
14593   Tab.TabWidth = 8;
14594   Tab.IndentWidth = 8;
14595   EXPECT_EQ("/*\n"
14596             "\t      a\t\tcomment\n"
14597             "\t      in multiple lines\n"
14598             "       */",
14599             format("   /*\t \t \n"
14600                    " \t \t a\t\tcomment\t \t\n"
14601                    " \t \t in multiple lines\t\n"
14602                    " \t  */",
14603                    Tab));
14604   verifyFormat("{\n"
14605                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14606                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14607                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14608                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14609                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14610                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14611                "};",
14612                Tab);
14613   verifyFormat("enum AA {\n"
14614                "\ta1, // Force multiple lines\n"
14615                "\ta2,\n"
14616                "\ta3\n"
14617                "};",
14618                Tab);
14619   EXPECT_EQ("if (aaaaaaaa && // q\n"
14620             "    bb)         // w\n"
14621             "\t;",
14622             format("if (aaaaaaaa &&// q\n"
14623                    "bb)// w\n"
14624                    ";",
14625                    Tab));
14626   verifyFormat("class X {\n"
14627                "\tvoid f() {\n"
14628                "\t\tsomeFunction(parameter1,\n"
14629                "\t\t\t     parameter2);\n"
14630                "\t}\n"
14631                "};",
14632                Tab);
14633   verifyFormat("{\n"
14634                "\tQ(\n"
14635                "\t    {\n"
14636                "\t\t    int a;\n"
14637                "\t\t    someFunction(aaaaaaaa,\n"
14638                "\t\t\t\t bbbbbbb);\n"
14639                "\t    },\n"
14640                "\t    p);\n"
14641                "}",
14642                Tab);
14643   EXPECT_EQ("{\n"
14644             "\t/* aaaa\n"
14645             "\t   bbbb */\n"
14646             "}",
14647             format("{\n"
14648                    "/* aaaa\n"
14649                    "   bbbb */\n"
14650                    "}",
14651                    Tab));
14652   EXPECT_EQ("{\n"
14653             "\t/*\n"
14654             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14655             "\t  bbbbbbbbbbbbb\n"
14656             "\t*/\n"
14657             "}",
14658             format("{\n"
14659                    "/*\n"
14660                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14661                    "*/\n"
14662                    "}",
14663                    Tab));
14664   EXPECT_EQ("{\n"
14665             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14666             "\t// bbbbbbbbbbbbb\n"
14667             "}",
14668             format("{\n"
14669                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14670                    "}",
14671                    Tab));
14672   EXPECT_EQ("{\n"
14673             "\t/*\n"
14674             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14675             "\t  bbbbbbbbbbbbb\n"
14676             "\t*/\n"
14677             "}",
14678             format("{\n"
14679                    "\t/*\n"
14680                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14681                    "\t*/\n"
14682                    "}",
14683                    Tab));
14684   EXPECT_EQ("{\n"
14685             "\t/*\n"
14686             "\n"
14687             "\t*/\n"
14688             "}",
14689             format("{\n"
14690                    "\t/*\n"
14691                    "\n"
14692                    "\t*/\n"
14693                    "}",
14694                    Tab));
14695   EXPECT_EQ("{\n"
14696             "\t/*\n"
14697             " asdf\n"
14698             "\t*/\n"
14699             "}",
14700             format("{\n"
14701                    "\t/*\n"
14702                    " asdf\n"
14703                    "\t*/\n"
14704                    "}",
14705                    Tab));
14706   EXPECT_EQ("/* some\n"
14707             "   comment */",
14708             format(" \t \t /* some\n"
14709                    " \t \t    comment */",
14710                    Tab));
14711   EXPECT_EQ("int a; /* some\n"
14712             "   comment */",
14713             format(" \t \t int a; /* some\n"
14714                    " \t \t    comment */",
14715                    Tab));
14716   EXPECT_EQ("int a; /* some\n"
14717             "comment */",
14718             format(" \t \t int\ta; /* some\n"
14719                    " \t \t    comment */",
14720                    Tab));
14721   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14722             "    comment */",
14723             format(" \t \t f(\"\t\t\"); /* some\n"
14724                    " \t \t    comment */",
14725                    Tab));
14726   EXPECT_EQ("{\n"
14727             "\t/*\n"
14728             "\t * Comment\n"
14729             "\t */\n"
14730             "\tint i;\n"
14731             "}",
14732             format("{\n"
14733                    "\t/*\n"
14734                    "\t * Comment\n"
14735                    "\t */\n"
14736                    "\t int i;\n"
14737                    "}",
14738                    Tab));
14739   Tab.TabWidth = 2;
14740   Tab.IndentWidth = 2;
14741   EXPECT_EQ("{\n"
14742             "\t/* aaaa\n"
14743             "\t\t bbbb */\n"
14744             "}",
14745             format("{\n"
14746                    "/* aaaa\n"
14747                    "\t bbbb */\n"
14748                    "}",
14749                    Tab));
14750   EXPECT_EQ("{\n"
14751             "\t/*\n"
14752             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14753             "\t\tbbbbbbbbbbbbb\n"
14754             "\t*/\n"
14755             "}",
14756             format("{\n"
14757                    "/*\n"
14758                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14759                    "*/\n"
14760                    "}",
14761                    Tab));
14762   Tab.AlignConsecutiveAssignments.Enabled = true;
14763   Tab.AlignConsecutiveDeclarations.Enabled = true;
14764   Tab.TabWidth = 4;
14765   Tab.IndentWidth = 4;
14766   verifyFormat("class Assign {\n"
14767                "\tvoid f() {\n"
14768                "\t\tint         x      = 123;\n"
14769                "\t\tint         random = 4;\n"
14770                "\t\tstd::string alphabet =\n"
14771                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14772                "\t}\n"
14773                "};",
14774                Tab);
14775 
14776   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14777   Tab.TabWidth = 8;
14778   Tab.IndentWidth = 8;
14779   EXPECT_EQ("if (aaaaaaaa && // q\n"
14780             "    bb)         // w\n"
14781             "\t;",
14782             format("if (aaaaaaaa &&// q\n"
14783                    "bb)// w\n"
14784                    ";",
14785                    Tab));
14786   EXPECT_EQ("if (aaa && bbb) // w\n"
14787             "\t;",
14788             format("if(aaa&&bbb)// w\n"
14789                    ";",
14790                    Tab));
14791   verifyFormat("class X {\n"
14792                "\tvoid f() {\n"
14793                "\t\tsomeFunction(parameter1,\n"
14794                "\t\t             parameter2);\n"
14795                "\t}\n"
14796                "};",
14797                Tab);
14798   verifyFormat("#define A                        \\\n"
14799                "\tvoid f() {               \\\n"
14800                "\t\tsomeFunction(    \\\n"
14801                "\t\t    parameter1,  \\\n"
14802                "\t\t    parameter2); \\\n"
14803                "\t}",
14804                Tab);
14805   Tab.TabWidth = 4;
14806   Tab.IndentWidth = 8;
14807   verifyFormat("class TabWidth4Indent8 {\n"
14808                "\t\tvoid f() {\n"
14809                "\t\t\t\tsomeFunction(parameter1,\n"
14810                "\t\t\t\t             parameter2);\n"
14811                "\t\t}\n"
14812                "};",
14813                Tab);
14814   Tab.TabWidth = 4;
14815   Tab.IndentWidth = 4;
14816   verifyFormat("class TabWidth4Indent4 {\n"
14817                "\tvoid f() {\n"
14818                "\t\tsomeFunction(parameter1,\n"
14819                "\t\t             parameter2);\n"
14820                "\t}\n"
14821                "};",
14822                Tab);
14823   Tab.TabWidth = 8;
14824   Tab.IndentWidth = 4;
14825   verifyFormat("class TabWidth8Indent4 {\n"
14826                "    void f() {\n"
14827                "\tsomeFunction(parameter1,\n"
14828                "\t             parameter2);\n"
14829                "    }\n"
14830                "};",
14831                Tab);
14832   Tab.TabWidth = 8;
14833   Tab.IndentWidth = 8;
14834   EXPECT_EQ("/*\n"
14835             "              a\t\tcomment\n"
14836             "              in multiple lines\n"
14837             "       */",
14838             format("   /*\t \t \n"
14839                    " \t \t a\t\tcomment\t \t\n"
14840                    " \t \t in multiple lines\t\n"
14841                    " \t  */",
14842                    Tab));
14843   verifyFormat("{\n"
14844                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14845                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14846                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14847                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14848                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14849                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14850                "};",
14851                Tab);
14852   verifyFormat("enum AA {\n"
14853                "\ta1, // Force multiple lines\n"
14854                "\ta2,\n"
14855                "\ta3\n"
14856                "};",
14857                Tab);
14858   EXPECT_EQ("if (aaaaaaaa && // q\n"
14859             "    bb)         // w\n"
14860             "\t;",
14861             format("if (aaaaaaaa &&// q\n"
14862                    "bb)// w\n"
14863                    ";",
14864                    Tab));
14865   verifyFormat("class X {\n"
14866                "\tvoid f() {\n"
14867                "\t\tsomeFunction(parameter1,\n"
14868                "\t\t             parameter2);\n"
14869                "\t}\n"
14870                "};",
14871                Tab);
14872   verifyFormat("{\n"
14873                "\tQ(\n"
14874                "\t    {\n"
14875                "\t\t    int a;\n"
14876                "\t\t    someFunction(aaaaaaaa,\n"
14877                "\t\t                 bbbbbbb);\n"
14878                "\t    },\n"
14879                "\t    p);\n"
14880                "}",
14881                Tab);
14882   EXPECT_EQ("{\n"
14883             "\t/* aaaa\n"
14884             "\t   bbbb */\n"
14885             "}",
14886             format("{\n"
14887                    "/* aaaa\n"
14888                    "   bbbb */\n"
14889                    "}",
14890                    Tab));
14891   EXPECT_EQ("{\n"
14892             "\t/*\n"
14893             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14894             "\t  bbbbbbbbbbbbb\n"
14895             "\t*/\n"
14896             "}",
14897             format("{\n"
14898                    "/*\n"
14899                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14900                    "*/\n"
14901                    "}",
14902                    Tab));
14903   EXPECT_EQ("{\n"
14904             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14905             "\t// bbbbbbbbbbbbb\n"
14906             "}",
14907             format("{\n"
14908                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14909                    "}",
14910                    Tab));
14911   EXPECT_EQ("{\n"
14912             "\t/*\n"
14913             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14914             "\t  bbbbbbbbbbbbb\n"
14915             "\t*/\n"
14916             "}",
14917             format("{\n"
14918                    "\t/*\n"
14919                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14920                    "\t*/\n"
14921                    "}",
14922                    Tab));
14923   EXPECT_EQ("{\n"
14924             "\t/*\n"
14925             "\n"
14926             "\t*/\n"
14927             "}",
14928             format("{\n"
14929                    "\t/*\n"
14930                    "\n"
14931                    "\t*/\n"
14932                    "}",
14933                    Tab));
14934   EXPECT_EQ("{\n"
14935             "\t/*\n"
14936             " asdf\n"
14937             "\t*/\n"
14938             "}",
14939             format("{\n"
14940                    "\t/*\n"
14941                    " asdf\n"
14942                    "\t*/\n"
14943                    "}",
14944                    Tab));
14945   EXPECT_EQ("/* some\n"
14946             "   comment */",
14947             format(" \t \t /* some\n"
14948                    " \t \t    comment */",
14949                    Tab));
14950   EXPECT_EQ("int a; /* some\n"
14951             "   comment */",
14952             format(" \t \t int a; /* some\n"
14953                    " \t \t    comment */",
14954                    Tab));
14955   EXPECT_EQ("int a; /* some\n"
14956             "comment */",
14957             format(" \t \t int\ta; /* some\n"
14958                    " \t \t    comment */",
14959                    Tab));
14960   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14961             "    comment */",
14962             format(" \t \t f(\"\t\t\"); /* some\n"
14963                    " \t \t    comment */",
14964                    Tab));
14965   EXPECT_EQ("{\n"
14966             "\t/*\n"
14967             "\t * Comment\n"
14968             "\t */\n"
14969             "\tint i;\n"
14970             "}",
14971             format("{\n"
14972                    "\t/*\n"
14973                    "\t * Comment\n"
14974                    "\t */\n"
14975                    "\t int i;\n"
14976                    "}",
14977                    Tab));
14978   Tab.TabWidth = 2;
14979   Tab.IndentWidth = 2;
14980   EXPECT_EQ("{\n"
14981             "\t/* aaaa\n"
14982             "\t   bbbb */\n"
14983             "}",
14984             format("{\n"
14985                    "/* aaaa\n"
14986                    "   bbbb */\n"
14987                    "}",
14988                    Tab));
14989   EXPECT_EQ("{\n"
14990             "\t/*\n"
14991             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14992             "\t  bbbbbbbbbbbbb\n"
14993             "\t*/\n"
14994             "}",
14995             format("{\n"
14996                    "/*\n"
14997                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14998                    "*/\n"
14999                    "}",
15000                    Tab));
15001   Tab.AlignConsecutiveAssignments.Enabled = true;
15002   Tab.AlignConsecutiveDeclarations.Enabled = true;
15003   Tab.TabWidth = 4;
15004   Tab.IndentWidth = 4;
15005   verifyFormat("class Assign {\n"
15006                "\tvoid f() {\n"
15007                "\t\tint         x      = 123;\n"
15008                "\t\tint         random = 4;\n"
15009                "\t\tstd::string alphabet =\n"
15010                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
15011                "\t}\n"
15012                "};",
15013                Tab);
15014   Tab.AlignOperands = FormatStyle::OAS_Align;
15015   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
15016                "                 cccccccccccccccccccc;",
15017                Tab);
15018   // no alignment
15019   verifyFormat("int aaaaaaaaaa =\n"
15020                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
15021                Tab);
15022   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
15023                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
15024                "                        : 333333333333333;",
15025                Tab);
15026   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15027   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
15028   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
15029                "               + cccccccccccccccccccc;",
15030                Tab);
15031 }
15032 
15033 TEST_F(FormatTest, ZeroTabWidth) {
15034   FormatStyle Tab = getLLVMStyleWithColumns(42);
15035   Tab.IndentWidth = 8;
15036   Tab.UseTab = FormatStyle::UT_Never;
15037   Tab.TabWidth = 0;
15038   EXPECT_EQ("void a(){\n"
15039             "    // line starts with '\t'\n"
15040             "};",
15041             format("void a(){\n"
15042                    "\t// line starts with '\t'\n"
15043                    "};",
15044                    Tab));
15045 
15046   EXPECT_EQ("void a(){\n"
15047             "    // line starts with '\t'\n"
15048             "};",
15049             format("void a(){\n"
15050                    "\t\t// line starts with '\t'\n"
15051                    "};",
15052                    Tab));
15053 
15054   Tab.UseTab = FormatStyle::UT_ForIndentation;
15055   EXPECT_EQ("void a(){\n"
15056             "    // line starts with '\t'\n"
15057             "};",
15058             format("void a(){\n"
15059                    "\t// line starts with '\t'\n"
15060                    "};",
15061                    Tab));
15062 
15063   EXPECT_EQ("void a(){\n"
15064             "    // line starts with '\t'\n"
15065             "};",
15066             format("void a(){\n"
15067                    "\t\t// line starts with '\t'\n"
15068                    "};",
15069                    Tab));
15070 
15071   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
15072   EXPECT_EQ("void a(){\n"
15073             "    // line starts with '\t'\n"
15074             "};",
15075             format("void a(){\n"
15076                    "\t// line starts with '\t'\n"
15077                    "};",
15078                    Tab));
15079 
15080   EXPECT_EQ("void a(){\n"
15081             "    // line starts with '\t'\n"
15082             "};",
15083             format("void a(){\n"
15084                    "\t\t// line starts with '\t'\n"
15085                    "};",
15086                    Tab));
15087 
15088   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
15089   EXPECT_EQ("void a(){\n"
15090             "    // line starts with '\t'\n"
15091             "};",
15092             format("void a(){\n"
15093                    "\t// line starts with '\t'\n"
15094                    "};",
15095                    Tab));
15096 
15097   EXPECT_EQ("void a(){\n"
15098             "    // line starts with '\t'\n"
15099             "};",
15100             format("void a(){\n"
15101                    "\t\t// line starts with '\t'\n"
15102                    "};",
15103                    Tab));
15104 
15105   Tab.UseTab = FormatStyle::UT_Always;
15106   EXPECT_EQ("void a(){\n"
15107             "// line starts with '\t'\n"
15108             "};",
15109             format("void a(){\n"
15110                    "\t// line starts with '\t'\n"
15111                    "};",
15112                    Tab));
15113 
15114   EXPECT_EQ("void a(){\n"
15115             "// line starts with '\t'\n"
15116             "};",
15117             format("void a(){\n"
15118                    "\t\t// line starts with '\t'\n"
15119                    "};",
15120                    Tab));
15121 }
15122 
15123 TEST_F(FormatTest, CalculatesOriginalColumn) {
15124   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15125             "q\"; /* some\n"
15126             "       comment */",
15127             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15128                    "q\"; /* some\n"
15129                    "       comment */",
15130                    getLLVMStyle()));
15131   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
15132             "/* some\n"
15133             "   comment */",
15134             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
15135                    " /* some\n"
15136                    "    comment */",
15137                    getLLVMStyle()));
15138   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15139             "qqq\n"
15140             "/* some\n"
15141             "   comment */",
15142             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15143                    "qqq\n"
15144                    " /* some\n"
15145                    "    comment */",
15146                    getLLVMStyle()));
15147   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15148             "wwww; /* some\n"
15149             "         comment */",
15150             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15151                    "wwww; /* some\n"
15152                    "         comment */",
15153                    getLLVMStyle()));
15154 }
15155 
15156 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
15157   FormatStyle NoSpace = getLLVMStyle();
15158   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
15159 
15160   verifyFormat("while(true)\n"
15161                "  continue;",
15162                NoSpace);
15163   verifyFormat("for(;;)\n"
15164                "  continue;",
15165                NoSpace);
15166   verifyFormat("if(true)\n"
15167                "  f();\n"
15168                "else if(true)\n"
15169                "  f();",
15170                NoSpace);
15171   verifyFormat("do {\n"
15172                "  do_something();\n"
15173                "} while(something());",
15174                NoSpace);
15175   verifyFormat("switch(x) {\n"
15176                "default:\n"
15177                "  break;\n"
15178                "}",
15179                NoSpace);
15180   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
15181   verifyFormat("size_t x = sizeof(x);", NoSpace);
15182   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
15183   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
15184   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
15185   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
15186   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
15187   verifyFormat("alignas(128) char a[128];", NoSpace);
15188   verifyFormat("size_t x = alignof(MyType);", NoSpace);
15189   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
15190   verifyFormat("int f() throw(Deprecated);", NoSpace);
15191   verifyFormat("typedef void (*cb)(int);", NoSpace);
15192   verifyFormat("T A::operator()();", NoSpace);
15193   verifyFormat("X A::operator++(T);", NoSpace);
15194   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
15195 
15196   FormatStyle Space = getLLVMStyle();
15197   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
15198 
15199   verifyFormat("int f ();", Space);
15200   verifyFormat("void f (int a, T b) {\n"
15201                "  while (true)\n"
15202                "    continue;\n"
15203                "}",
15204                Space);
15205   verifyFormat("if (true)\n"
15206                "  f ();\n"
15207                "else if (true)\n"
15208                "  f ();",
15209                Space);
15210   verifyFormat("do {\n"
15211                "  do_something ();\n"
15212                "} while (something ());",
15213                Space);
15214   verifyFormat("switch (x) {\n"
15215                "default:\n"
15216                "  break;\n"
15217                "}",
15218                Space);
15219   verifyFormat("A::A () : a (1) {}", Space);
15220   verifyFormat("void f () __attribute__ ((asdf));", Space);
15221   verifyFormat("*(&a + 1);\n"
15222                "&((&a)[1]);\n"
15223                "a[(b + c) * d];\n"
15224                "(((a + 1) * 2) + 3) * 4;",
15225                Space);
15226   verifyFormat("#define A(x) x", Space);
15227   verifyFormat("#define A (x) x", Space);
15228   verifyFormat("#if defined(x)\n"
15229                "#endif",
15230                Space);
15231   verifyFormat("auto i = std::make_unique<int> (5);", Space);
15232   verifyFormat("size_t x = sizeof (x);", Space);
15233   verifyFormat("auto f (int x) -> decltype (x);", Space);
15234   verifyFormat("auto f (int x) -> typeof (x);", Space);
15235   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
15236   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
15237   verifyFormat("int f (T x) noexcept (x.create ());", Space);
15238   verifyFormat("alignas (128) char a[128];", Space);
15239   verifyFormat("size_t x = alignof (MyType);", Space);
15240   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
15241   verifyFormat("int f () throw (Deprecated);", Space);
15242   verifyFormat("typedef void (*cb) (int);", Space);
15243   // FIXME these tests regressed behaviour.
15244   // verifyFormat("T A::operator() ();", Space);
15245   // verifyFormat("X A::operator++ (T);", Space);
15246   verifyFormat("auto lambda = [] () { return 0; };", Space);
15247   verifyFormat("int x = int (y);", Space);
15248   verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
15249   verifyFormat("__builtin_LINE ()", Space);
15250   verifyFormat("__builtin_UNKNOWN ()", Space);
15251 
15252   FormatStyle SomeSpace = getLLVMStyle();
15253   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
15254 
15255   verifyFormat("[]() -> float {}", SomeSpace);
15256   verifyFormat("[] (auto foo) {}", SomeSpace);
15257   verifyFormat("[foo]() -> int {}", SomeSpace);
15258   verifyFormat("int f();", SomeSpace);
15259   verifyFormat("void f (int a, T b) {\n"
15260                "  while (true)\n"
15261                "    continue;\n"
15262                "}",
15263                SomeSpace);
15264   verifyFormat("if (true)\n"
15265                "  f();\n"
15266                "else if (true)\n"
15267                "  f();",
15268                SomeSpace);
15269   verifyFormat("do {\n"
15270                "  do_something();\n"
15271                "} while (something());",
15272                SomeSpace);
15273   verifyFormat("switch (x) {\n"
15274                "default:\n"
15275                "  break;\n"
15276                "}",
15277                SomeSpace);
15278   verifyFormat("A::A() : a (1) {}", SomeSpace);
15279   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
15280   verifyFormat("*(&a + 1);\n"
15281                "&((&a)[1]);\n"
15282                "a[(b + c) * d];\n"
15283                "(((a + 1) * 2) + 3) * 4;",
15284                SomeSpace);
15285   verifyFormat("#define A(x) x", SomeSpace);
15286   verifyFormat("#define A (x) x", SomeSpace);
15287   verifyFormat("#if defined(x)\n"
15288                "#endif",
15289                SomeSpace);
15290   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
15291   verifyFormat("size_t x = sizeof (x);", SomeSpace);
15292   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
15293   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
15294   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
15295   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
15296   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
15297   verifyFormat("alignas (128) char a[128];", SomeSpace);
15298   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
15299   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15300                SomeSpace);
15301   verifyFormat("int f() throw (Deprecated);", SomeSpace);
15302   verifyFormat("typedef void (*cb) (int);", SomeSpace);
15303   verifyFormat("T A::operator()();", SomeSpace);
15304   // FIXME these tests regressed behaviour.
15305   // verifyFormat("X A::operator++ (T);", SomeSpace);
15306   verifyFormat("int x = int (y);", SomeSpace);
15307   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
15308 
15309   FormatStyle SpaceControlStatements = getLLVMStyle();
15310   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15311   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
15312 
15313   verifyFormat("while (true)\n"
15314                "  continue;",
15315                SpaceControlStatements);
15316   verifyFormat("if (true)\n"
15317                "  f();\n"
15318                "else if (true)\n"
15319                "  f();",
15320                SpaceControlStatements);
15321   verifyFormat("for (;;) {\n"
15322                "  do_something();\n"
15323                "}",
15324                SpaceControlStatements);
15325   verifyFormat("do {\n"
15326                "  do_something();\n"
15327                "} while (something());",
15328                SpaceControlStatements);
15329   verifyFormat("switch (x) {\n"
15330                "default:\n"
15331                "  break;\n"
15332                "}",
15333                SpaceControlStatements);
15334 
15335   FormatStyle SpaceFuncDecl = getLLVMStyle();
15336   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15337   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
15338 
15339   verifyFormat("int f ();", SpaceFuncDecl);
15340   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
15341   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
15342   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
15343   verifyFormat("#define A(x) x", SpaceFuncDecl);
15344   verifyFormat("#define A (x) x", SpaceFuncDecl);
15345   verifyFormat("#if defined(x)\n"
15346                "#endif",
15347                SpaceFuncDecl);
15348   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
15349   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
15350   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
15351   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
15352   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
15353   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
15354   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
15355   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
15356   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
15357   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15358                SpaceFuncDecl);
15359   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
15360   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
15361   // FIXME these tests regressed behaviour.
15362   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
15363   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
15364   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
15365   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
15366   verifyFormat("int x = int(y);", SpaceFuncDecl);
15367   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15368                SpaceFuncDecl);
15369 
15370   FormatStyle SpaceFuncDef = getLLVMStyle();
15371   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15372   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
15373 
15374   verifyFormat("int f();", SpaceFuncDef);
15375   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
15376   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
15377   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
15378   verifyFormat("#define A(x) x", SpaceFuncDef);
15379   verifyFormat("#define A (x) x", SpaceFuncDef);
15380   verifyFormat("#if defined(x)\n"
15381                "#endif",
15382                SpaceFuncDef);
15383   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
15384   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
15385   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
15386   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
15387   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
15388   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
15389   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
15390   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
15391   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
15392   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15393                SpaceFuncDef);
15394   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
15395   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
15396   verifyFormat("T A::operator()();", SpaceFuncDef);
15397   verifyFormat("X A::operator++(T);", SpaceFuncDef);
15398   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
15399   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
15400   verifyFormat("int x = int(y);", SpaceFuncDef);
15401   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15402                SpaceFuncDef);
15403 
15404   FormatStyle SpaceIfMacros = getLLVMStyle();
15405   SpaceIfMacros.IfMacros.clear();
15406   SpaceIfMacros.IfMacros.push_back("MYIF");
15407   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15408   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15409   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15410   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15411   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15412 
15413   FormatStyle SpaceForeachMacros = getLLVMStyle();
15414   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15415             FormatStyle::SBS_Never);
15416   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15417   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15418   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15419   verifyFormat("for (;;) {\n"
15420                "}",
15421                SpaceForeachMacros);
15422   verifyFormat("foreach (Item *item, itemlist) {\n"
15423                "}",
15424                SpaceForeachMacros);
15425   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15426                "}",
15427                SpaceForeachMacros);
15428   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15429                "}",
15430                SpaceForeachMacros);
15431   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15432 
15433   FormatStyle SomeSpace2 = getLLVMStyle();
15434   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15435   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15436   verifyFormat("[]() -> float {}", SomeSpace2);
15437   verifyFormat("[] (auto foo) {}", SomeSpace2);
15438   verifyFormat("[foo]() -> int {}", SomeSpace2);
15439   verifyFormat("int f();", SomeSpace2);
15440   verifyFormat("void f (int a, T b) {\n"
15441                "  while (true)\n"
15442                "    continue;\n"
15443                "}",
15444                SomeSpace2);
15445   verifyFormat("if (true)\n"
15446                "  f();\n"
15447                "else if (true)\n"
15448                "  f();",
15449                SomeSpace2);
15450   verifyFormat("do {\n"
15451                "  do_something();\n"
15452                "} while (something());",
15453                SomeSpace2);
15454   verifyFormat("switch (x) {\n"
15455                "default:\n"
15456                "  break;\n"
15457                "}",
15458                SomeSpace2);
15459   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15460   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15461   verifyFormat("*(&a + 1);\n"
15462                "&((&a)[1]);\n"
15463                "a[(b + c) * d];\n"
15464                "(((a + 1) * 2) + 3) * 4;",
15465                SomeSpace2);
15466   verifyFormat("#define A(x) x", SomeSpace2);
15467   verifyFormat("#define A (x) x", SomeSpace2);
15468   verifyFormat("#if defined(x)\n"
15469                "#endif",
15470                SomeSpace2);
15471   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15472   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15473   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15474   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15475   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15476   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15477   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15478   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15479   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15480   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15481                SomeSpace2);
15482   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15483   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15484   verifyFormat("T A::operator()();", SomeSpace2);
15485   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15486   verifyFormat("int x = int (y);", SomeSpace2);
15487   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15488 
15489   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15490   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15491   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15492       .AfterOverloadedOperator = true;
15493 
15494   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15495   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15496   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15497   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15498 
15499   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15500       .AfterOverloadedOperator = false;
15501 
15502   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15503   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15504   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15505   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15506 
15507   auto SpaceAfterRequires = getLLVMStyle();
15508   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15509   EXPECT_FALSE(
15510       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15511   EXPECT_FALSE(
15512       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15513   verifyFormat("void f(auto x)\n"
15514                "  requires requires(int i) { x + i; }\n"
15515                "{}",
15516                SpaceAfterRequires);
15517   verifyFormat("void f(auto x)\n"
15518                "  requires(requires(int i) { x + i; })\n"
15519                "{}",
15520                SpaceAfterRequires);
15521   verifyFormat("if (requires(int i) { x + i; })\n"
15522                "  return;",
15523                SpaceAfterRequires);
15524   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15525   verifyFormat("template <typename T>\n"
15526                "  requires(Foo<T>)\n"
15527                "class Bar;",
15528                SpaceAfterRequires);
15529 
15530   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15531   verifyFormat("void f(auto x)\n"
15532                "  requires requires(int i) { x + i; }\n"
15533                "{}",
15534                SpaceAfterRequires);
15535   verifyFormat("void f(auto x)\n"
15536                "  requires (requires(int i) { x + i; })\n"
15537                "{}",
15538                SpaceAfterRequires);
15539   verifyFormat("if (requires(int i) { x + i; })\n"
15540                "  return;",
15541                SpaceAfterRequires);
15542   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15543   verifyFormat("template <typename T>\n"
15544                "  requires (Foo<T>)\n"
15545                "class Bar;",
15546                SpaceAfterRequires);
15547 
15548   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15549   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15550   verifyFormat("void f(auto x)\n"
15551                "  requires requires (int i) { x + i; }\n"
15552                "{}",
15553                SpaceAfterRequires);
15554   verifyFormat("void f(auto x)\n"
15555                "  requires(requires (int i) { x + i; })\n"
15556                "{}",
15557                SpaceAfterRequires);
15558   verifyFormat("if (requires (int i) { x + i; })\n"
15559                "  return;",
15560                SpaceAfterRequires);
15561   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15562   verifyFormat("template <typename T>\n"
15563                "  requires(Foo<T>)\n"
15564                "class Bar;",
15565                SpaceAfterRequires);
15566 
15567   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15568   verifyFormat("void f(auto x)\n"
15569                "  requires requires (int i) { x + i; }\n"
15570                "{}",
15571                SpaceAfterRequires);
15572   verifyFormat("void f(auto x)\n"
15573                "  requires (requires (int i) { x + i; })\n"
15574                "{}",
15575                SpaceAfterRequires);
15576   verifyFormat("if (requires (int i) { x + i; })\n"
15577                "  return;",
15578                SpaceAfterRequires);
15579   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15580   verifyFormat("template <typename T>\n"
15581                "  requires (Foo<T>)\n"
15582                "class Bar;",
15583                SpaceAfterRequires);
15584 }
15585 
15586 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15587   FormatStyle Spaces = getLLVMStyle();
15588   Spaces.SpaceAfterLogicalNot = true;
15589 
15590   verifyFormat("bool x = ! y", Spaces);
15591   verifyFormat("if (! isFailure())", Spaces);
15592   verifyFormat("if (! (a && b))", Spaces);
15593   verifyFormat("\"Error!\"", Spaces);
15594   verifyFormat("! ! x", Spaces);
15595 }
15596 
15597 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15598   FormatStyle Spaces = getLLVMStyle();
15599 
15600   Spaces.SpacesInParentheses = true;
15601   verifyFormat("do_something( ::globalVar );", Spaces);
15602   verifyFormat("call( x, y, z );", Spaces);
15603   verifyFormat("call();", Spaces);
15604   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15605   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15606                Spaces);
15607   verifyFormat("while ( (bool)1 )\n"
15608                "  continue;",
15609                Spaces);
15610   verifyFormat("for ( ;; )\n"
15611                "  continue;",
15612                Spaces);
15613   verifyFormat("if ( true )\n"
15614                "  f();\n"
15615                "else if ( true )\n"
15616                "  f();",
15617                Spaces);
15618   verifyFormat("do {\n"
15619                "  do_something( (int)i );\n"
15620                "} while ( something() );",
15621                Spaces);
15622   verifyFormat("switch ( x ) {\n"
15623                "default:\n"
15624                "  break;\n"
15625                "}",
15626                Spaces);
15627 
15628   Spaces.SpacesInParentheses = false;
15629   Spaces.SpacesInCStyleCastParentheses = true;
15630   verifyFormat("Type *A = ( Type * )P;", Spaces);
15631   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15632   verifyFormat("x = ( int32 )y;", Spaces);
15633   verifyFormat("int a = ( int )(2.0f);", Spaces);
15634   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15635   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15636   verifyFormat("#define x (( int )-1)", Spaces);
15637 
15638   // Run the first set of tests again with:
15639   Spaces.SpacesInParentheses = false;
15640   Spaces.SpaceInEmptyParentheses = true;
15641   Spaces.SpacesInCStyleCastParentheses = true;
15642   verifyFormat("call(x, y, z);", Spaces);
15643   verifyFormat("call( );", Spaces);
15644   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15645   verifyFormat("while (( bool )1)\n"
15646                "  continue;",
15647                Spaces);
15648   verifyFormat("for (;;)\n"
15649                "  continue;",
15650                Spaces);
15651   verifyFormat("if (true)\n"
15652                "  f( );\n"
15653                "else if (true)\n"
15654                "  f( );",
15655                Spaces);
15656   verifyFormat("do {\n"
15657                "  do_something(( int )i);\n"
15658                "} while (something( ));",
15659                Spaces);
15660   verifyFormat("switch (x) {\n"
15661                "default:\n"
15662                "  break;\n"
15663                "}",
15664                Spaces);
15665 
15666   // Run the first set of tests again with:
15667   Spaces.SpaceAfterCStyleCast = true;
15668   verifyFormat("call(x, y, z);", Spaces);
15669   verifyFormat("call( );", Spaces);
15670   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15671   verifyFormat("while (( bool ) 1)\n"
15672                "  continue;",
15673                Spaces);
15674   verifyFormat("for (;;)\n"
15675                "  continue;",
15676                Spaces);
15677   verifyFormat("if (true)\n"
15678                "  f( );\n"
15679                "else if (true)\n"
15680                "  f( );",
15681                Spaces);
15682   verifyFormat("do {\n"
15683                "  do_something(( int ) i);\n"
15684                "} while (something( ));",
15685                Spaces);
15686   verifyFormat("switch (x) {\n"
15687                "default:\n"
15688                "  break;\n"
15689                "}",
15690                Spaces);
15691   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15692   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15693   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15694   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15695   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15696 
15697   // Run subset of tests again with:
15698   Spaces.SpacesInCStyleCastParentheses = false;
15699   Spaces.SpaceAfterCStyleCast = true;
15700   verifyFormat("while ((bool) 1)\n"
15701                "  continue;",
15702                Spaces);
15703   verifyFormat("do {\n"
15704                "  do_something((int) i);\n"
15705                "} while (something( ));",
15706                Spaces);
15707 
15708   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15709   verifyFormat("size_t idx = (size_t) a;", Spaces);
15710   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15711   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15712   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15713   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15714   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15715   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15716   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15717   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15718   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15719   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15720   Spaces.ColumnLimit = 80;
15721   Spaces.IndentWidth = 4;
15722   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15723   verifyFormat("void foo( ) {\n"
15724                "    size_t foo = (*(function))(\n"
15725                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15726                "BarrrrrrrrrrrrLong,\n"
15727                "        FoooooooooLooooong);\n"
15728                "}",
15729                Spaces);
15730   Spaces.SpaceAfterCStyleCast = false;
15731   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15732   verifyFormat("size_t idx = (size_t)a;", Spaces);
15733   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15734   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15735   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15736   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15737   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15738 
15739   verifyFormat("void foo( ) {\n"
15740                "    size_t foo = (*(function))(\n"
15741                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15742                "BarrrrrrrrrrrrLong,\n"
15743                "        FoooooooooLooooong);\n"
15744                "}",
15745                Spaces);
15746 }
15747 
15748 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15749   verifyFormat("int a[5];");
15750   verifyFormat("a[3] += 42;");
15751 
15752   FormatStyle Spaces = getLLVMStyle();
15753   Spaces.SpacesInSquareBrackets = true;
15754   // Not lambdas.
15755   verifyFormat("int a[ 5 ];", Spaces);
15756   verifyFormat("a[ 3 ] += 42;", Spaces);
15757   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15758   verifyFormat("double &operator[](int i) { return 0; }\n"
15759                "int i;",
15760                Spaces);
15761   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15762   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15763   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15764   // Lambdas.
15765   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15766   verifyFormat("return [ i, args... ] {};", Spaces);
15767   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15768   verifyFormat("int foo = [ = ]() {};", Spaces);
15769   verifyFormat("int foo = [ & ]() {};", Spaces);
15770   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15771   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15772 }
15773 
15774 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15775   FormatStyle NoSpaceStyle = getLLVMStyle();
15776   verifyFormat("int a[5];", NoSpaceStyle);
15777   verifyFormat("a[3] += 42;", NoSpaceStyle);
15778 
15779   verifyFormat("int a[1];", NoSpaceStyle);
15780   verifyFormat("int 1 [a];", NoSpaceStyle);
15781   verifyFormat("int a[1][2];", NoSpaceStyle);
15782   verifyFormat("a[7] = 5;", NoSpaceStyle);
15783   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15784   verifyFormat("f([] {})", NoSpaceStyle);
15785 
15786   FormatStyle Space = getLLVMStyle();
15787   Space.SpaceBeforeSquareBrackets = true;
15788   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15789   verifyFormat("return [i, args...] {};", Space);
15790 
15791   verifyFormat("int a [5];", Space);
15792   verifyFormat("a [3] += 42;", Space);
15793   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15794   verifyFormat("double &operator[](int i) { return 0; }\n"
15795                "int i;",
15796                Space);
15797   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15798   verifyFormat("int i = a [a][a]->f();", Space);
15799   verifyFormat("int i = (*b) [a]->f();", Space);
15800 
15801   verifyFormat("int a [1];", Space);
15802   verifyFormat("int 1 [a];", Space);
15803   verifyFormat("int a [1][2];", Space);
15804   verifyFormat("a [7] = 5;", Space);
15805   verifyFormat("int a = (f()) [23];", Space);
15806   verifyFormat("f([] {})", Space);
15807 }
15808 
15809 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15810   verifyFormat("int a = 5;");
15811   verifyFormat("a += 42;");
15812   verifyFormat("a or_eq 8;");
15813 
15814   FormatStyle Spaces = getLLVMStyle();
15815   Spaces.SpaceBeforeAssignmentOperators = false;
15816   verifyFormat("int a= 5;", Spaces);
15817   verifyFormat("a+= 42;", Spaces);
15818   verifyFormat("a or_eq 8;", Spaces);
15819 }
15820 
15821 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15822   verifyFormat("class Foo : public Bar {};");
15823   verifyFormat("Foo::Foo() : foo(1) {}");
15824   verifyFormat("for (auto a : b) {\n}");
15825   verifyFormat("int x = a ? b : c;");
15826   verifyFormat("{\n"
15827                "label0:\n"
15828                "  int x = 0;\n"
15829                "}");
15830   verifyFormat("switch (x) {\n"
15831                "case 1:\n"
15832                "default:\n"
15833                "}");
15834   verifyFormat("switch (allBraces) {\n"
15835                "case 1: {\n"
15836                "  break;\n"
15837                "}\n"
15838                "case 2: {\n"
15839                "  [[fallthrough]];\n"
15840                "}\n"
15841                "default: {\n"
15842                "  break;\n"
15843                "}\n"
15844                "}");
15845 
15846   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15847   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15848   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15849   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15850   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15851   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15852   verifyFormat("{\n"
15853                "label1:\n"
15854                "  int x = 0;\n"
15855                "}",
15856                CtorInitializerStyle);
15857   verifyFormat("switch (x) {\n"
15858                "case 1:\n"
15859                "default:\n"
15860                "}",
15861                CtorInitializerStyle);
15862   verifyFormat("switch (allBraces) {\n"
15863                "case 1: {\n"
15864                "  break;\n"
15865                "}\n"
15866                "case 2: {\n"
15867                "  [[fallthrough]];\n"
15868                "}\n"
15869                "default: {\n"
15870                "  break;\n"
15871                "}\n"
15872                "}",
15873                CtorInitializerStyle);
15874   CtorInitializerStyle.BreakConstructorInitializers =
15875       FormatStyle::BCIS_AfterColon;
15876   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15877                "    aaaaaaaaaaaaaaaa(1),\n"
15878                "    bbbbbbbbbbbbbbbb(2) {}",
15879                CtorInitializerStyle);
15880   CtorInitializerStyle.BreakConstructorInitializers =
15881       FormatStyle::BCIS_BeforeComma;
15882   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15883                "    : aaaaaaaaaaaaaaaa(1)\n"
15884                "    , bbbbbbbbbbbbbbbb(2) {}",
15885                CtorInitializerStyle);
15886   CtorInitializerStyle.BreakConstructorInitializers =
15887       FormatStyle::BCIS_BeforeColon;
15888   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15889                "    : aaaaaaaaaaaaaaaa(1),\n"
15890                "      bbbbbbbbbbbbbbbb(2) {}",
15891                CtorInitializerStyle);
15892   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15893   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15894                ": aaaaaaaaaaaaaaaa(1),\n"
15895                "  bbbbbbbbbbbbbbbb(2) {}",
15896                CtorInitializerStyle);
15897 
15898   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15899   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15900   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15901   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15902   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15903   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15904   verifyFormat("{\n"
15905                "label2:\n"
15906                "  int x = 0;\n"
15907                "}",
15908                InheritanceStyle);
15909   verifyFormat("switch (x) {\n"
15910                "case 1:\n"
15911                "default:\n"
15912                "}",
15913                InheritanceStyle);
15914   verifyFormat("switch (allBraces) {\n"
15915                "case 1: {\n"
15916                "  break;\n"
15917                "}\n"
15918                "case 2: {\n"
15919                "  [[fallthrough]];\n"
15920                "}\n"
15921                "default: {\n"
15922                "  break;\n"
15923                "}\n"
15924                "}",
15925                InheritanceStyle);
15926   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15927   verifyFormat("class Foooooooooooooooooooooo\n"
15928                "    : public aaaaaaaaaaaaaaaaaa,\n"
15929                "      public bbbbbbbbbbbbbbbbbb {\n"
15930                "}",
15931                InheritanceStyle);
15932   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15933   verifyFormat("class Foooooooooooooooooooooo:\n"
15934                "    public aaaaaaaaaaaaaaaaaa,\n"
15935                "    public bbbbbbbbbbbbbbbbbb {\n"
15936                "}",
15937                InheritanceStyle);
15938   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15939   verifyFormat("class Foooooooooooooooooooooo\n"
15940                "    : public aaaaaaaaaaaaaaaaaa\n"
15941                "    , public bbbbbbbbbbbbbbbbbb {\n"
15942                "}",
15943                InheritanceStyle);
15944   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15945   verifyFormat("class Foooooooooooooooooooooo\n"
15946                "    : public aaaaaaaaaaaaaaaaaa,\n"
15947                "      public bbbbbbbbbbbbbbbbbb {\n"
15948                "}",
15949                InheritanceStyle);
15950   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15951   verifyFormat("class Foooooooooooooooooooooo\n"
15952                ": public aaaaaaaaaaaaaaaaaa,\n"
15953                "  public bbbbbbbbbbbbbbbbbb {}",
15954                InheritanceStyle);
15955 
15956   FormatStyle ForLoopStyle = getLLVMStyle();
15957   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15958   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15959   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15960   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15961   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15962   verifyFormat("{\n"
15963                "label2:\n"
15964                "  int x = 0;\n"
15965                "}",
15966                ForLoopStyle);
15967   verifyFormat("switch (x) {\n"
15968                "case 1:\n"
15969                "default:\n"
15970                "}",
15971                ForLoopStyle);
15972   verifyFormat("switch (allBraces) {\n"
15973                "case 1: {\n"
15974                "  break;\n"
15975                "}\n"
15976                "case 2: {\n"
15977                "  [[fallthrough]];\n"
15978                "}\n"
15979                "default: {\n"
15980                "  break;\n"
15981                "}\n"
15982                "}",
15983                ForLoopStyle);
15984 
15985   FormatStyle CaseStyle = getLLVMStyle();
15986   CaseStyle.SpaceBeforeCaseColon = true;
15987   verifyFormat("class Foo : public Bar {};", CaseStyle);
15988   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15989   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15990   verifyFormat("int x = a ? b : c;", CaseStyle);
15991   verifyFormat("switch (x) {\n"
15992                "case 1 :\n"
15993                "default :\n"
15994                "}",
15995                CaseStyle);
15996   verifyFormat("switch (allBraces) {\n"
15997                "case 1 : {\n"
15998                "  break;\n"
15999                "}\n"
16000                "case 2 : {\n"
16001                "  [[fallthrough]];\n"
16002                "}\n"
16003                "default : {\n"
16004                "  break;\n"
16005                "}\n"
16006                "}",
16007                CaseStyle);
16008 
16009   FormatStyle NoSpaceStyle = getLLVMStyle();
16010   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
16011   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
16012   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
16013   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
16014   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
16015   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
16016   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
16017   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
16018   verifyFormat("{\n"
16019                "label3:\n"
16020                "  int x = 0;\n"
16021                "}",
16022                NoSpaceStyle);
16023   verifyFormat("switch (x) {\n"
16024                "case 1:\n"
16025                "default:\n"
16026                "}",
16027                NoSpaceStyle);
16028   verifyFormat("switch (allBraces) {\n"
16029                "case 1: {\n"
16030                "  break;\n"
16031                "}\n"
16032                "case 2: {\n"
16033                "  [[fallthrough]];\n"
16034                "}\n"
16035                "default: {\n"
16036                "  break;\n"
16037                "}\n"
16038                "}",
16039                NoSpaceStyle);
16040 
16041   FormatStyle InvertedSpaceStyle = getLLVMStyle();
16042   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
16043   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
16044   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
16045   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
16046   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
16047   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
16048   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
16049   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
16050   verifyFormat("{\n"
16051                "label3:\n"
16052                "  int x = 0;\n"
16053                "}",
16054                InvertedSpaceStyle);
16055   verifyFormat("switch (x) {\n"
16056                "case 1 :\n"
16057                "case 2 : {\n"
16058                "  break;\n"
16059                "}\n"
16060                "default :\n"
16061                "  break;\n"
16062                "}",
16063                InvertedSpaceStyle);
16064   verifyFormat("switch (allBraces) {\n"
16065                "case 1 : {\n"
16066                "  break;\n"
16067                "}\n"
16068                "case 2 : {\n"
16069                "  [[fallthrough]];\n"
16070                "}\n"
16071                "default : {\n"
16072                "  break;\n"
16073                "}\n"
16074                "}",
16075                InvertedSpaceStyle);
16076 }
16077 
16078 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
16079   FormatStyle Style = getLLVMStyle();
16080 
16081   Style.PointerAlignment = FormatStyle::PAS_Left;
16082   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
16083   verifyFormat("void* const* x = NULL;", Style);
16084 
16085 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
16086   do {                                                                         \
16087     Style.PointerAlignment = FormatStyle::Pointers;                            \
16088     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
16089     verifyFormat(Code, Style);                                                 \
16090   } while (false)
16091 
16092   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
16093   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
16094   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
16095 
16096   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
16097   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
16098   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
16099 
16100   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
16101   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
16102   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
16103 
16104   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
16105   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
16106   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
16107 
16108   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
16109   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
16110                         SAPQ_Default);
16111   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
16112                         SAPQ_Default);
16113 
16114   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
16115   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
16116                         SAPQ_Before);
16117   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
16118                         SAPQ_Before);
16119 
16120   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
16121   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
16122   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
16123                         SAPQ_After);
16124 
16125   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
16126   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
16127   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
16128 
16129 #undef verifyQualifierSpaces
16130 
16131   FormatStyle Spaces = getLLVMStyle();
16132   Spaces.AttributeMacros.push_back("qualified");
16133   Spaces.PointerAlignment = FormatStyle::PAS_Right;
16134   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
16135   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
16136   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
16137   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
16138   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
16139   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16140   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
16141   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
16142   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
16143   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
16144   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
16145   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16146 
16147   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
16148   Spaces.PointerAlignment = FormatStyle::PAS_Left;
16149   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
16150   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
16151   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
16152   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
16153   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
16154   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16155   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
16156   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
16157   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
16158   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
16159   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
16160   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
16161   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16162 
16163   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
16164   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
16165   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
16166   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
16167   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
16168   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
16169   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
16170   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16171 }
16172 
16173 TEST_F(FormatTest, AlignConsecutiveMacros) {
16174   FormatStyle Style = getLLVMStyle();
16175   Style.AlignConsecutiveAssignments.Enabled = true;
16176   Style.AlignConsecutiveDeclarations.Enabled = true;
16177 
16178   verifyFormat("#define a 3\n"
16179                "#define bbbb 4\n"
16180                "#define ccc (5)",
16181                Style);
16182 
16183   verifyFormat("#define f(x) (x * x)\n"
16184                "#define fff(x, y, z) (x * y + z)\n"
16185                "#define ffff(x, y) (x - y)",
16186                Style);
16187 
16188   verifyFormat("#define foo(x, y) (x + y)\n"
16189                "#define bar (5, 6)(2 + 2)",
16190                Style);
16191 
16192   verifyFormat("#define a 3\n"
16193                "#define bbbb 4\n"
16194                "#define ccc (5)\n"
16195                "#define f(x) (x * x)\n"
16196                "#define fff(x, y, z) (x * y + z)\n"
16197                "#define ffff(x, y) (x - y)",
16198                Style);
16199 
16200   Style.AlignConsecutiveMacros.Enabled = true;
16201   verifyFormat("#define a    3\n"
16202                "#define bbbb 4\n"
16203                "#define ccc  (5)",
16204                Style);
16205 
16206   verifyFormat("#define true  1\n"
16207                "#define false 0",
16208                Style);
16209 
16210   verifyFormat("#define f(x)         (x * x)\n"
16211                "#define fff(x, y, z) (x * y + z)\n"
16212                "#define ffff(x, y)   (x - y)",
16213                Style);
16214 
16215   verifyFormat("#define foo(x, y) (x + y)\n"
16216                "#define bar       (5, 6)(2 + 2)",
16217                Style);
16218 
16219   verifyFormat("#define a            3\n"
16220                "#define bbbb         4\n"
16221                "#define ccc          (5)\n"
16222                "#define f(x)         (x * x)\n"
16223                "#define fff(x, y, z) (x * y + z)\n"
16224                "#define ffff(x, y)   (x - y)",
16225                Style);
16226 
16227   verifyFormat("#define a         5\n"
16228                "#define foo(x, y) (x + y)\n"
16229                "#define CCC       (6)\n"
16230                "auto lambda = []() {\n"
16231                "  auto  ii = 0;\n"
16232                "  float j  = 0;\n"
16233                "  return 0;\n"
16234                "};\n"
16235                "int   i  = 0;\n"
16236                "float i2 = 0;\n"
16237                "auto  v  = type{\n"
16238                "    i = 1,   //\n"
16239                "    (i = 2), //\n"
16240                "    i = 3    //\n"
16241                "};",
16242                Style);
16243 
16244   Style.AlignConsecutiveMacros.Enabled = false;
16245   Style.ColumnLimit = 20;
16246 
16247   verifyFormat("#define a          \\\n"
16248                "  \"aabbbbbbbbbbbb\"\n"
16249                "#define D          \\\n"
16250                "  \"aabbbbbbbbbbbb\" \\\n"
16251                "  \"ccddeeeeeeeee\"\n"
16252                "#define B          \\\n"
16253                "  \"QQQQQQQQQQQQQ\"  \\\n"
16254                "  \"FFFFFFFFFFFFF\"  \\\n"
16255                "  \"LLLLLLLL\"\n",
16256                Style);
16257 
16258   Style.AlignConsecutiveMacros.Enabled = true;
16259   verifyFormat("#define a          \\\n"
16260                "  \"aabbbbbbbbbbbb\"\n"
16261                "#define D          \\\n"
16262                "  \"aabbbbbbbbbbbb\" \\\n"
16263                "  \"ccddeeeeeeeee\"\n"
16264                "#define B          \\\n"
16265                "  \"QQQQQQQQQQQQQ\"  \\\n"
16266                "  \"FFFFFFFFFFFFF\"  \\\n"
16267                "  \"LLLLLLLL\"\n",
16268                Style);
16269 
16270   // Test across comments
16271   Style.MaxEmptyLinesToKeep = 10;
16272   Style.ReflowComments = false;
16273   Style.AlignConsecutiveMacros.AcrossComments = true;
16274   EXPECT_EQ("#define a    3\n"
16275             "// line comment\n"
16276             "#define bbbb 4\n"
16277             "#define ccc  (5)",
16278             format("#define a 3\n"
16279                    "// line comment\n"
16280                    "#define bbbb 4\n"
16281                    "#define ccc (5)",
16282                    Style));
16283 
16284   EXPECT_EQ("#define a    3\n"
16285             "/* block comment */\n"
16286             "#define bbbb 4\n"
16287             "#define ccc  (5)",
16288             format("#define a  3\n"
16289                    "/* block comment */\n"
16290                    "#define bbbb 4\n"
16291                    "#define ccc (5)",
16292                    Style));
16293 
16294   EXPECT_EQ("#define a    3\n"
16295             "/* multi-line *\n"
16296             " * block comment */\n"
16297             "#define bbbb 4\n"
16298             "#define ccc  (5)",
16299             format("#define a 3\n"
16300                    "/* multi-line *\n"
16301                    " * block comment */\n"
16302                    "#define bbbb 4\n"
16303                    "#define ccc (5)",
16304                    Style));
16305 
16306   EXPECT_EQ("#define a    3\n"
16307             "// multi-line line comment\n"
16308             "//\n"
16309             "#define bbbb 4\n"
16310             "#define ccc  (5)",
16311             format("#define a  3\n"
16312                    "// multi-line line comment\n"
16313                    "//\n"
16314                    "#define bbbb 4\n"
16315                    "#define ccc (5)",
16316                    Style));
16317 
16318   EXPECT_EQ("#define a 3\n"
16319             "// empty lines still break.\n"
16320             "\n"
16321             "#define bbbb 4\n"
16322             "#define ccc  (5)",
16323             format("#define a     3\n"
16324                    "// empty lines still break.\n"
16325                    "\n"
16326                    "#define bbbb     4\n"
16327                    "#define ccc  (5)",
16328                    Style));
16329 
16330   // Test across empty lines
16331   Style.AlignConsecutiveMacros.AcrossComments = false;
16332   Style.AlignConsecutiveMacros.AcrossEmptyLines = true;
16333   EXPECT_EQ("#define a    3\n"
16334             "\n"
16335             "#define bbbb 4\n"
16336             "#define ccc  (5)",
16337             format("#define a 3\n"
16338                    "\n"
16339                    "#define bbbb 4\n"
16340                    "#define ccc (5)",
16341                    Style));
16342 
16343   EXPECT_EQ("#define a    3\n"
16344             "\n"
16345             "\n"
16346             "\n"
16347             "#define bbbb 4\n"
16348             "#define ccc  (5)",
16349             format("#define a        3\n"
16350                    "\n"
16351                    "\n"
16352                    "\n"
16353                    "#define bbbb 4\n"
16354                    "#define ccc (5)",
16355                    Style));
16356 
16357   EXPECT_EQ("#define a 3\n"
16358             "// comments should break alignment\n"
16359             "//\n"
16360             "#define bbbb 4\n"
16361             "#define ccc  (5)",
16362             format("#define a        3\n"
16363                    "// comments should break alignment\n"
16364                    "//\n"
16365                    "#define bbbb 4\n"
16366                    "#define ccc (5)",
16367                    Style));
16368 
16369   // Test across empty lines and comments
16370   Style.AlignConsecutiveMacros.AcrossComments = true;
16371   verifyFormat("#define a    3\n"
16372                "\n"
16373                "// line comment\n"
16374                "#define bbbb 4\n"
16375                "#define ccc  (5)",
16376                Style);
16377 
16378   EXPECT_EQ("#define a    3\n"
16379             "\n"
16380             "\n"
16381             "/* multi-line *\n"
16382             " * block comment */\n"
16383             "\n"
16384             "\n"
16385             "#define bbbb 4\n"
16386             "#define ccc  (5)",
16387             format("#define a 3\n"
16388                    "\n"
16389                    "\n"
16390                    "/* multi-line *\n"
16391                    " * block comment */\n"
16392                    "\n"
16393                    "\n"
16394                    "#define bbbb 4\n"
16395                    "#define ccc (5)",
16396                    Style));
16397 
16398   EXPECT_EQ("#define a    3\n"
16399             "\n"
16400             "\n"
16401             "/* multi-line *\n"
16402             " * block comment */\n"
16403             "\n"
16404             "\n"
16405             "#define bbbb 4\n"
16406             "#define ccc  (5)",
16407             format("#define a 3\n"
16408                    "\n"
16409                    "\n"
16410                    "/* multi-line *\n"
16411                    " * block comment */\n"
16412                    "\n"
16413                    "\n"
16414                    "#define bbbb 4\n"
16415                    "#define ccc       (5)",
16416                    Style));
16417 }
16418 
16419 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16420   FormatStyle Alignment = getLLVMStyle();
16421   Alignment.AlignConsecutiveMacros.Enabled = true;
16422   Alignment.AlignConsecutiveAssignments.Enabled = true;
16423   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16424 
16425   Alignment.MaxEmptyLinesToKeep = 10;
16426   /* Test alignment across empty lines */
16427   EXPECT_EQ("int a           = 5;\n"
16428             "\n"
16429             "int oneTwoThree = 123;",
16430             format("int a       = 5;\n"
16431                    "\n"
16432                    "int oneTwoThree= 123;",
16433                    Alignment));
16434   EXPECT_EQ("int a           = 5;\n"
16435             "int one         = 1;\n"
16436             "\n"
16437             "int oneTwoThree = 123;",
16438             format("int a = 5;\n"
16439                    "int one = 1;\n"
16440                    "\n"
16441                    "int oneTwoThree = 123;",
16442                    Alignment));
16443   EXPECT_EQ("int a           = 5;\n"
16444             "int one         = 1;\n"
16445             "\n"
16446             "int oneTwoThree = 123;\n"
16447             "int oneTwo      = 12;",
16448             format("int a = 5;\n"
16449                    "int one = 1;\n"
16450                    "\n"
16451                    "int oneTwoThree = 123;\n"
16452                    "int oneTwo = 12;",
16453                    Alignment));
16454 
16455   /* Test across comments */
16456   EXPECT_EQ("int a = 5;\n"
16457             "/* block comment */\n"
16458             "int oneTwoThree = 123;",
16459             format("int a = 5;\n"
16460                    "/* block comment */\n"
16461                    "int oneTwoThree=123;",
16462                    Alignment));
16463 
16464   EXPECT_EQ("int a = 5;\n"
16465             "// line comment\n"
16466             "int oneTwoThree = 123;",
16467             format("int a = 5;\n"
16468                    "// line comment\n"
16469                    "int oneTwoThree=123;",
16470                    Alignment));
16471 
16472   /* Test across comments and newlines */
16473   EXPECT_EQ("int a = 5;\n"
16474             "\n"
16475             "/* block comment */\n"
16476             "int oneTwoThree = 123;",
16477             format("int a = 5;\n"
16478                    "\n"
16479                    "/* block comment */\n"
16480                    "int oneTwoThree=123;",
16481                    Alignment));
16482 
16483   EXPECT_EQ("int a = 5;\n"
16484             "\n"
16485             "// line comment\n"
16486             "int oneTwoThree = 123;",
16487             format("int a = 5;\n"
16488                    "\n"
16489                    "// line comment\n"
16490                    "int oneTwoThree=123;",
16491                    Alignment));
16492 }
16493 
16494 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16495   FormatStyle Alignment = getLLVMStyle();
16496   Alignment.AlignConsecutiveDeclarations.Enabled = true;
16497   Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true;
16498   Alignment.AlignConsecutiveDeclarations.AcrossComments = true;
16499 
16500   Alignment.MaxEmptyLinesToKeep = 10;
16501   /* Test alignment across empty lines */
16502   EXPECT_EQ("int         a = 5;\n"
16503             "\n"
16504             "float const oneTwoThree = 123;",
16505             format("int a = 5;\n"
16506                    "\n"
16507                    "float const oneTwoThree = 123;",
16508                    Alignment));
16509   EXPECT_EQ("int         a = 5;\n"
16510             "float const one = 1;\n"
16511             "\n"
16512             "int         oneTwoThree = 123;",
16513             format("int a = 5;\n"
16514                    "float const one = 1;\n"
16515                    "\n"
16516                    "int oneTwoThree = 123;",
16517                    Alignment));
16518 
16519   /* Test across comments */
16520   EXPECT_EQ("float const a = 5;\n"
16521             "/* block comment */\n"
16522             "int         oneTwoThree = 123;",
16523             format("float const a = 5;\n"
16524                    "/* block comment */\n"
16525                    "int oneTwoThree=123;",
16526                    Alignment));
16527 
16528   EXPECT_EQ("float const a = 5;\n"
16529             "// line comment\n"
16530             "int         oneTwoThree = 123;",
16531             format("float const a = 5;\n"
16532                    "// line comment\n"
16533                    "int oneTwoThree=123;",
16534                    Alignment));
16535 
16536   /* Test across comments and newlines */
16537   EXPECT_EQ("float const a = 5;\n"
16538             "\n"
16539             "/* block comment */\n"
16540             "int         oneTwoThree = 123;",
16541             format("float const a = 5;\n"
16542                    "\n"
16543                    "/* block comment */\n"
16544                    "int         oneTwoThree=123;",
16545                    Alignment));
16546 
16547   EXPECT_EQ("float const a = 5;\n"
16548             "\n"
16549             "// line comment\n"
16550             "int         oneTwoThree = 123;",
16551             format("float const a = 5;\n"
16552                    "\n"
16553                    "// line comment\n"
16554                    "int oneTwoThree=123;",
16555                    Alignment));
16556 }
16557 
16558 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16559   FormatStyle Alignment = getLLVMStyle();
16560   Alignment.AlignConsecutiveBitFields.Enabled = true;
16561   Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true;
16562   Alignment.AlignConsecutiveBitFields.AcrossComments = true;
16563 
16564   Alignment.MaxEmptyLinesToKeep = 10;
16565   /* Test alignment across empty lines */
16566   EXPECT_EQ("int a            : 5;\n"
16567             "\n"
16568             "int longbitfield : 6;",
16569             format("int a : 5;\n"
16570                    "\n"
16571                    "int longbitfield : 6;",
16572                    Alignment));
16573   EXPECT_EQ("int a            : 5;\n"
16574             "int one          : 1;\n"
16575             "\n"
16576             "int longbitfield : 6;",
16577             format("int a : 5;\n"
16578                    "int one : 1;\n"
16579                    "\n"
16580                    "int longbitfield : 6;",
16581                    Alignment));
16582 
16583   /* Test across comments */
16584   EXPECT_EQ("int a            : 5;\n"
16585             "/* block comment */\n"
16586             "int longbitfield : 6;",
16587             format("int a : 5;\n"
16588                    "/* block comment */\n"
16589                    "int longbitfield : 6;",
16590                    Alignment));
16591   EXPECT_EQ("int a            : 5;\n"
16592             "int one          : 1;\n"
16593             "// line comment\n"
16594             "int longbitfield : 6;",
16595             format("int a : 5;\n"
16596                    "int one : 1;\n"
16597                    "// line comment\n"
16598                    "int longbitfield : 6;",
16599                    Alignment));
16600 
16601   /* Test across comments and newlines */
16602   EXPECT_EQ("int a            : 5;\n"
16603             "/* block comment */\n"
16604             "\n"
16605             "int longbitfield : 6;",
16606             format("int a : 5;\n"
16607                    "/* block comment */\n"
16608                    "\n"
16609                    "int longbitfield : 6;",
16610                    Alignment));
16611   EXPECT_EQ("int a            : 5;\n"
16612             "int one          : 1;\n"
16613             "\n"
16614             "// line comment\n"
16615             "\n"
16616             "int longbitfield : 6;",
16617             format("int a : 5;\n"
16618                    "int one : 1;\n"
16619                    "\n"
16620                    "// line comment \n"
16621                    "\n"
16622                    "int longbitfield : 6;",
16623                    Alignment));
16624 }
16625 
16626 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16627   FormatStyle Alignment = getLLVMStyle();
16628   Alignment.AlignConsecutiveMacros.Enabled = true;
16629   Alignment.AlignConsecutiveAssignments.Enabled = true;
16630   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16631 
16632   Alignment.MaxEmptyLinesToKeep = 10;
16633   /* Test alignment across empty lines */
16634   EXPECT_EQ("int a = 5;\n"
16635             "\n"
16636             "int oneTwoThree = 123;",
16637             format("int a       = 5;\n"
16638                    "\n"
16639                    "int oneTwoThree= 123;",
16640                    Alignment));
16641   EXPECT_EQ("int a   = 5;\n"
16642             "int one = 1;\n"
16643             "\n"
16644             "int oneTwoThree = 123;",
16645             format("int a = 5;\n"
16646                    "int one = 1;\n"
16647                    "\n"
16648                    "int oneTwoThree = 123;",
16649                    Alignment));
16650 
16651   /* Test across comments */
16652   EXPECT_EQ("int a           = 5;\n"
16653             "/* block comment */\n"
16654             "int oneTwoThree = 123;",
16655             format("int a = 5;\n"
16656                    "/* block comment */\n"
16657                    "int oneTwoThree=123;",
16658                    Alignment));
16659 
16660   EXPECT_EQ("int a           = 5;\n"
16661             "// line comment\n"
16662             "int oneTwoThree = 123;",
16663             format("int a = 5;\n"
16664                    "// line comment\n"
16665                    "int oneTwoThree=123;",
16666                    Alignment));
16667 
16668   EXPECT_EQ("int a           = 5;\n"
16669             "/*\n"
16670             " * multi-line block comment\n"
16671             " */\n"
16672             "int oneTwoThree = 123;",
16673             format("int a = 5;\n"
16674                    "/*\n"
16675                    " * multi-line block comment\n"
16676                    " */\n"
16677                    "int oneTwoThree=123;",
16678                    Alignment));
16679 
16680   EXPECT_EQ("int a           = 5;\n"
16681             "//\n"
16682             "// multi-line line comment\n"
16683             "//\n"
16684             "int oneTwoThree = 123;",
16685             format("int a = 5;\n"
16686                    "//\n"
16687                    "// multi-line line comment\n"
16688                    "//\n"
16689                    "int oneTwoThree=123;",
16690                    Alignment));
16691 
16692   /* Test across comments and newlines */
16693   EXPECT_EQ("int a = 5;\n"
16694             "\n"
16695             "/* block comment */\n"
16696             "int oneTwoThree = 123;",
16697             format("int a = 5;\n"
16698                    "\n"
16699                    "/* block comment */\n"
16700                    "int oneTwoThree=123;",
16701                    Alignment));
16702 
16703   EXPECT_EQ("int a = 5;\n"
16704             "\n"
16705             "// line comment\n"
16706             "int oneTwoThree = 123;",
16707             format("int a = 5;\n"
16708                    "\n"
16709                    "// line comment\n"
16710                    "int oneTwoThree=123;",
16711                    Alignment));
16712 }
16713 
16714 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16715   FormatStyle Alignment = getLLVMStyle();
16716   Alignment.AlignConsecutiveMacros.Enabled = true;
16717   Alignment.AlignConsecutiveAssignments.Enabled = true;
16718   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16719   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16720   verifyFormat("int a           = 5;\n"
16721                "int oneTwoThree = 123;",
16722                Alignment);
16723   verifyFormat("int a           = method();\n"
16724                "int oneTwoThree = 133;",
16725                Alignment);
16726   verifyFormat("a &= 5;\n"
16727                "bcd *= 5;\n"
16728                "ghtyf += 5;\n"
16729                "dvfvdb -= 5;\n"
16730                "a /= 5;\n"
16731                "vdsvsv %= 5;\n"
16732                "sfdbddfbdfbb ^= 5;\n"
16733                "dvsdsv |= 5;\n"
16734                "int dsvvdvsdvvv = 123;",
16735                Alignment);
16736   verifyFormat("int i = 1, j = 10;\n"
16737                "something = 2000;",
16738                Alignment);
16739   verifyFormat("something = 2000;\n"
16740                "int i = 1, j = 10;\n",
16741                Alignment);
16742   verifyFormat("something = 2000;\n"
16743                "another   = 911;\n"
16744                "int i = 1, j = 10;\n"
16745                "oneMore = 1;\n"
16746                "i       = 2;",
16747                Alignment);
16748   verifyFormat("int a   = 5;\n"
16749                "int one = 1;\n"
16750                "method();\n"
16751                "int oneTwoThree = 123;\n"
16752                "int oneTwo      = 12;",
16753                Alignment);
16754   verifyFormat("int oneTwoThree = 123;\n"
16755                "int oneTwo      = 12;\n"
16756                "method();\n",
16757                Alignment);
16758   verifyFormat("int oneTwoThree = 123; // comment\n"
16759                "int oneTwo      = 12;  // comment",
16760                Alignment);
16761 
16762   // Bug 25167
16763   /* Uncomment when fixed
16764     verifyFormat("#if A\n"
16765                  "#else\n"
16766                  "int aaaaaaaa = 12;\n"
16767                  "#endif\n"
16768                  "#if B\n"
16769                  "#else\n"
16770                  "int a = 12;\n"
16771                  "#endif\n",
16772                  Alignment);
16773     verifyFormat("enum foo {\n"
16774                  "#if A\n"
16775                  "#else\n"
16776                  "  aaaaaaaa = 12;\n"
16777                  "#endif\n"
16778                  "#if B\n"
16779                  "#else\n"
16780                  "  a = 12;\n"
16781                  "#endif\n"
16782                  "};\n",
16783                  Alignment);
16784   */
16785 
16786   Alignment.MaxEmptyLinesToKeep = 10;
16787   /* Test alignment across empty lines */
16788   EXPECT_EQ("int a           = 5;\n"
16789             "\n"
16790             "int oneTwoThree = 123;",
16791             format("int a       = 5;\n"
16792                    "\n"
16793                    "int oneTwoThree= 123;",
16794                    Alignment));
16795   EXPECT_EQ("int a           = 5;\n"
16796             "int one         = 1;\n"
16797             "\n"
16798             "int oneTwoThree = 123;",
16799             format("int a = 5;\n"
16800                    "int one = 1;\n"
16801                    "\n"
16802                    "int oneTwoThree = 123;",
16803                    Alignment));
16804   EXPECT_EQ("int a           = 5;\n"
16805             "int one         = 1;\n"
16806             "\n"
16807             "int oneTwoThree = 123;\n"
16808             "int oneTwo      = 12;",
16809             format("int a = 5;\n"
16810                    "int one = 1;\n"
16811                    "\n"
16812                    "int oneTwoThree = 123;\n"
16813                    "int oneTwo = 12;",
16814                    Alignment));
16815 
16816   /* Test across comments */
16817   EXPECT_EQ("int a           = 5;\n"
16818             "/* block comment */\n"
16819             "int oneTwoThree = 123;",
16820             format("int a = 5;\n"
16821                    "/* block comment */\n"
16822                    "int oneTwoThree=123;",
16823                    Alignment));
16824 
16825   EXPECT_EQ("int a           = 5;\n"
16826             "// line comment\n"
16827             "int oneTwoThree = 123;",
16828             format("int a = 5;\n"
16829                    "// line comment\n"
16830                    "int oneTwoThree=123;",
16831                    Alignment));
16832 
16833   /* Test across comments and newlines */
16834   EXPECT_EQ("int a           = 5;\n"
16835             "\n"
16836             "/* block comment */\n"
16837             "int oneTwoThree = 123;",
16838             format("int a = 5;\n"
16839                    "\n"
16840                    "/* block comment */\n"
16841                    "int oneTwoThree=123;",
16842                    Alignment));
16843 
16844   EXPECT_EQ("int a           = 5;\n"
16845             "\n"
16846             "// line comment\n"
16847             "int oneTwoThree = 123;",
16848             format("int a = 5;\n"
16849                    "\n"
16850                    "// line comment\n"
16851                    "int oneTwoThree=123;",
16852                    Alignment));
16853 
16854   EXPECT_EQ("int a           = 5;\n"
16855             "//\n"
16856             "// multi-line line comment\n"
16857             "//\n"
16858             "int oneTwoThree = 123;",
16859             format("int a = 5;\n"
16860                    "//\n"
16861                    "// multi-line line comment\n"
16862                    "//\n"
16863                    "int oneTwoThree=123;",
16864                    Alignment));
16865 
16866   EXPECT_EQ("int a           = 5;\n"
16867             "/*\n"
16868             " *  multi-line block comment\n"
16869             " */\n"
16870             "int oneTwoThree = 123;",
16871             format("int a = 5;\n"
16872                    "/*\n"
16873                    " *  multi-line block comment\n"
16874                    " */\n"
16875                    "int oneTwoThree=123;",
16876                    Alignment));
16877 
16878   EXPECT_EQ("int a           = 5;\n"
16879             "\n"
16880             "/* block comment */\n"
16881             "\n"
16882             "\n"
16883             "\n"
16884             "int oneTwoThree = 123;",
16885             format("int a = 5;\n"
16886                    "\n"
16887                    "/* block comment */\n"
16888                    "\n"
16889                    "\n"
16890                    "\n"
16891                    "int oneTwoThree=123;",
16892                    Alignment));
16893 
16894   EXPECT_EQ("int a           = 5;\n"
16895             "\n"
16896             "// line comment\n"
16897             "\n"
16898             "\n"
16899             "\n"
16900             "int oneTwoThree = 123;",
16901             format("int a = 5;\n"
16902                    "\n"
16903                    "// line comment\n"
16904                    "\n"
16905                    "\n"
16906                    "\n"
16907                    "int oneTwoThree=123;",
16908                    Alignment));
16909 
16910   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16911   verifyFormat("#define A \\\n"
16912                "  int aaaa       = 12; \\\n"
16913                "  int b          = 23; \\\n"
16914                "  int ccc        = 234; \\\n"
16915                "  int dddddddddd = 2345;",
16916                Alignment);
16917   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16918   verifyFormat("#define A               \\\n"
16919                "  int aaaa       = 12;  \\\n"
16920                "  int b          = 23;  \\\n"
16921                "  int ccc        = 234; \\\n"
16922                "  int dddddddddd = 2345;",
16923                Alignment);
16924   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16925   verifyFormat("#define A                                                      "
16926                "                \\\n"
16927                "  int aaaa       = 12;                                         "
16928                "                \\\n"
16929                "  int b          = 23;                                         "
16930                "                \\\n"
16931                "  int ccc        = 234;                                        "
16932                "                \\\n"
16933                "  int dddddddddd = 2345;",
16934                Alignment);
16935   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16936                "k = 4, int l = 5,\n"
16937                "                  int m = 6) {\n"
16938                "  int j      = 10;\n"
16939                "  otherThing = 1;\n"
16940                "}",
16941                Alignment);
16942   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16943                "  int i   = 1;\n"
16944                "  int j   = 2;\n"
16945                "  int big = 10000;\n"
16946                "}",
16947                Alignment);
16948   verifyFormat("class C {\n"
16949                "public:\n"
16950                "  int i            = 1;\n"
16951                "  virtual void f() = 0;\n"
16952                "};",
16953                Alignment);
16954   verifyFormat("int i = 1;\n"
16955                "if (SomeType t = getSomething()) {\n"
16956                "}\n"
16957                "int j   = 2;\n"
16958                "int big = 10000;",
16959                Alignment);
16960   verifyFormat("int j = 7;\n"
16961                "for (int k = 0; k < N; ++k) {\n"
16962                "}\n"
16963                "int j   = 2;\n"
16964                "int big = 10000;\n"
16965                "}",
16966                Alignment);
16967   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16968   verifyFormat("int i = 1;\n"
16969                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16970                "    = someLooooooooooooooooongFunction();\n"
16971                "int j = 2;",
16972                Alignment);
16973   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16974   verifyFormat("int i = 1;\n"
16975                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16976                "    someLooooooooooooooooongFunction();\n"
16977                "int j = 2;",
16978                Alignment);
16979 
16980   verifyFormat("auto lambda = []() {\n"
16981                "  auto i = 0;\n"
16982                "  return 0;\n"
16983                "};\n"
16984                "int i  = 0;\n"
16985                "auto v = type{\n"
16986                "    i = 1,   //\n"
16987                "    (i = 2), //\n"
16988                "    i = 3    //\n"
16989                "};",
16990                Alignment);
16991 
16992   verifyFormat(
16993       "int i      = 1;\n"
16994       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16995       "                          loooooooooooooooooooooongParameterB);\n"
16996       "int j      = 2;",
16997       Alignment);
16998 
16999   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17000                "          typename B   = very_long_type_name_1,\n"
17001                "          typename T_2 = very_long_type_name_2>\n"
17002                "auto foo() {}\n",
17003                Alignment);
17004   verifyFormat("int a, b = 1;\n"
17005                "int c  = 2;\n"
17006                "int dd = 3;\n",
17007                Alignment);
17008   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17009                "float b[1][] = {{3.f}};\n",
17010                Alignment);
17011   verifyFormat("for (int i = 0; i < 1; i++)\n"
17012                "  int x = 1;\n",
17013                Alignment);
17014   verifyFormat("for (i = 0; i < 1; i++)\n"
17015                "  x = 1;\n"
17016                "y = 1;\n",
17017                Alignment);
17018 
17019   Alignment.ReflowComments = true;
17020   Alignment.ColumnLimit = 50;
17021   EXPECT_EQ("int x   = 0;\n"
17022             "int yy  = 1; /// specificlennospace\n"
17023             "int zzz = 2;\n",
17024             format("int x   = 0;\n"
17025                    "int yy  = 1; ///specificlennospace\n"
17026                    "int zzz = 2;\n",
17027                    Alignment));
17028 }
17029 
17030 TEST_F(FormatTest, AlignCompoundAssignments) {
17031   FormatStyle Alignment = getLLVMStyle();
17032   Alignment.AlignConsecutiveAssignments.Enabled = true;
17033   Alignment.AlignConsecutiveAssignments.AlignCompound = true;
17034   Alignment.AlignConsecutiveAssignments.PadOperators = false;
17035   verifyFormat("sfdbddfbdfbb    = 5;\n"
17036                "dvsdsv          = 5;\n"
17037                "int dsvvdvsdvvv = 123;",
17038                Alignment);
17039   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
17040                "dvsdsv         |= 5;\n"
17041                "int dsvvdvsdvvv = 123;",
17042                Alignment);
17043   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
17044                "dvsdsv        <<= 5;\n"
17045                "int dsvvdvsdvvv = 123;",
17046                Alignment);
17047   // Test that `<=` is not treated as a compound assignment.
17048   verifyFormat("aa &= 5;\n"
17049                "b <= 10;\n"
17050                "c = 15;",
17051                Alignment);
17052   Alignment.AlignConsecutiveAssignments.PadOperators = true;
17053   verifyFormat("sfdbddfbdfbb    = 5;\n"
17054                "dvsdsv          = 5;\n"
17055                "int dsvvdvsdvvv = 123;",
17056                Alignment);
17057   verifyFormat("sfdbddfbdfbb    ^= 5;\n"
17058                "dvsdsv          |= 5;\n"
17059                "int dsvvdvsdvvv  = 123;",
17060                Alignment);
17061   verifyFormat("sfdbddfbdfbb     ^= 5;\n"
17062                "dvsdsv          <<= 5;\n"
17063                "int dsvvdvsdvvv   = 123;",
17064                Alignment);
17065   EXPECT_EQ("a   += 5;\n"
17066             "one  = 1;\n"
17067             "\n"
17068             "oneTwoThree = 123;\n",
17069             format("a += 5;\n"
17070                    "one = 1;\n"
17071                    "\n"
17072                    "oneTwoThree = 123;\n",
17073                    Alignment));
17074   EXPECT_EQ("a   += 5;\n"
17075             "one  = 1;\n"
17076             "//\n"
17077             "oneTwoThree = 123;\n",
17078             format("a += 5;\n"
17079                    "one = 1;\n"
17080                    "//\n"
17081                    "oneTwoThree = 123;\n",
17082                    Alignment));
17083   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
17084   EXPECT_EQ("a           += 5;\n"
17085             "one          = 1;\n"
17086             "\n"
17087             "oneTwoThree  = 123;\n",
17088             format("a += 5;\n"
17089                    "one = 1;\n"
17090                    "\n"
17091                    "oneTwoThree = 123;\n",
17092                    Alignment));
17093   EXPECT_EQ("a   += 5;\n"
17094             "one  = 1;\n"
17095             "//\n"
17096             "oneTwoThree = 123;\n",
17097             format("a += 5;\n"
17098                    "one = 1;\n"
17099                    "//\n"
17100                    "oneTwoThree = 123;\n",
17101                    Alignment));
17102   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false;
17103   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
17104   EXPECT_EQ("a   += 5;\n"
17105             "one  = 1;\n"
17106             "\n"
17107             "oneTwoThree = 123;\n",
17108             format("a += 5;\n"
17109                    "one = 1;\n"
17110                    "\n"
17111                    "oneTwoThree = 123;\n",
17112                    Alignment));
17113   EXPECT_EQ("a           += 5;\n"
17114             "one          = 1;\n"
17115             "//\n"
17116             "oneTwoThree  = 123;\n",
17117             format("a += 5;\n"
17118                    "one = 1;\n"
17119                    "//\n"
17120                    "oneTwoThree = 123;\n",
17121                    Alignment));
17122   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
17123   EXPECT_EQ("a            += 5;\n"
17124             "one         >>= 1;\n"
17125             "\n"
17126             "oneTwoThree   = 123;\n",
17127             format("a += 5;\n"
17128                    "one >>= 1;\n"
17129                    "\n"
17130                    "oneTwoThree = 123;\n",
17131                    Alignment));
17132   EXPECT_EQ("a            += 5;\n"
17133             "one           = 1;\n"
17134             "//\n"
17135             "oneTwoThree <<= 123;\n",
17136             format("a += 5;\n"
17137                    "one = 1;\n"
17138                    "//\n"
17139                    "oneTwoThree <<= 123;\n",
17140                    Alignment));
17141 }
17142 
17143 TEST_F(FormatTest, AlignConsecutiveAssignments) {
17144   FormatStyle Alignment = getLLVMStyle();
17145   Alignment.AlignConsecutiveMacros.Enabled = true;
17146   verifyFormat("int a = 5;\n"
17147                "int oneTwoThree = 123;",
17148                Alignment);
17149   verifyFormat("int a = 5;\n"
17150                "int oneTwoThree = 123;",
17151                Alignment);
17152 
17153   Alignment.AlignConsecutiveAssignments.Enabled = true;
17154   verifyFormat("int a           = 5;\n"
17155                "int oneTwoThree = 123;",
17156                Alignment);
17157   verifyFormat("int a           = method();\n"
17158                "int oneTwoThree = 133;",
17159                Alignment);
17160   verifyFormat("aa <= 5;\n"
17161                "a &= 5;\n"
17162                "bcd *= 5;\n"
17163                "ghtyf += 5;\n"
17164                "dvfvdb -= 5;\n"
17165                "a /= 5;\n"
17166                "vdsvsv %= 5;\n"
17167                "sfdbddfbdfbb ^= 5;\n"
17168                "dvsdsv |= 5;\n"
17169                "int dsvvdvsdvvv = 123;",
17170                Alignment);
17171   verifyFormat("int i = 1, j = 10;\n"
17172                "something = 2000;",
17173                Alignment);
17174   verifyFormat("something = 2000;\n"
17175                "int i = 1, j = 10;\n",
17176                Alignment);
17177   verifyFormat("something = 2000;\n"
17178                "another   = 911;\n"
17179                "int i = 1, j = 10;\n"
17180                "oneMore = 1;\n"
17181                "i       = 2;",
17182                Alignment);
17183   verifyFormat("int a   = 5;\n"
17184                "int one = 1;\n"
17185                "method();\n"
17186                "int oneTwoThree = 123;\n"
17187                "int oneTwo      = 12;",
17188                Alignment);
17189   verifyFormat("int oneTwoThree = 123;\n"
17190                "int oneTwo      = 12;\n"
17191                "method();\n",
17192                Alignment);
17193   verifyFormat("int oneTwoThree = 123; // comment\n"
17194                "int oneTwo      = 12;  // comment",
17195                Alignment);
17196   verifyFormat("int f()         = default;\n"
17197                "int &operator() = default;\n"
17198                "int &operator=() {",
17199                Alignment);
17200   verifyFormat("int f()         = delete;\n"
17201                "int &operator() = delete;\n"
17202                "int &operator=() {",
17203                Alignment);
17204   verifyFormat("int f()         = default; // comment\n"
17205                "int &operator() = default; // comment\n"
17206                "int &operator=() {",
17207                Alignment);
17208   verifyFormat("int f()         = default;\n"
17209                "int &operator() = default;\n"
17210                "int &operator==() {",
17211                Alignment);
17212   verifyFormat("int f()         = default;\n"
17213                "int &operator() = default;\n"
17214                "int &operator<=() {",
17215                Alignment);
17216   verifyFormat("int f()         = default;\n"
17217                "int &operator() = default;\n"
17218                "int &operator!=() {",
17219                Alignment);
17220   verifyFormat("int f()         = default;\n"
17221                "int &operator() = default;\n"
17222                "int &operator=();",
17223                Alignment);
17224   verifyFormat("int f()         = delete;\n"
17225                "int &operator() = delete;\n"
17226                "int &operator=();",
17227                Alignment);
17228   verifyFormat("/* long long padding */ int f() = default;\n"
17229                "int &operator()                 = default;\n"
17230                "int &operator/**/ =();",
17231                Alignment);
17232   // https://llvm.org/PR33697
17233   FormatStyle AlignmentWithPenalty = getLLVMStyle();
17234   AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true;
17235   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
17236   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
17237                "  void f() = delete;\n"
17238                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
17239                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
17240                "};\n",
17241                AlignmentWithPenalty);
17242 
17243   // Bug 25167
17244   /* Uncomment when fixed
17245     verifyFormat("#if A\n"
17246                  "#else\n"
17247                  "int aaaaaaaa = 12;\n"
17248                  "#endif\n"
17249                  "#if B\n"
17250                  "#else\n"
17251                  "int a = 12;\n"
17252                  "#endif\n",
17253                  Alignment);
17254     verifyFormat("enum foo {\n"
17255                  "#if A\n"
17256                  "#else\n"
17257                  "  aaaaaaaa = 12;\n"
17258                  "#endif\n"
17259                  "#if B\n"
17260                  "#else\n"
17261                  "  a = 12;\n"
17262                  "#endif\n"
17263                  "};\n",
17264                  Alignment);
17265   */
17266 
17267   EXPECT_EQ("int a = 5;\n"
17268             "\n"
17269             "int oneTwoThree = 123;",
17270             format("int a       = 5;\n"
17271                    "\n"
17272                    "int oneTwoThree= 123;",
17273                    Alignment));
17274   EXPECT_EQ("int a   = 5;\n"
17275             "int one = 1;\n"
17276             "\n"
17277             "int oneTwoThree = 123;",
17278             format("int a = 5;\n"
17279                    "int one = 1;\n"
17280                    "\n"
17281                    "int oneTwoThree = 123;",
17282                    Alignment));
17283   EXPECT_EQ("int a   = 5;\n"
17284             "int one = 1;\n"
17285             "\n"
17286             "int oneTwoThree = 123;\n"
17287             "int oneTwo      = 12;",
17288             format("int a = 5;\n"
17289                    "int one = 1;\n"
17290                    "\n"
17291                    "int oneTwoThree = 123;\n"
17292                    "int oneTwo = 12;",
17293                    Alignment));
17294   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17295   verifyFormat("#define A \\\n"
17296                "  int aaaa       = 12; \\\n"
17297                "  int b          = 23; \\\n"
17298                "  int ccc        = 234; \\\n"
17299                "  int dddddddddd = 2345;",
17300                Alignment);
17301   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17302   verifyFormat("#define A               \\\n"
17303                "  int aaaa       = 12;  \\\n"
17304                "  int b          = 23;  \\\n"
17305                "  int ccc        = 234; \\\n"
17306                "  int dddddddddd = 2345;",
17307                Alignment);
17308   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17309   verifyFormat("#define A                                                      "
17310                "                \\\n"
17311                "  int aaaa       = 12;                                         "
17312                "                \\\n"
17313                "  int b          = 23;                                         "
17314                "                \\\n"
17315                "  int ccc        = 234;                                        "
17316                "                \\\n"
17317                "  int dddddddddd = 2345;",
17318                Alignment);
17319   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17320                "k = 4, int l = 5,\n"
17321                "                  int m = 6) {\n"
17322                "  int j      = 10;\n"
17323                "  otherThing = 1;\n"
17324                "}",
17325                Alignment);
17326   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17327                "  int i   = 1;\n"
17328                "  int j   = 2;\n"
17329                "  int big = 10000;\n"
17330                "}",
17331                Alignment);
17332   verifyFormat("class C {\n"
17333                "public:\n"
17334                "  int i            = 1;\n"
17335                "  virtual void f() = 0;\n"
17336                "};",
17337                Alignment);
17338   verifyFormat("int i = 1;\n"
17339                "if (SomeType t = getSomething()) {\n"
17340                "}\n"
17341                "int j   = 2;\n"
17342                "int big = 10000;",
17343                Alignment);
17344   verifyFormat("int j = 7;\n"
17345                "for (int k = 0; k < N; ++k) {\n"
17346                "}\n"
17347                "int j   = 2;\n"
17348                "int big = 10000;\n"
17349                "}",
17350                Alignment);
17351   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17352   verifyFormat("int i = 1;\n"
17353                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17354                "    = someLooooooooooooooooongFunction();\n"
17355                "int j = 2;",
17356                Alignment);
17357   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17358   verifyFormat("int i = 1;\n"
17359                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17360                "    someLooooooooooooooooongFunction();\n"
17361                "int j = 2;",
17362                Alignment);
17363 
17364   verifyFormat("auto lambda = []() {\n"
17365                "  auto i = 0;\n"
17366                "  return 0;\n"
17367                "};\n"
17368                "int i  = 0;\n"
17369                "auto v = type{\n"
17370                "    i = 1,   //\n"
17371                "    (i = 2), //\n"
17372                "    i = 3    //\n"
17373                "};",
17374                Alignment);
17375 
17376   verifyFormat(
17377       "int i      = 1;\n"
17378       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17379       "                          loooooooooooooooooooooongParameterB);\n"
17380       "int j      = 2;",
17381       Alignment);
17382 
17383   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17384                "          typename B   = very_long_type_name_1,\n"
17385                "          typename T_2 = very_long_type_name_2>\n"
17386                "auto foo() {}\n",
17387                Alignment);
17388   verifyFormat("int a, b = 1;\n"
17389                "int c  = 2;\n"
17390                "int dd = 3;\n",
17391                Alignment);
17392   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17393                "float b[1][] = {{3.f}};\n",
17394                Alignment);
17395   verifyFormat("for (int i = 0; i < 1; i++)\n"
17396                "  int x = 1;\n",
17397                Alignment);
17398   verifyFormat("for (i = 0; i < 1; i++)\n"
17399                "  x = 1;\n"
17400                "y = 1;\n",
17401                Alignment);
17402 
17403   EXPECT_EQ(Alignment.ReflowComments, true);
17404   Alignment.ColumnLimit = 50;
17405   EXPECT_EQ("int x   = 0;\n"
17406             "int yy  = 1; /// specificlennospace\n"
17407             "int zzz = 2;\n",
17408             format("int x   = 0;\n"
17409                    "int yy  = 1; ///specificlennospace\n"
17410                    "int zzz = 2;\n",
17411                    Alignment));
17412 
17413   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17414                "auto b                     = [] {\n"
17415                "  f();\n"
17416                "  return;\n"
17417                "};",
17418                Alignment);
17419   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17420                "auto b                     = g([] {\n"
17421                "  f();\n"
17422                "  return;\n"
17423                "});",
17424                Alignment);
17425   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17426                "auto b                     = g(param, [] {\n"
17427                "  f();\n"
17428                "  return;\n"
17429                "});",
17430                Alignment);
17431   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17432                "auto b                     = [] {\n"
17433                "  if (condition) {\n"
17434                "    return;\n"
17435                "  }\n"
17436                "};",
17437                Alignment);
17438 
17439   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17440                "           ccc ? aaaaa : bbbbb,\n"
17441                "           dddddddddddddddddddddddddd);",
17442                Alignment);
17443   // FIXME: https://llvm.org/PR53497
17444   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
17445   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17446   //              "    ccc ? aaaaa : bbbbb,\n"
17447   //              "    dddddddddddddddddddddddddd);",
17448   //              Alignment);
17449 
17450   // Confirm proper handling of AlignConsecutiveAssignments with
17451   // BinPackArguments.
17452   // See https://llvm.org/PR55360
17453   Alignment = getLLVMStyleWithColumns(50);
17454   Alignment.AlignConsecutiveAssignments.Enabled = true;
17455   Alignment.BinPackArguments = false;
17456   verifyFormat("int a_long_name = 1;\n"
17457                "auto b          = B({a_long_name, a_long_name},\n"
17458                "                    {a_longer_name_for_wrap,\n"
17459                "                     a_longer_name_for_wrap});",
17460                Alignment);
17461   verifyFormat("int a_long_name = 1;\n"
17462                "auto b          = B{{a_long_name, a_long_name},\n"
17463                "                    {a_longer_name_for_wrap,\n"
17464                "                     a_longer_name_for_wrap}};",
17465                Alignment);
17466 }
17467 
17468 TEST_F(FormatTest, AlignConsecutiveBitFields) {
17469   FormatStyle Alignment = getLLVMStyle();
17470   Alignment.AlignConsecutiveBitFields.Enabled = true;
17471   verifyFormat("int const a     : 5;\n"
17472                "int oneTwoThree : 23;",
17473                Alignment);
17474 
17475   // Initializers are allowed starting with c++2a
17476   verifyFormat("int const a     : 5 = 1;\n"
17477                "int oneTwoThree : 23 = 0;",
17478                Alignment);
17479 
17480   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17481   verifyFormat("int const a           : 5;\n"
17482                "int       oneTwoThree : 23;",
17483                Alignment);
17484 
17485   verifyFormat("int const a           : 5;  // comment\n"
17486                "int       oneTwoThree : 23; // comment",
17487                Alignment);
17488 
17489   verifyFormat("int const a           : 5 = 1;\n"
17490                "int       oneTwoThree : 23 = 0;",
17491                Alignment);
17492 
17493   Alignment.AlignConsecutiveAssignments.Enabled = true;
17494   verifyFormat("int const a           : 5  = 1;\n"
17495                "int       oneTwoThree : 23 = 0;",
17496                Alignment);
17497   verifyFormat("int const a           : 5  = {1};\n"
17498                "int       oneTwoThree : 23 = 0;",
17499                Alignment);
17500 
17501   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
17502   verifyFormat("int const a          :5;\n"
17503                "int       oneTwoThree:23;",
17504                Alignment);
17505 
17506   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
17507   verifyFormat("int const a           :5;\n"
17508                "int       oneTwoThree :23;",
17509                Alignment);
17510 
17511   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
17512   verifyFormat("int const a          : 5;\n"
17513                "int       oneTwoThree: 23;",
17514                Alignment);
17515 
17516   // Known limitations: ':' is only recognized as a bitfield colon when
17517   // followed by a number.
17518   /*
17519   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
17520                "int a           : 5;",
17521                Alignment);
17522   */
17523 }
17524 
17525 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
17526   FormatStyle Alignment = getLLVMStyle();
17527   Alignment.AlignConsecutiveMacros.Enabled = true;
17528   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17529   verifyFormat("float const a = 5;\n"
17530                "int oneTwoThree = 123;",
17531                Alignment);
17532   verifyFormat("int a = 5;\n"
17533                "float const oneTwoThree = 123;",
17534                Alignment);
17535 
17536   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17537   verifyFormat("float const a = 5;\n"
17538                "int         oneTwoThree = 123;",
17539                Alignment);
17540   verifyFormat("int         a = method();\n"
17541                "float const oneTwoThree = 133;",
17542                Alignment);
17543   verifyFormat("int i = 1, j = 10;\n"
17544                "something = 2000;",
17545                Alignment);
17546   verifyFormat("something = 2000;\n"
17547                "int i = 1, j = 10;\n",
17548                Alignment);
17549   verifyFormat("float      something = 2000;\n"
17550                "double     another = 911;\n"
17551                "int        i = 1, j = 10;\n"
17552                "const int *oneMore = 1;\n"
17553                "unsigned   i = 2;",
17554                Alignment);
17555   verifyFormat("float a = 5;\n"
17556                "int   one = 1;\n"
17557                "method();\n"
17558                "const double       oneTwoThree = 123;\n"
17559                "const unsigned int oneTwo = 12;",
17560                Alignment);
17561   verifyFormat("int      oneTwoThree{0}; // comment\n"
17562                "unsigned oneTwo;         // comment",
17563                Alignment);
17564   verifyFormat("unsigned int       *a;\n"
17565                "int                *b;\n"
17566                "unsigned int Const *c;\n"
17567                "unsigned int const *d;\n"
17568                "unsigned int Const &e;\n"
17569                "unsigned int const &f;",
17570                Alignment);
17571   verifyFormat("Const unsigned int *c;\n"
17572                "const unsigned int *d;\n"
17573                "Const unsigned int &e;\n"
17574                "const unsigned int &f;\n"
17575                "const unsigned      g;\n"
17576                "Const unsigned      h;",
17577                Alignment);
17578   EXPECT_EQ("float const a = 5;\n"
17579             "\n"
17580             "int oneTwoThree = 123;",
17581             format("float const   a = 5;\n"
17582                    "\n"
17583                    "int           oneTwoThree= 123;",
17584                    Alignment));
17585   EXPECT_EQ("float a = 5;\n"
17586             "int   one = 1;\n"
17587             "\n"
17588             "unsigned oneTwoThree = 123;",
17589             format("float    a = 5;\n"
17590                    "int      one = 1;\n"
17591                    "\n"
17592                    "unsigned oneTwoThree = 123;",
17593                    Alignment));
17594   EXPECT_EQ("float a = 5;\n"
17595             "int   one = 1;\n"
17596             "\n"
17597             "unsigned oneTwoThree = 123;\n"
17598             "int      oneTwo = 12;",
17599             format("float    a = 5;\n"
17600                    "int one = 1;\n"
17601                    "\n"
17602                    "unsigned oneTwoThree = 123;\n"
17603                    "int oneTwo = 12;",
17604                    Alignment));
17605   // Function prototype alignment
17606   verifyFormat("int    a();\n"
17607                "double b();",
17608                Alignment);
17609   verifyFormat("int    a(int x);\n"
17610                "double b();",
17611                Alignment);
17612   unsigned OldColumnLimit = Alignment.ColumnLimit;
17613   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17614   // otherwise the function parameters will be re-flowed onto a single line.
17615   Alignment.ColumnLimit = 0;
17616   EXPECT_EQ("int    a(int   x,\n"
17617             "         float y);\n"
17618             "double b(int    x,\n"
17619             "         double y);",
17620             format("int a(int x,\n"
17621                    " float y);\n"
17622                    "double b(int x,\n"
17623                    " double y);",
17624                    Alignment));
17625   // This ensures that function parameters of function declarations are
17626   // correctly indented when their owning functions are indented.
17627   // The failure case here is for 'double y' to not be indented enough.
17628   EXPECT_EQ("double a(int x);\n"
17629             "int    b(int    y,\n"
17630             "         double z);",
17631             format("double a(int x);\n"
17632                    "int b(int y,\n"
17633                    " double z);",
17634                    Alignment));
17635   // Set ColumnLimit low so that we induce wrapping immediately after
17636   // the function name and opening paren.
17637   Alignment.ColumnLimit = 13;
17638   verifyFormat("int function(\n"
17639                "    int  x,\n"
17640                "    bool y);",
17641                Alignment);
17642   Alignment.ColumnLimit = OldColumnLimit;
17643   // Ensure function pointers don't screw up recursive alignment
17644   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17645                "double b();",
17646                Alignment);
17647   Alignment.AlignConsecutiveAssignments.Enabled = true;
17648   // Ensure recursive alignment is broken by function braces, so that the
17649   // "a = 1" does not align with subsequent assignments inside the function
17650   // body.
17651   verifyFormat("int func(int a = 1) {\n"
17652                "  int b  = 2;\n"
17653                "  int cc = 3;\n"
17654                "}",
17655                Alignment);
17656   verifyFormat("float      something = 2000;\n"
17657                "double     another   = 911;\n"
17658                "int        i = 1, j = 10;\n"
17659                "const int *oneMore = 1;\n"
17660                "unsigned   i       = 2;",
17661                Alignment);
17662   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17663                "unsigned oneTwo      = 0;   // comment",
17664                Alignment);
17665   // Make sure that scope is correctly tracked, in the absence of braces
17666   verifyFormat("for (int i = 0; i < n; i++)\n"
17667                "  j = i;\n"
17668                "double x = 1;\n",
17669                Alignment);
17670   verifyFormat("if (int i = 0)\n"
17671                "  j = i;\n"
17672                "double x = 1;\n",
17673                Alignment);
17674   // Ensure operator[] and operator() are comprehended
17675   verifyFormat("struct test {\n"
17676                "  long long int foo();\n"
17677                "  int           operator[](int a);\n"
17678                "  double        bar();\n"
17679                "};\n",
17680                Alignment);
17681   verifyFormat("struct test {\n"
17682                "  long long int foo();\n"
17683                "  int           operator()(int a);\n"
17684                "  double        bar();\n"
17685                "};\n",
17686                Alignment);
17687   // http://llvm.org/PR52914
17688   verifyFormat("char *a[]     = {\"a\", // comment\n"
17689                "                 \"bb\"};\n"
17690                "int   bbbbbbb = 0;",
17691                Alignment);
17692 
17693   // PAS_Right
17694   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17695             "  int const i   = 1;\n"
17696             "  int      *j   = 2;\n"
17697             "  int       big = 10000;\n"
17698             "\n"
17699             "  unsigned oneTwoThree = 123;\n"
17700             "  int      oneTwo      = 12;\n"
17701             "  method();\n"
17702             "  float k  = 2;\n"
17703             "  int   ll = 10000;\n"
17704             "}",
17705             format("void SomeFunction(int parameter= 0) {\n"
17706                    " int const  i= 1;\n"
17707                    "  int *j=2;\n"
17708                    " int big  =  10000;\n"
17709                    "\n"
17710                    "unsigned oneTwoThree  =123;\n"
17711                    "int oneTwo = 12;\n"
17712                    "  method();\n"
17713                    "float k= 2;\n"
17714                    "int ll=10000;\n"
17715                    "}",
17716                    Alignment));
17717   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17718             "  int const i   = 1;\n"
17719             "  int     **j   = 2, ***k;\n"
17720             "  int      &k   = i;\n"
17721             "  int     &&l   = i + j;\n"
17722             "  int       big = 10000;\n"
17723             "\n"
17724             "  unsigned oneTwoThree = 123;\n"
17725             "  int      oneTwo      = 12;\n"
17726             "  method();\n"
17727             "  float k  = 2;\n"
17728             "  int   ll = 10000;\n"
17729             "}",
17730             format("void SomeFunction(int parameter= 0) {\n"
17731                    " int const  i= 1;\n"
17732                    "  int **j=2,***k;\n"
17733                    "int &k=i;\n"
17734                    "int &&l=i+j;\n"
17735                    " int big  =  10000;\n"
17736                    "\n"
17737                    "unsigned oneTwoThree  =123;\n"
17738                    "int oneTwo = 12;\n"
17739                    "  method();\n"
17740                    "float k= 2;\n"
17741                    "int ll=10000;\n"
17742                    "}",
17743                    Alignment));
17744   // variables are aligned at their name, pointers are at the right most
17745   // position
17746   verifyFormat("int   *a;\n"
17747                "int  **b;\n"
17748                "int ***c;\n"
17749                "int    foobar;\n",
17750                Alignment);
17751 
17752   // PAS_Left
17753   FormatStyle AlignmentLeft = Alignment;
17754   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17755   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17756             "  int const i   = 1;\n"
17757             "  int*      j   = 2;\n"
17758             "  int       big = 10000;\n"
17759             "\n"
17760             "  unsigned oneTwoThree = 123;\n"
17761             "  int      oneTwo      = 12;\n"
17762             "  method();\n"
17763             "  float k  = 2;\n"
17764             "  int   ll = 10000;\n"
17765             "}",
17766             format("void SomeFunction(int parameter= 0) {\n"
17767                    " int const  i= 1;\n"
17768                    "  int *j=2;\n"
17769                    " int big  =  10000;\n"
17770                    "\n"
17771                    "unsigned oneTwoThree  =123;\n"
17772                    "int oneTwo = 12;\n"
17773                    "  method();\n"
17774                    "float k= 2;\n"
17775                    "int ll=10000;\n"
17776                    "}",
17777                    AlignmentLeft));
17778   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17779             "  int const i   = 1;\n"
17780             "  int**     j   = 2;\n"
17781             "  int&      k   = i;\n"
17782             "  int&&     l   = i + j;\n"
17783             "  int       big = 10000;\n"
17784             "\n"
17785             "  unsigned oneTwoThree = 123;\n"
17786             "  int      oneTwo      = 12;\n"
17787             "  method();\n"
17788             "  float k  = 2;\n"
17789             "  int   ll = 10000;\n"
17790             "}",
17791             format("void SomeFunction(int parameter= 0) {\n"
17792                    " int const  i= 1;\n"
17793                    "  int **j=2;\n"
17794                    "int &k=i;\n"
17795                    "int &&l=i+j;\n"
17796                    " int big  =  10000;\n"
17797                    "\n"
17798                    "unsigned oneTwoThree  =123;\n"
17799                    "int oneTwo = 12;\n"
17800                    "  method();\n"
17801                    "float k= 2;\n"
17802                    "int ll=10000;\n"
17803                    "}",
17804                    AlignmentLeft));
17805   // variables are aligned at their name, pointers are at the left most position
17806   verifyFormat("int*   a;\n"
17807                "int**  b;\n"
17808                "int*** c;\n"
17809                "int    foobar;\n",
17810                AlignmentLeft);
17811 
17812   // PAS_Middle
17813   FormatStyle AlignmentMiddle = Alignment;
17814   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17815   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17816             "  int const i   = 1;\n"
17817             "  int *     j   = 2;\n"
17818             "  int       big = 10000;\n"
17819             "\n"
17820             "  unsigned oneTwoThree = 123;\n"
17821             "  int      oneTwo      = 12;\n"
17822             "  method();\n"
17823             "  float k  = 2;\n"
17824             "  int   ll = 10000;\n"
17825             "}",
17826             format("void SomeFunction(int parameter= 0) {\n"
17827                    " int const  i= 1;\n"
17828                    "  int *j=2;\n"
17829                    " int big  =  10000;\n"
17830                    "\n"
17831                    "unsigned oneTwoThree  =123;\n"
17832                    "int oneTwo = 12;\n"
17833                    "  method();\n"
17834                    "float k= 2;\n"
17835                    "int ll=10000;\n"
17836                    "}",
17837                    AlignmentMiddle));
17838   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17839             "  int const i   = 1;\n"
17840             "  int **    j   = 2, ***k;\n"
17841             "  int &     k   = i;\n"
17842             "  int &&    l   = i + j;\n"
17843             "  int       big = 10000;\n"
17844             "\n"
17845             "  unsigned oneTwoThree = 123;\n"
17846             "  int      oneTwo      = 12;\n"
17847             "  method();\n"
17848             "  float k  = 2;\n"
17849             "  int   ll = 10000;\n"
17850             "}",
17851             format("void SomeFunction(int parameter= 0) {\n"
17852                    " int const  i= 1;\n"
17853                    "  int **j=2,***k;\n"
17854                    "int &k=i;\n"
17855                    "int &&l=i+j;\n"
17856                    " int big  =  10000;\n"
17857                    "\n"
17858                    "unsigned oneTwoThree  =123;\n"
17859                    "int oneTwo = 12;\n"
17860                    "  method();\n"
17861                    "float k= 2;\n"
17862                    "int ll=10000;\n"
17863                    "}",
17864                    AlignmentMiddle));
17865   // variables are aligned at their name, pointers are in the middle
17866   verifyFormat("int *   a;\n"
17867                "int *   b;\n"
17868                "int *** c;\n"
17869                "int     foobar;\n",
17870                AlignmentMiddle);
17871 
17872   Alignment.AlignConsecutiveAssignments.Enabled = false;
17873   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17874   verifyFormat("#define A \\\n"
17875                "  int       aaaa = 12; \\\n"
17876                "  float     b = 23; \\\n"
17877                "  const int ccc = 234; \\\n"
17878                "  unsigned  dddddddddd = 2345;",
17879                Alignment);
17880   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17881   verifyFormat("#define A              \\\n"
17882                "  int       aaaa = 12; \\\n"
17883                "  float     b = 23;    \\\n"
17884                "  const int ccc = 234; \\\n"
17885                "  unsigned  dddddddddd = 2345;",
17886                Alignment);
17887   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17888   Alignment.ColumnLimit = 30;
17889   verifyFormat("#define A                    \\\n"
17890                "  int       aaaa = 12;       \\\n"
17891                "  float     b = 23;          \\\n"
17892                "  const int ccc = 234;       \\\n"
17893                "  int       dddddddddd = 2345;",
17894                Alignment);
17895   Alignment.ColumnLimit = 80;
17896   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17897                "k = 4, int l = 5,\n"
17898                "                  int m = 6) {\n"
17899                "  const int j = 10;\n"
17900                "  otherThing = 1;\n"
17901                "}",
17902                Alignment);
17903   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17904                "  int const i = 1;\n"
17905                "  int      *j = 2;\n"
17906                "  int       big = 10000;\n"
17907                "}",
17908                Alignment);
17909   verifyFormat("class C {\n"
17910                "public:\n"
17911                "  int          i = 1;\n"
17912                "  virtual void f() = 0;\n"
17913                "};",
17914                Alignment);
17915   verifyFormat("float i = 1;\n"
17916                "if (SomeType t = getSomething()) {\n"
17917                "}\n"
17918                "const unsigned j = 2;\n"
17919                "int            big = 10000;",
17920                Alignment);
17921   verifyFormat("float j = 7;\n"
17922                "for (int k = 0; k < N; ++k) {\n"
17923                "}\n"
17924                "unsigned j = 2;\n"
17925                "int      big = 10000;\n"
17926                "}",
17927                Alignment);
17928   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17929   verifyFormat("float              i = 1;\n"
17930                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17931                "    = someLooooooooooooooooongFunction();\n"
17932                "int j = 2;",
17933                Alignment);
17934   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17935   verifyFormat("int                i = 1;\n"
17936                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17937                "    someLooooooooooooooooongFunction();\n"
17938                "int j = 2;",
17939                Alignment);
17940 
17941   Alignment.AlignConsecutiveAssignments.Enabled = true;
17942   verifyFormat("auto lambda = []() {\n"
17943                "  auto  ii = 0;\n"
17944                "  float j  = 0;\n"
17945                "  return 0;\n"
17946                "};\n"
17947                "int   i  = 0;\n"
17948                "float i2 = 0;\n"
17949                "auto  v  = type{\n"
17950                "    i = 1,   //\n"
17951                "    (i = 2), //\n"
17952                "    i = 3    //\n"
17953                "};",
17954                Alignment);
17955   Alignment.AlignConsecutiveAssignments.Enabled = false;
17956 
17957   verifyFormat(
17958       "int      i = 1;\n"
17959       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17960       "                          loooooooooooooooooooooongParameterB);\n"
17961       "int      j = 2;",
17962       Alignment);
17963 
17964   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17965   // We expect declarations and assignments to align, as long as it doesn't
17966   // exceed the column limit, starting a new alignment sequence whenever it
17967   // happens.
17968   Alignment.AlignConsecutiveAssignments.Enabled = true;
17969   Alignment.ColumnLimit = 30;
17970   verifyFormat("float    ii              = 1;\n"
17971                "unsigned j               = 2;\n"
17972                "int someVerylongVariable = 1;\n"
17973                "AnotherLongType  ll = 123456;\n"
17974                "VeryVeryLongType k  = 2;\n"
17975                "int              myvar = 1;",
17976                Alignment);
17977   Alignment.ColumnLimit = 80;
17978   Alignment.AlignConsecutiveAssignments.Enabled = false;
17979 
17980   verifyFormat(
17981       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17982       "          typename LongType, typename B>\n"
17983       "auto foo() {}\n",
17984       Alignment);
17985   verifyFormat("float a, b = 1;\n"
17986                "int   c = 2;\n"
17987                "int   dd = 3;\n",
17988                Alignment);
17989   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17990                "float b[1][] = {{3.f}};\n",
17991                Alignment);
17992   Alignment.AlignConsecutiveAssignments.Enabled = true;
17993   verifyFormat("float a, b = 1;\n"
17994                "int   c  = 2;\n"
17995                "int   dd = 3;\n",
17996                Alignment);
17997   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17998                "float b[1][] = {{3.f}};\n",
17999                Alignment);
18000   Alignment.AlignConsecutiveAssignments.Enabled = false;
18001 
18002   Alignment.ColumnLimit = 30;
18003   Alignment.BinPackParameters = false;
18004   verifyFormat("void foo(float     a,\n"
18005                "         float     b,\n"
18006                "         int       c,\n"
18007                "         uint32_t *d) {\n"
18008                "  int   *e = 0;\n"
18009                "  float  f = 0;\n"
18010                "  double g = 0;\n"
18011                "}\n"
18012                "void bar(ino_t     a,\n"
18013                "         int       b,\n"
18014                "         uint32_t *c,\n"
18015                "         bool      d) {}\n",
18016                Alignment);
18017   Alignment.BinPackParameters = true;
18018   Alignment.ColumnLimit = 80;
18019 
18020   // Bug 33507
18021   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
18022   verifyFormat(
18023       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
18024       "  static const Version verVs2017;\n"
18025       "  return true;\n"
18026       "});\n",
18027       Alignment);
18028   Alignment.PointerAlignment = FormatStyle::PAS_Right;
18029 
18030   // See llvm.org/PR35641
18031   Alignment.AlignConsecutiveDeclarations.Enabled = true;
18032   verifyFormat("int func() { //\n"
18033                "  int      b;\n"
18034                "  unsigned c;\n"
18035                "}",
18036                Alignment);
18037 
18038   // See PR37175
18039   FormatStyle Style = getMozillaStyle();
18040   Style.AlignConsecutiveDeclarations.Enabled = true;
18041   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
18042             "foo(int a);",
18043             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
18044 
18045   Alignment.PointerAlignment = FormatStyle::PAS_Left;
18046   verifyFormat("unsigned int*       a;\n"
18047                "int*                b;\n"
18048                "unsigned int Const* c;\n"
18049                "unsigned int const* d;\n"
18050                "unsigned int Const& e;\n"
18051                "unsigned int const& f;",
18052                Alignment);
18053   verifyFormat("Const unsigned int* c;\n"
18054                "const unsigned int* d;\n"
18055                "Const unsigned int& e;\n"
18056                "const unsigned int& f;\n"
18057                "const unsigned      g;\n"
18058                "Const unsigned      h;",
18059                Alignment);
18060 
18061   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
18062   verifyFormat("unsigned int *       a;\n"
18063                "int *                b;\n"
18064                "unsigned int Const * c;\n"
18065                "unsigned int const * d;\n"
18066                "unsigned int Const & e;\n"
18067                "unsigned int const & f;",
18068                Alignment);
18069   verifyFormat("Const unsigned int * c;\n"
18070                "const unsigned int * d;\n"
18071                "Const unsigned int & e;\n"
18072                "const unsigned int & f;\n"
18073                "const unsigned       g;\n"
18074                "Const unsigned       h;",
18075                Alignment);
18076 
18077   // See PR46529
18078   FormatStyle BracedAlign = getLLVMStyle();
18079   BracedAlign.AlignConsecutiveDeclarations.Enabled = true;
18080   verifyFormat("const auto result{[]() {\n"
18081                "  const auto something = 1;\n"
18082                "  return 2;\n"
18083                "}};",
18084                BracedAlign);
18085   verifyFormat("int foo{[]() {\n"
18086                "  int bar{0};\n"
18087                "  return 0;\n"
18088                "}()};",
18089                BracedAlign);
18090   BracedAlign.Cpp11BracedListStyle = false;
18091   verifyFormat("const auto result{ []() {\n"
18092                "  const auto something = 1;\n"
18093                "  return 2;\n"
18094                "} };",
18095                BracedAlign);
18096   verifyFormat("int foo{ []() {\n"
18097                "  int bar{ 0 };\n"
18098                "  return 0;\n"
18099                "}() };",
18100                BracedAlign);
18101 }
18102 
18103 TEST_F(FormatTest, AlignWithLineBreaks) {
18104   auto Style = getLLVMStyleWithColumns(120);
18105 
18106   EXPECT_EQ(Style.AlignConsecutiveAssignments,
18107             FormatStyle::AlignConsecutiveStyle(
18108                 {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
18109                  /*AcrossComments=*/false, /*AlignCompound=*/false,
18110                  /*PadOperators=*/true}));
18111   EXPECT_EQ(Style.AlignConsecutiveDeclarations,
18112             FormatStyle::AlignConsecutiveStyle({}));
18113   verifyFormat("void foo() {\n"
18114                "  int myVar = 5;\n"
18115                "  double x = 3.14;\n"
18116                "  auto str = \"Hello \"\n"
18117                "             \"World\";\n"
18118                "  auto s = \"Hello \"\n"
18119                "           \"Again\";\n"
18120                "}",
18121                Style);
18122 
18123   // clang-format off
18124   verifyFormat("void foo() {\n"
18125                "  const int capacityBefore = Entries.capacity();\n"
18126                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18127                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18128                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18129                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18130                "}",
18131                Style);
18132   // clang-format on
18133 
18134   Style.AlignConsecutiveAssignments.Enabled = true;
18135   verifyFormat("void foo() {\n"
18136                "  int myVar = 5;\n"
18137                "  double x  = 3.14;\n"
18138                "  auto str  = \"Hello \"\n"
18139                "              \"World\";\n"
18140                "  auto s    = \"Hello \"\n"
18141                "              \"Again\";\n"
18142                "}",
18143                Style);
18144 
18145   // clang-format off
18146   verifyFormat("void foo() {\n"
18147                "  const int capacityBefore = Entries.capacity();\n"
18148                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18149                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18150                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18151                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18152                "}",
18153                Style);
18154   // clang-format on
18155 
18156   Style.AlignConsecutiveAssignments.Enabled = false;
18157   Style.AlignConsecutiveDeclarations.Enabled = true;
18158   verifyFormat("void foo() {\n"
18159                "  int    myVar = 5;\n"
18160                "  double x = 3.14;\n"
18161                "  auto   str = \"Hello \"\n"
18162                "               \"World\";\n"
18163                "  auto   s = \"Hello \"\n"
18164                "             \"Again\";\n"
18165                "}",
18166                Style);
18167 
18168   // clang-format off
18169   verifyFormat("void foo() {\n"
18170                "  const int  capacityBefore = Entries.capacity();\n"
18171                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18172                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18173                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18174                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18175                "}",
18176                Style);
18177   // clang-format on
18178 
18179   Style.AlignConsecutiveAssignments.Enabled = true;
18180   Style.AlignConsecutiveDeclarations.Enabled = true;
18181 
18182   verifyFormat("void foo() {\n"
18183                "  int    myVar = 5;\n"
18184                "  double x     = 3.14;\n"
18185                "  auto   str   = \"Hello \"\n"
18186                "                 \"World\";\n"
18187                "  auto   s     = \"Hello \"\n"
18188                "                 \"Again\";\n"
18189                "}",
18190                Style);
18191 
18192   // clang-format off
18193   verifyFormat("void foo() {\n"
18194                "  const int  capacityBefore = Entries.capacity();\n"
18195                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18196                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18197                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18198                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18199                "}",
18200                Style);
18201   // clang-format on
18202 
18203   Style = getLLVMStyleWithColumns(20);
18204   Style.AlignConsecutiveAssignments.Enabled = true;
18205   Style.IndentWidth = 4;
18206 
18207   verifyFormat("void foo() {\n"
18208                "    int i1 = 1;\n"
18209                "    int j  = 0;\n"
18210                "    int k  = bar(\n"
18211                "        argument1,\n"
18212                "        argument2);\n"
18213                "}",
18214                Style);
18215 
18216   verifyFormat("unsigned i = 0;\n"
18217                "int a[]    = {\n"
18218                "    1234567890,\n"
18219                "    -1234567890};",
18220                Style);
18221 
18222   Style.ColumnLimit = 120;
18223 
18224   // clang-format off
18225   verifyFormat("void SomeFunc() {\n"
18226                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18227                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18228                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18229                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18230                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18231                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18232                "}",
18233                Style);
18234   // clang-format on
18235 
18236   Style.BinPackArguments = false;
18237 
18238   // clang-format off
18239   verifyFormat("void SomeFunc() {\n"
18240                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
18241                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18242                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
18243                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18244                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
18245                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18246                "}",
18247                Style);
18248   // clang-format on
18249 }
18250 
18251 TEST_F(FormatTest, AlignWithInitializerPeriods) {
18252   auto Style = getLLVMStyleWithColumns(60);
18253 
18254   verifyFormat("void foo1(void) {\n"
18255                "  BYTE p[1] = 1;\n"
18256                "  A B = {.one_foooooooooooooooo = 2,\n"
18257                "         .two_fooooooooooooo = 3,\n"
18258                "         .three_fooooooooooooo = 4};\n"
18259                "  BYTE payload = 2;\n"
18260                "}",
18261                Style);
18262 
18263   Style.AlignConsecutiveAssignments.Enabled = true;
18264   Style.AlignConsecutiveDeclarations.Enabled = false;
18265   verifyFormat("void foo2(void) {\n"
18266                "  BYTE p[1]    = 1;\n"
18267                "  A B          = {.one_foooooooooooooooo = 2,\n"
18268                "                  .two_fooooooooooooo    = 3,\n"
18269                "                  .three_fooooooooooooo  = 4};\n"
18270                "  BYTE payload = 2;\n"
18271                "}",
18272                Style);
18273 
18274   Style.AlignConsecutiveAssignments.Enabled = false;
18275   Style.AlignConsecutiveDeclarations.Enabled = true;
18276   verifyFormat("void foo3(void) {\n"
18277                "  BYTE p[1] = 1;\n"
18278                "  A    B = {.one_foooooooooooooooo = 2,\n"
18279                "            .two_fooooooooooooo = 3,\n"
18280                "            .three_fooooooooooooo = 4};\n"
18281                "  BYTE payload = 2;\n"
18282                "}",
18283                Style);
18284 
18285   Style.AlignConsecutiveAssignments.Enabled = true;
18286   Style.AlignConsecutiveDeclarations.Enabled = true;
18287   verifyFormat("void foo4(void) {\n"
18288                "  BYTE p[1]    = 1;\n"
18289                "  A    B       = {.one_foooooooooooooooo = 2,\n"
18290                "                  .two_fooooooooooooo    = 3,\n"
18291                "                  .three_fooooooooooooo  = 4};\n"
18292                "  BYTE payload = 2;\n"
18293                "}",
18294                Style);
18295 }
18296 
18297 TEST_F(FormatTest, LinuxBraceBreaking) {
18298   FormatStyle LinuxBraceStyle = getLLVMStyle();
18299   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
18300   verifyFormat("namespace a\n"
18301                "{\n"
18302                "class A\n"
18303                "{\n"
18304                "  void f()\n"
18305                "  {\n"
18306                "    if (true) {\n"
18307                "      a();\n"
18308                "      b();\n"
18309                "    } else {\n"
18310                "      a();\n"
18311                "    }\n"
18312                "  }\n"
18313                "  void g() { return; }\n"
18314                "};\n"
18315                "struct B {\n"
18316                "  int x;\n"
18317                "};\n"
18318                "} // namespace a\n",
18319                LinuxBraceStyle);
18320   verifyFormat("enum X {\n"
18321                "  Y = 0,\n"
18322                "}\n",
18323                LinuxBraceStyle);
18324   verifyFormat("struct S {\n"
18325                "  int Type;\n"
18326                "  union {\n"
18327                "    int x;\n"
18328                "    double y;\n"
18329                "  } Value;\n"
18330                "  class C\n"
18331                "  {\n"
18332                "    MyFavoriteType Value;\n"
18333                "  } Class;\n"
18334                "}\n",
18335                LinuxBraceStyle);
18336 }
18337 
18338 TEST_F(FormatTest, MozillaBraceBreaking) {
18339   FormatStyle MozillaBraceStyle = getLLVMStyle();
18340   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
18341   MozillaBraceStyle.FixNamespaceComments = false;
18342   verifyFormat("namespace a {\n"
18343                "class A\n"
18344                "{\n"
18345                "  void f()\n"
18346                "  {\n"
18347                "    if (true) {\n"
18348                "      a();\n"
18349                "      b();\n"
18350                "    }\n"
18351                "  }\n"
18352                "  void g() { return; }\n"
18353                "};\n"
18354                "enum E\n"
18355                "{\n"
18356                "  A,\n"
18357                "  // foo\n"
18358                "  B,\n"
18359                "  C\n"
18360                "};\n"
18361                "struct B\n"
18362                "{\n"
18363                "  int x;\n"
18364                "};\n"
18365                "}\n",
18366                MozillaBraceStyle);
18367   verifyFormat("struct S\n"
18368                "{\n"
18369                "  int Type;\n"
18370                "  union\n"
18371                "  {\n"
18372                "    int x;\n"
18373                "    double y;\n"
18374                "  } Value;\n"
18375                "  class C\n"
18376                "  {\n"
18377                "    MyFavoriteType Value;\n"
18378                "  } Class;\n"
18379                "}\n",
18380                MozillaBraceStyle);
18381 }
18382 
18383 TEST_F(FormatTest, StroustrupBraceBreaking) {
18384   FormatStyle StroustrupBraceStyle = getLLVMStyle();
18385   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18386   verifyFormat("namespace a {\n"
18387                "class A {\n"
18388                "  void f()\n"
18389                "  {\n"
18390                "    if (true) {\n"
18391                "      a();\n"
18392                "      b();\n"
18393                "    }\n"
18394                "  }\n"
18395                "  void g() { return; }\n"
18396                "};\n"
18397                "struct B {\n"
18398                "  int x;\n"
18399                "};\n"
18400                "} // namespace a\n",
18401                StroustrupBraceStyle);
18402 
18403   verifyFormat("void foo()\n"
18404                "{\n"
18405                "  if (a) {\n"
18406                "    a();\n"
18407                "  }\n"
18408                "  else {\n"
18409                "    b();\n"
18410                "  }\n"
18411                "}\n",
18412                StroustrupBraceStyle);
18413 
18414   verifyFormat("#ifdef _DEBUG\n"
18415                "int foo(int i = 0)\n"
18416                "#else\n"
18417                "int foo(int i = 5)\n"
18418                "#endif\n"
18419                "{\n"
18420                "  return i;\n"
18421                "}",
18422                StroustrupBraceStyle);
18423 
18424   verifyFormat("void foo() {}\n"
18425                "void bar()\n"
18426                "#ifdef _DEBUG\n"
18427                "{\n"
18428                "  foo();\n"
18429                "}\n"
18430                "#else\n"
18431                "{\n"
18432                "}\n"
18433                "#endif",
18434                StroustrupBraceStyle);
18435 
18436   verifyFormat("void foobar() { int i = 5; }\n"
18437                "#ifdef _DEBUG\n"
18438                "void bar() {}\n"
18439                "#else\n"
18440                "void bar() { foobar(); }\n"
18441                "#endif",
18442                StroustrupBraceStyle);
18443 }
18444 
18445 TEST_F(FormatTest, AllmanBraceBreaking) {
18446   FormatStyle AllmanBraceStyle = getLLVMStyle();
18447   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
18448 
18449   EXPECT_EQ("namespace a\n"
18450             "{\n"
18451             "void f();\n"
18452             "void g();\n"
18453             "} // namespace a\n",
18454             format("namespace a\n"
18455                    "{\n"
18456                    "void f();\n"
18457                    "void g();\n"
18458                    "}\n",
18459                    AllmanBraceStyle));
18460 
18461   verifyFormat("namespace a\n"
18462                "{\n"
18463                "class A\n"
18464                "{\n"
18465                "  void f()\n"
18466                "  {\n"
18467                "    if (true)\n"
18468                "    {\n"
18469                "      a();\n"
18470                "      b();\n"
18471                "    }\n"
18472                "  }\n"
18473                "  void g() { return; }\n"
18474                "};\n"
18475                "struct B\n"
18476                "{\n"
18477                "  int x;\n"
18478                "};\n"
18479                "union C\n"
18480                "{\n"
18481                "};\n"
18482                "} // namespace a",
18483                AllmanBraceStyle);
18484 
18485   verifyFormat("void f()\n"
18486                "{\n"
18487                "  if (true)\n"
18488                "  {\n"
18489                "    a();\n"
18490                "  }\n"
18491                "  else if (false)\n"
18492                "  {\n"
18493                "    b();\n"
18494                "  }\n"
18495                "  else\n"
18496                "  {\n"
18497                "    c();\n"
18498                "  }\n"
18499                "}\n",
18500                AllmanBraceStyle);
18501 
18502   verifyFormat("void f()\n"
18503                "{\n"
18504                "  for (int i = 0; i < 10; ++i)\n"
18505                "  {\n"
18506                "    a();\n"
18507                "  }\n"
18508                "  while (false)\n"
18509                "  {\n"
18510                "    b();\n"
18511                "  }\n"
18512                "  do\n"
18513                "  {\n"
18514                "    c();\n"
18515                "  } while (false)\n"
18516                "}\n",
18517                AllmanBraceStyle);
18518 
18519   verifyFormat("void f(int a)\n"
18520                "{\n"
18521                "  switch (a)\n"
18522                "  {\n"
18523                "  case 0:\n"
18524                "    break;\n"
18525                "  case 1:\n"
18526                "  {\n"
18527                "    break;\n"
18528                "  }\n"
18529                "  case 2:\n"
18530                "  {\n"
18531                "  }\n"
18532                "  break;\n"
18533                "  default:\n"
18534                "    break;\n"
18535                "  }\n"
18536                "}\n",
18537                AllmanBraceStyle);
18538 
18539   verifyFormat("enum X\n"
18540                "{\n"
18541                "  Y = 0,\n"
18542                "}\n",
18543                AllmanBraceStyle);
18544   verifyFormat("enum X\n"
18545                "{\n"
18546                "  Y = 0\n"
18547                "}\n",
18548                AllmanBraceStyle);
18549 
18550   verifyFormat("@interface BSApplicationController ()\n"
18551                "{\n"
18552                "@private\n"
18553                "  id _extraIvar;\n"
18554                "}\n"
18555                "@end\n",
18556                AllmanBraceStyle);
18557 
18558   verifyFormat("#ifdef _DEBUG\n"
18559                "int foo(int i = 0)\n"
18560                "#else\n"
18561                "int foo(int i = 5)\n"
18562                "#endif\n"
18563                "{\n"
18564                "  return i;\n"
18565                "}",
18566                AllmanBraceStyle);
18567 
18568   verifyFormat("void foo() {}\n"
18569                "void bar()\n"
18570                "#ifdef _DEBUG\n"
18571                "{\n"
18572                "  foo();\n"
18573                "}\n"
18574                "#else\n"
18575                "{\n"
18576                "}\n"
18577                "#endif",
18578                AllmanBraceStyle);
18579 
18580   verifyFormat("void foobar() { int i = 5; }\n"
18581                "#ifdef _DEBUG\n"
18582                "void bar() {}\n"
18583                "#else\n"
18584                "void bar() { foobar(); }\n"
18585                "#endif",
18586                AllmanBraceStyle);
18587 
18588   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18589             FormatStyle::SLS_All);
18590 
18591   verifyFormat("[](int i) { return i + 2; };\n"
18592                "[](int i, int j)\n"
18593                "{\n"
18594                "  auto x = i + j;\n"
18595                "  auto y = i * j;\n"
18596                "  return x ^ y;\n"
18597                "};\n"
18598                "void foo()\n"
18599                "{\n"
18600                "  auto shortLambda = [](int i) { return i + 2; };\n"
18601                "  auto longLambda = [](int i, int j)\n"
18602                "  {\n"
18603                "    auto x = i + j;\n"
18604                "    auto y = i * j;\n"
18605                "    return x ^ y;\n"
18606                "  };\n"
18607                "}",
18608                AllmanBraceStyle);
18609 
18610   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18611 
18612   verifyFormat("[](int i)\n"
18613                "{\n"
18614                "  return i + 2;\n"
18615                "};\n"
18616                "[](int i, int j)\n"
18617                "{\n"
18618                "  auto x = i + j;\n"
18619                "  auto y = i * j;\n"
18620                "  return x ^ y;\n"
18621                "};\n"
18622                "void foo()\n"
18623                "{\n"
18624                "  auto shortLambda = [](int i)\n"
18625                "  {\n"
18626                "    return i + 2;\n"
18627                "  };\n"
18628                "  auto longLambda = [](int i, int j)\n"
18629                "  {\n"
18630                "    auto x = i + j;\n"
18631                "    auto y = i * j;\n"
18632                "    return x ^ y;\n"
18633                "  };\n"
18634                "}",
18635                AllmanBraceStyle);
18636 
18637   // Reset
18638   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18639 
18640   // This shouldn't affect ObjC blocks..
18641   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18642                "  // ...\n"
18643                "  int i;\n"
18644                "}];",
18645                AllmanBraceStyle);
18646   verifyFormat("void (^block)(void) = ^{\n"
18647                "  // ...\n"
18648                "  int i;\n"
18649                "};",
18650                AllmanBraceStyle);
18651   // .. or dict literals.
18652   verifyFormat("void f()\n"
18653                "{\n"
18654                "  // ...\n"
18655                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18656                "}",
18657                AllmanBraceStyle);
18658   verifyFormat("void f()\n"
18659                "{\n"
18660                "  // ...\n"
18661                "  [object someMethod:@{a : @\"b\"}];\n"
18662                "}",
18663                AllmanBraceStyle);
18664   verifyFormat("int f()\n"
18665                "{ // comment\n"
18666                "  return 42;\n"
18667                "}",
18668                AllmanBraceStyle);
18669 
18670   AllmanBraceStyle.ColumnLimit = 19;
18671   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18672   AllmanBraceStyle.ColumnLimit = 18;
18673   verifyFormat("void f()\n"
18674                "{\n"
18675                "  int i;\n"
18676                "}",
18677                AllmanBraceStyle);
18678   AllmanBraceStyle.ColumnLimit = 80;
18679 
18680   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18681   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18682       FormatStyle::SIS_WithoutElse;
18683   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18684   verifyFormat("void f(bool b)\n"
18685                "{\n"
18686                "  if (b)\n"
18687                "  {\n"
18688                "    return;\n"
18689                "  }\n"
18690                "}\n",
18691                BreakBeforeBraceShortIfs);
18692   verifyFormat("void f(bool b)\n"
18693                "{\n"
18694                "  if constexpr (b)\n"
18695                "  {\n"
18696                "    return;\n"
18697                "  }\n"
18698                "}\n",
18699                BreakBeforeBraceShortIfs);
18700   verifyFormat("void f(bool b)\n"
18701                "{\n"
18702                "  if CONSTEXPR (b)\n"
18703                "  {\n"
18704                "    return;\n"
18705                "  }\n"
18706                "}\n",
18707                BreakBeforeBraceShortIfs);
18708   verifyFormat("void f(bool b)\n"
18709                "{\n"
18710                "  if (b) return;\n"
18711                "}\n",
18712                BreakBeforeBraceShortIfs);
18713   verifyFormat("void f(bool b)\n"
18714                "{\n"
18715                "  if constexpr (b) return;\n"
18716                "}\n",
18717                BreakBeforeBraceShortIfs);
18718   verifyFormat("void f(bool b)\n"
18719                "{\n"
18720                "  if CONSTEXPR (b) return;\n"
18721                "}\n",
18722                BreakBeforeBraceShortIfs);
18723   verifyFormat("void f(bool b)\n"
18724                "{\n"
18725                "  while (b)\n"
18726                "  {\n"
18727                "    return;\n"
18728                "  }\n"
18729                "}\n",
18730                BreakBeforeBraceShortIfs);
18731 }
18732 
18733 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18734   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18735   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18736 
18737   // Make a few changes to the style for testing purposes
18738   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18739       FormatStyle::SFS_Empty;
18740   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18741 
18742   // FIXME: this test case can't decide whether there should be a blank line
18743   // after the ~D() line or not. It adds one if one doesn't exist in the test
18744   // and it removes the line if one exists.
18745   /*
18746   verifyFormat("class A;\n"
18747                "namespace B\n"
18748                "  {\n"
18749                "class C;\n"
18750                "// Comment\n"
18751                "class D\n"
18752                "  {\n"
18753                "public:\n"
18754                "  D();\n"
18755                "  ~D() {}\n"
18756                "private:\n"
18757                "  enum E\n"
18758                "    {\n"
18759                "    F\n"
18760                "    }\n"
18761                "  };\n"
18762                "  } // namespace B\n",
18763                WhitesmithsBraceStyle);
18764   */
18765 
18766   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18767   verifyFormat("namespace a\n"
18768                "  {\n"
18769                "class A\n"
18770                "  {\n"
18771                "  void f()\n"
18772                "    {\n"
18773                "    if (true)\n"
18774                "      {\n"
18775                "      a();\n"
18776                "      b();\n"
18777                "      }\n"
18778                "    }\n"
18779                "  void g()\n"
18780                "    {\n"
18781                "    return;\n"
18782                "    }\n"
18783                "  };\n"
18784                "struct B\n"
18785                "  {\n"
18786                "  int x;\n"
18787                "  };\n"
18788                "  } // namespace a",
18789                WhitesmithsBraceStyle);
18790 
18791   verifyFormat("namespace a\n"
18792                "  {\n"
18793                "namespace b\n"
18794                "  {\n"
18795                "class A\n"
18796                "  {\n"
18797                "  void f()\n"
18798                "    {\n"
18799                "    if (true)\n"
18800                "      {\n"
18801                "      a();\n"
18802                "      b();\n"
18803                "      }\n"
18804                "    }\n"
18805                "  void g()\n"
18806                "    {\n"
18807                "    return;\n"
18808                "    }\n"
18809                "  };\n"
18810                "struct B\n"
18811                "  {\n"
18812                "  int x;\n"
18813                "  };\n"
18814                "  } // namespace b\n"
18815                "  } // namespace a",
18816                WhitesmithsBraceStyle);
18817 
18818   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18819   verifyFormat("namespace a\n"
18820                "  {\n"
18821                "namespace b\n"
18822                "  {\n"
18823                "  class A\n"
18824                "    {\n"
18825                "    void f()\n"
18826                "      {\n"
18827                "      if (true)\n"
18828                "        {\n"
18829                "        a();\n"
18830                "        b();\n"
18831                "        }\n"
18832                "      }\n"
18833                "    void g()\n"
18834                "      {\n"
18835                "      return;\n"
18836                "      }\n"
18837                "    };\n"
18838                "  struct B\n"
18839                "    {\n"
18840                "    int x;\n"
18841                "    };\n"
18842                "  } // namespace b\n"
18843                "  } // namespace a",
18844                WhitesmithsBraceStyle);
18845 
18846   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18847   verifyFormat("namespace a\n"
18848                "  {\n"
18849                "  namespace b\n"
18850                "    {\n"
18851                "    class A\n"
18852                "      {\n"
18853                "      void f()\n"
18854                "        {\n"
18855                "        if (true)\n"
18856                "          {\n"
18857                "          a();\n"
18858                "          b();\n"
18859                "          }\n"
18860                "        }\n"
18861                "      void g()\n"
18862                "        {\n"
18863                "        return;\n"
18864                "        }\n"
18865                "      };\n"
18866                "    struct B\n"
18867                "      {\n"
18868                "      int x;\n"
18869                "      };\n"
18870                "    } // namespace b\n"
18871                "  }   // namespace a",
18872                WhitesmithsBraceStyle);
18873 
18874   verifyFormat("void f()\n"
18875                "  {\n"
18876                "  if (true)\n"
18877                "    {\n"
18878                "    a();\n"
18879                "    }\n"
18880                "  else if (false)\n"
18881                "    {\n"
18882                "    b();\n"
18883                "    }\n"
18884                "  else\n"
18885                "    {\n"
18886                "    c();\n"
18887                "    }\n"
18888                "  }\n",
18889                WhitesmithsBraceStyle);
18890 
18891   verifyFormat("void f()\n"
18892                "  {\n"
18893                "  for (int i = 0; i < 10; ++i)\n"
18894                "    {\n"
18895                "    a();\n"
18896                "    }\n"
18897                "  while (false)\n"
18898                "    {\n"
18899                "    b();\n"
18900                "    }\n"
18901                "  do\n"
18902                "    {\n"
18903                "    c();\n"
18904                "    } while (false)\n"
18905                "  }\n",
18906                WhitesmithsBraceStyle);
18907 
18908   WhitesmithsBraceStyle.IndentCaseLabels = true;
18909   verifyFormat("void switchTest1(int a)\n"
18910                "  {\n"
18911                "  switch (a)\n"
18912                "    {\n"
18913                "    case 2:\n"
18914                "      {\n"
18915                "      }\n"
18916                "      break;\n"
18917                "    }\n"
18918                "  }\n",
18919                WhitesmithsBraceStyle);
18920 
18921   verifyFormat("void switchTest2(int a)\n"
18922                "  {\n"
18923                "  switch (a)\n"
18924                "    {\n"
18925                "    case 0:\n"
18926                "      break;\n"
18927                "    case 1:\n"
18928                "      {\n"
18929                "      break;\n"
18930                "      }\n"
18931                "    case 2:\n"
18932                "      {\n"
18933                "      }\n"
18934                "      break;\n"
18935                "    default:\n"
18936                "      break;\n"
18937                "    }\n"
18938                "  }\n",
18939                WhitesmithsBraceStyle);
18940 
18941   verifyFormat("void switchTest3(int a)\n"
18942                "  {\n"
18943                "  switch (a)\n"
18944                "    {\n"
18945                "    case 0:\n"
18946                "      {\n"
18947                "      foo(x);\n"
18948                "      }\n"
18949                "      break;\n"
18950                "    default:\n"
18951                "      {\n"
18952                "      foo(1);\n"
18953                "      }\n"
18954                "      break;\n"
18955                "    }\n"
18956                "  }\n",
18957                WhitesmithsBraceStyle);
18958 
18959   WhitesmithsBraceStyle.IndentCaseLabels = false;
18960 
18961   verifyFormat("void switchTest4(int a)\n"
18962                "  {\n"
18963                "  switch (a)\n"
18964                "    {\n"
18965                "  case 2:\n"
18966                "    {\n"
18967                "    }\n"
18968                "    break;\n"
18969                "    }\n"
18970                "  }\n",
18971                WhitesmithsBraceStyle);
18972 
18973   verifyFormat("void switchTest5(int a)\n"
18974                "  {\n"
18975                "  switch (a)\n"
18976                "    {\n"
18977                "  case 0:\n"
18978                "    break;\n"
18979                "  case 1:\n"
18980                "    {\n"
18981                "    foo();\n"
18982                "    break;\n"
18983                "    }\n"
18984                "  case 2:\n"
18985                "    {\n"
18986                "    }\n"
18987                "    break;\n"
18988                "  default:\n"
18989                "    break;\n"
18990                "    }\n"
18991                "  }\n",
18992                WhitesmithsBraceStyle);
18993 
18994   verifyFormat("void switchTest6(int a)\n"
18995                "  {\n"
18996                "  switch (a)\n"
18997                "    {\n"
18998                "  case 0:\n"
18999                "    {\n"
19000                "    foo(x);\n"
19001                "    }\n"
19002                "    break;\n"
19003                "  default:\n"
19004                "    {\n"
19005                "    foo(1);\n"
19006                "    }\n"
19007                "    break;\n"
19008                "    }\n"
19009                "  }\n",
19010                WhitesmithsBraceStyle);
19011 
19012   verifyFormat("enum X\n"
19013                "  {\n"
19014                "  Y = 0, // testing\n"
19015                "  }\n",
19016                WhitesmithsBraceStyle);
19017 
19018   verifyFormat("enum X\n"
19019                "  {\n"
19020                "  Y = 0\n"
19021                "  }\n",
19022                WhitesmithsBraceStyle);
19023   verifyFormat("enum X\n"
19024                "  {\n"
19025                "  Y = 0,\n"
19026                "  Z = 1\n"
19027                "  };\n",
19028                WhitesmithsBraceStyle);
19029 
19030   verifyFormat("@interface BSApplicationController ()\n"
19031                "  {\n"
19032                "@private\n"
19033                "  id _extraIvar;\n"
19034                "  }\n"
19035                "@end\n",
19036                WhitesmithsBraceStyle);
19037 
19038   verifyFormat("#ifdef _DEBUG\n"
19039                "int foo(int i = 0)\n"
19040                "#else\n"
19041                "int foo(int i = 5)\n"
19042                "#endif\n"
19043                "  {\n"
19044                "  return i;\n"
19045                "  }",
19046                WhitesmithsBraceStyle);
19047 
19048   verifyFormat("void foo() {}\n"
19049                "void bar()\n"
19050                "#ifdef _DEBUG\n"
19051                "  {\n"
19052                "  foo();\n"
19053                "  }\n"
19054                "#else\n"
19055                "  {\n"
19056                "  }\n"
19057                "#endif",
19058                WhitesmithsBraceStyle);
19059 
19060   verifyFormat("void foobar()\n"
19061                "  {\n"
19062                "  int i = 5;\n"
19063                "  }\n"
19064                "#ifdef _DEBUG\n"
19065                "void bar()\n"
19066                "  {\n"
19067                "  }\n"
19068                "#else\n"
19069                "void bar()\n"
19070                "  {\n"
19071                "  foobar();\n"
19072                "  }\n"
19073                "#endif",
19074                WhitesmithsBraceStyle);
19075 
19076   // This shouldn't affect ObjC blocks..
19077   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
19078                "  // ...\n"
19079                "  int i;\n"
19080                "}];",
19081                WhitesmithsBraceStyle);
19082   verifyFormat("void (^block)(void) = ^{\n"
19083                "  // ...\n"
19084                "  int i;\n"
19085                "};",
19086                WhitesmithsBraceStyle);
19087   // .. or dict literals.
19088   verifyFormat("void f()\n"
19089                "  {\n"
19090                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
19091                "  }",
19092                WhitesmithsBraceStyle);
19093 
19094   verifyFormat("int f()\n"
19095                "  { // comment\n"
19096                "  return 42;\n"
19097                "  }",
19098                WhitesmithsBraceStyle);
19099 
19100   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
19101   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
19102       FormatStyle::SIS_OnlyFirstIf;
19103   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
19104   verifyFormat("void f(bool b)\n"
19105                "  {\n"
19106                "  if (b)\n"
19107                "    {\n"
19108                "    return;\n"
19109                "    }\n"
19110                "  }\n",
19111                BreakBeforeBraceShortIfs);
19112   verifyFormat("void f(bool b)\n"
19113                "  {\n"
19114                "  if (b) return;\n"
19115                "  }\n",
19116                BreakBeforeBraceShortIfs);
19117   verifyFormat("void f(bool b)\n"
19118                "  {\n"
19119                "  while (b)\n"
19120                "    {\n"
19121                "    return;\n"
19122                "    }\n"
19123                "  }\n",
19124                BreakBeforeBraceShortIfs);
19125 }
19126 
19127 TEST_F(FormatTest, GNUBraceBreaking) {
19128   FormatStyle GNUBraceStyle = getLLVMStyle();
19129   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
19130   verifyFormat("namespace a\n"
19131                "{\n"
19132                "class A\n"
19133                "{\n"
19134                "  void f()\n"
19135                "  {\n"
19136                "    int a;\n"
19137                "    {\n"
19138                "      int b;\n"
19139                "    }\n"
19140                "    if (true)\n"
19141                "      {\n"
19142                "        a();\n"
19143                "        b();\n"
19144                "      }\n"
19145                "  }\n"
19146                "  void g() { return; }\n"
19147                "}\n"
19148                "} // namespace a",
19149                GNUBraceStyle);
19150 
19151   verifyFormat("void f()\n"
19152                "{\n"
19153                "  if (true)\n"
19154                "    {\n"
19155                "      a();\n"
19156                "    }\n"
19157                "  else if (false)\n"
19158                "    {\n"
19159                "      b();\n"
19160                "    }\n"
19161                "  else\n"
19162                "    {\n"
19163                "      c();\n"
19164                "    }\n"
19165                "}\n",
19166                GNUBraceStyle);
19167 
19168   verifyFormat("void f()\n"
19169                "{\n"
19170                "  for (int i = 0; i < 10; ++i)\n"
19171                "    {\n"
19172                "      a();\n"
19173                "    }\n"
19174                "  while (false)\n"
19175                "    {\n"
19176                "      b();\n"
19177                "    }\n"
19178                "  do\n"
19179                "    {\n"
19180                "      c();\n"
19181                "    }\n"
19182                "  while (false);\n"
19183                "}\n",
19184                GNUBraceStyle);
19185 
19186   verifyFormat("void f(int a)\n"
19187                "{\n"
19188                "  switch (a)\n"
19189                "    {\n"
19190                "    case 0:\n"
19191                "      break;\n"
19192                "    case 1:\n"
19193                "      {\n"
19194                "        break;\n"
19195                "      }\n"
19196                "    case 2:\n"
19197                "      {\n"
19198                "      }\n"
19199                "      break;\n"
19200                "    default:\n"
19201                "      break;\n"
19202                "    }\n"
19203                "}\n",
19204                GNUBraceStyle);
19205 
19206   verifyFormat("enum X\n"
19207                "{\n"
19208                "  Y = 0,\n"
19209                "}\n",
19210                GNUBraceStyle);
19211 
19212   verifyFormat("@interface BSApplicationController ()\n"
19213                "{\n"
19214                "@private\n"
19215                "  id _extraIvar;\n"
19216                "}\n"
19217                "@end\n",
19218                GNUBraceStyle);
19219 
19220   verifyFormat("#ifdef _DEBUG\n"
19221                "int foo(int i = 0)\n"
19222                "#else\n"
19223                "int foo(int i = 5)\n"
19224                "#endif\n"
19225                "{\n"
19226                "  return i;\n"
19227                "}",
19228                GNUBraceStyle);
19229 
19230   verifyFormat("void foo() {}\n"
19231                "void bar()\n"
19232                "#ifdef _DEBUG\n"
19233                "{\n"
19234                "  foo();\n"
19235                "}\n"
19236                "#else\n"
19237                "{\n"
19238                "}\n"
19239                "#endif",
19240                GNUBraceStyle);
19241 
19242   verifyFormat("void foobar() { int i = 5; }\n"
19243                "#ifdef _DEBUG\n"
19244                "void bar() {}\n"
19245                "#else\n"
19246                "void bar() { foobar(); }\n"
19247                "#endif",
19248                GNUBraceStyle);
19249 }
19250 
19251 TEST_F(FormatTest, WebKitBraceBreaking) {
19252   FormatStyle WebKitBraceStyle = getLLVMStyle();
19253   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
19254   WebKitBraceStyle.FixNamespaceComments = false;
19255   verifyFormat("namespace a {\n"
19256                "class A {\n"
19257                "  void f()\n"
19258                "  {\n"
19259                "    if (true) {\n"
19260                "      a();\n"
19261                "      b();\n"
19262                "    }\n"
19263                "  }\n"
19264                "  void g() { return; }\n"
19265                "};\n"
19266                "enum E {\n"
19267                "  A,\n"
19268                "  // foo\n"
19269                "  B,\n"
19270                "  C\n"
19271                "};\n"
19272                "struct B {\n"
19273                "  int x;\n"
19274                "};\n"
19275                "}\n",
19276                WebKitBraceStyle);
19277   verifyFormat("struct S {\n"
19278                "  int Type;\n"
19279                "  union {\n"
19280                "    int x;\n"
19281                "    double y;\n"
19282                "  } Value;\n"
19283                "  class C {\n"
19284                "    MyFavoriteType Value;\n"
19285                "  } Class;\n"
19286                "};\n",
19287                WebKitBraceStyle);
19288 }
19289 
19290 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
19291   verifyFormat("void f() {\n"
19292                "  try {\n"
19293                "  } catch (const Exception &e) {\n"
19294                "  }\n"
19295                "}\n",
19296                getLLVMStyle());
19297 }
19298 
19299 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
19300   auto Style = getLLVMStyle();
19301   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19302   Style.AlignConsecutiveAssignments.Enabled = true;
19303   Style.AlignConsecutiveDeclarations.Enabled = true;
19304   verifyFormat("struct test demo[] = {\n"
19305                "    {56,    23, \"hello\"},\n"
19306                "    {-1, 93463, \"world\"},\n"
19307                "    { 7,     5,    \"!!\"}\n"
19308                "};\n",
19309                Style);
19310 
19311   verifyFormat("struct test demo[] = {\n"
19312                "    {56,    23, \"hello\"}, // first line\n"
19313                "    {-1, 93463, \"world\"}, // second line\n"
19314                "    { 7,     5,    \"!!\"}  // third line\n"
19315                "};\n",
19316                Style);
19317 
19318   verifyFormat("struct test demo[4] = {\n"
19319                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19320                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19321                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19322                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19323                "};\n",
19324                Style);
19325 
19326   verifyFormat("struct test demo[3] = {\n"
19327                "    {56,    23, \"hello\"},\n"
19328                "    {-1, 93463, \"world\"},\n"
19329                "    { 7,     5,    \"!!\"}\n"
19330                "};\n",
19331                Style);
19332 
19333   verifyFormat("struct test demo[3] = {\n"
19334                "    {int{56},    23, \"hello\"},\n"
19335                "    {int{-1}, 93463, \"world\"},\n"
19336                "    { int{7},     5,    \"!!\"}\n"
19337                "};\n",
19338                Style);
19339 
19340   verifyFormat("struct test demo[] = {\n"
19341                "    {56,    23, \"hello\"},\n"
19342                "    {-1, 93463, \"world\"},\n"
19343                "    { 7,     5,    \"!!\"},\n"
19344                "};\n",
19345                Style);
19346 
19347   verifyFormat("test demo[] = {\n"
19348                "    {56,    23, \"hello\"},\n"
19349                "    {-1, 93463, \"world\"},\n"
19350                "    { 7,     5,    \"!!\"},\n"
19351                "};\n",
19352                Style);
19353 
19354   verifyFormat("demo = std::array<struct test, 3>{\n"
19355                "    test{56,    23, \"hello\"},\n"
19356                "    test{-1, 93463, \"world\"},\n"
19357                "    test{ 7,     5,    \"!!\"},\n"
19358                "};\n",
19359                Style);
19360 
19361   verifyFormat("test demo[] = {\n"
19362                "    {56,    23, \"hello\"},\n"
19363                "#if X\n"
19364                "    {-1, 93463, \"world\"},\n"
19365                "#endif\n"
19366                "    { 7,     5,    \"!!\"}\n"
19367                "};\n",
19368                Style);
19369 
19370   verifyFormat(
19371       "test demo[] = {\n"
19372       "    { 7,    23,\n"
19373       "     \"hello world i am a very long line that really, in any\"\n"
19374       "     \"just world, ought to be split over multiple lines\"},\n"
19375       "    {-1, 93463,                                  \"world\"},\n"
19376       "    {56,     5,                                     \"!!\"}\n"
19377       "};\n",
19378       Style);
19379 
19380   verifyFormat("return GradForUnaryCwise(g, {\n"
19381                "                                {{\"sign\"}, \"Sign\",  "
19382                "  {\"x\", \"dy\"}},\n"
19383                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
19384                ", \"sign\"}},\n"
19385                "});\n",
19386                Style);
19387 
19388   Style.ColumnLimit = 0;
19389   EXPECT_EQ(
19390       "test demo[] = {\n"
19391       "    {56,    23, \"hello world i am a very long line that really, "
19392       "in any just world, ought to be split over multiple lines\"},\n"
19393       "    {-1, 93463,                                                  "
19394       "                                                 \"world\"},\n"
19395       "    { 7,     5,                                                  "
19396       "                                                    \"!!\"},\n"
19397       "};",
19398       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19399              "that really, in any just world, ought to be split over multiple "
19400              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19401              Style));
19402 
19403   Style.ColumnLimit = 80;
19404   verifyFormat("test demo[] = {\n"
19405                "    {56,    23, /* a comment */ \"hello\"},\n"
19406                "    {-1, 93463,                 \"world\"},\n"
19407                "    { 7,     5,                    \"!!\"}\n"
19408                "};\n",
19409                Style);
19410 
19411   verifyFormat("test demo[] = {\n"
19412                "    {56,    23,                    \"hello\"},\n"
19413                "    {-1, 93463, \"world\" /* comment here */},\n"
19414                "    { 7,     5,                       \"!!\"}\n"
19415                "};\n",
19416                Style);
19417 
19418   verifyFormat("test demo[] = {\n"
19419                "    {56, /* a comment */ 23, \"hello\"},\n"
19420                "    {-1,              93463, \"world\"},\n"
19421                "    { 7,                  5,    \"!!\"}\n"
19422                "};\n",
19423                Style);
19424 
19425   Style.ColumnLimit = 20;
19426   EXPECT_EQ(
19427       "demo = std::array<\n"
19428       "    struct test, 3>{\n"
19429       "    test{\n"
19430       "         56,    23,\n"
19431       "         \"hello \"\n"
19432       "         \"world i \"\n"
19433       "         \"am a very \"\n"
19434       "         \"long line \"\n"
19435       "         \"that \"\n"
19436       "         \"really, \"\n"
19437       "         \"in any \"\n"
19438       "         \"just \"\n"
19439       "         \"world, \"\n"
19440       "         \"ought to \"\n"
19441       "         \"be split \"\n"
19442       "         \"over \"\n"
19443       "         \"multiple \"\n"
19444       "         \"lines\"},\n"
19445       "    test{-1, 93463,\n"
19446       "         \"world\"},\n"
19447       "    test{ 7,     5,\n"
19448       "         \"!!\"   },\n"
19449       "};",
19450       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19451              "i am a very long line that really, in any just world, ought "
19452              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19453              "test{7, 5, \"!!\"},};",
19454              Style));
19455   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19456   Style = getLLVMStyleWithColumns(50);
19457   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19458   verifyFormat("static A x = {\n"
19459                "    {{init1, init2, init3, init4},\n"
19460                "     {init1, init2, init3, init4}}\n"
19461                "};",
19462                Style);
19463   // TODO: Fix the indentations below when this option is fully functional.
19464   verifyFormat("int a[][] = {\n"
19465                "    {\n"
19466                "     {0, 2}, //\n"
19467                " {1, 2}  //\n"
19468                "    }\n"
19469                "};",
19470                Style);
19471   Style.ColumnLimit = 100;
19472   EXPECT_EQ(
19473       "test demo[] = {\n"
19474       "    {56,    23,\n"
19475       "     \"hello world i am a very long line that really, in any just world"
19476       ", ought to be split over \"\n"
19477       "     \"multiple lines\"  },\n"
19478       "    {-1, 93463, \"world\"},\n"
19479       "    { 7,     5,    \"!!\"},\n"
19480       "};",
19481       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19482              "that really, in any just world, ought to be split over multiple "
19483              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19484              Style));
19485 
19486   Style = getLLVMStyleWithColumns(50);
19487   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19488   verifyFormat("struct test demo[] = {\n"
19489                "    {56,    23, \"hello\"},\n"
19490                "    {-1, 93463, \"world\"},\n"
19491                "    { 7,     5,    \"!!\"}\n"
19492                "};\n"
19493                "static A x = {\n"
19494                "    {{init1, init2, init3, init4},\n"
19495                "     {init1, init2, init3, init4}}\n"
19496                "};",
19497                Style);
19498   Style.ColumnLimit = 100;
19499   Style.AlignConsecutiveAssignments.AcrossComments = true;
19500   Style.AlignConsecutiveDeclarations.AcrossComments = true;
19501   verifyFormat("struct test demo[] = {\n"
19502                "    {56,    23, \"hello\"},\n"
19503                "    {-1, 93463, \"world\"},\n"
19504                "    { 7,     5,    \"!!\"}\n"
19505                "};\n"
19506                "struct test demo[4] = {\n"
19507                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19508                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19509                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19510                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19511                "};\n",
19512                Style);
19513   EXPECT_EQ(
19514       "test demo[] = {\n"
19515       "    {56,\n"
19516       "     \"hello world i am a very long line that really, in any just world"
19517       ", ought to be split over \"\n"
19518       "     \"multiple lines\",    23},\n"
19519       "    {-1,      \"world\", 93463},\n"
19520       "    { 7,         \"!!\",     5},\n"
19521       "};",
19522       format("test demo[] = {{56, \"hello world i am a very long line "
19523              "that really, in any just world, ought to be split over multiple "
19524              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
19525              Style));
19526 }
19527 
19528 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
19529   auto Style = getLLVMStyle();
19530   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19531   /* FIXME: This case gets misformatted.
19532   verifyFormat("auto foo = Items{\n"
19533                "    Section{0, bar(), },\n"
19534                "    Section{1, boo()  }\n"
19535                "};\n",
19536                Style);
19537   */
19538   verifyFormat("auto foo = Items{\n"
19539                "    Section{\n"
19540                "            0, bar(),\n"
19541                "            }\n"
19542                "};\n",
19543                Style);
19544   verifyFormat("struct test demo[] = {\n"
19545                "    {56, 23,    \"hello\"},\n"
19546                "    {-1, 93463, \"world\"},\n"
19547                "    {7,  5,     \"!!\"   }\n"
19548                "};\n",
19549                Style);
19550   verifyFormat("struct test demo[] = {\n"
19551                "    {56, 23,    \"hello\"}, // first line\n"
19552                "    {-1, 93463, \"world\"}, // second line\n"
19553                "    {7,  5,     \"!!\"   }  // third line\n"
19554                "};\n",
19555                Style);
19556   verifyFormat("struct test demo[4] = {\n"
19557                "    {56,  23,    21, \"oh\"      }, // first line\n"
19558                "    {-1,  93463, 22, \"my\"      }, // second line\n"
19559                "    {7,   5,     1,  \"goodness\"}  // third line\n"
19560                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
19561                "};\n",
19562                Style);
19563   verifyFormat("struct test demo[3] = {\n"
19564                "    {56, 23,    \"hello\"},\n"
19565                "    {-1, 93463, \"world\"},\n"
19566                "    {7,  5,     \"!!\"   }\n"
19567                "};\n",
19568                Style);
19569 
19570   verifyFormat("struct test demo[3] = {\n"
19571                "    {int{56}, 23,    \"hello\"},\n"
19572                "    {int{-1}, 93463, \"world\"},\n"
19573                "    {int{7},  5,     \"!!\"   }\n"
19574                "};\n",
19575                Style);
19576   verifyFormat("struct test demo[] = {\n"
19577                "    {56, 23,    \"hello\"},\n"
19578                "    {-1, 93463, \"world\"},\n"
19579                "    {7,  5,     \"!!\"   },\n"
19580                "};\n",
19581                Style);
19582   verifyFormat("test demo[] = {\n"
19583                "    {56, 23,    \"hello\"},\n"
19584                "    {-1, 93463, \"world\"},\n"
19585                "    {7,  5,     \"!!\"   },\n"
19586                "};\n",
19587                Style);
19588   verifyFormat("demo = std::array<struct test, 3>{\n"
19589                "    test{56, 23,    \"hello\"},\n"
19590                "    test{-1, 93463, \"world\"},\n"
19591                "    test{7,  5,     \"!!\"   },\n"
19592                "};\n",
19593                Style);
19594   verifyFormat("test demo[] = {\n"
19595                "    {56, 23,    \"hello\"},\n"
19596                "#if X\n"
19597                "    {-1, 93463, \"world\"},\n"
19598                "#endif\n"
19599                "    {7,  5,     \"!!\"   }\n"
19600                "};\n",
19601                Style);
19602   verifyFormat(
19603       "test demo[] = {\n"
19604       "    {7,  23,\n"
19605       "     \"hello world i am a very long line that really, in any\"\n"
19606       "     \"just world, ought to be split over multiple lines\"},\n"
19607       "    {-1, 93463, \"world\"                                 },\n"
19608       "    {56, 5,     \"!!\"                                    }\n"
19609       "};\n",
19610       Style);
19611 
19612   verifyFormat("return GradForUnaryCwise(g, {\n"
19613                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19614                "\"dy\"}   },\n"
19615                "                                {{\"dx\"},   \"Mul\",  "
19616                "{\"dy\", \"sign\"}},\n"
19617                "});\n",
19618                Style);
19619 
19620   Style.ColumnLimit = 0;
19621   EXPECT_EQ(
19622       "test demo[] = {\n"
19623       "    {56, 23,    \"hello world i am a very long line that really, in any "
19624       "just world, ought to be split over multiple lines\"},\n"
19625       "    {-1, 93463, \"world\"                                               "
19626       "                                                   },\n"
19627       "    {7,  5,     \"!!\"                                                  "
19628       "                                                   },\n"
19629       "};",
19630       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19631              "that really, in any just world, ought to be split over multiple "
19632              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19633              Style));
19634 
19635   Style.ColumnLimit = 80;
19636   verifyFormat("test demo[] = {\n"
19637                "    {56, 23,    /* a comment */ \"hello\"},\n"
19638                "    {-1, 93463, \"world\"                },\n"
19639                "    {7,  5,     \"!!\"                   }\n"
19640                "};\n",
19641                Style);
19642 
19643   verifyFormat("test demo[] = {\n"
19644                "    {56, 23,    \"hello\"                   },\n"
19645                "    {-1, 93463, \"world\" /* comment here */},\n"
19646                "    {7,  5,     \"!!\"                      }\n"
19647                "};\n",
19648                Style);
19649 
19650   verifyFormat("test demo[] = {\n"
19651                "    {56, /* a comment */ 23, \"hello\"},\n"
19652                "    {-1, 93463,              \"world\"},\n"
19653                "    {7,  5,                  \"!!\"   }\n"
19654                "};\n",
19655                Style);
19656 
19657   Style.ColumnLimit = 20;
19658   EXPECT_EQ(
19659       "demo = std::array<\n"
19660       "    struct test, 3>{\n"
19661       "    test{\n"
19662       "         56, 23,\n"
19663       "         \"hello \"\n"
19664       "         \"world i \"\n"
19665       "         \"am a very \"\n"
19666       "         \"long line \"\n"
19667       "         \"that \"\n"
19668       "         \"really, \"\n"
19669       "         \"in any \"\n"
19670       "         \"just \"\n"
19671       "         \"world, \"\n"
19672       "         \"ought to \"\n"
19673       "         \"be split \"\n"
19674       "         \"over \"\n"
19675       "         \"multiple \"\n"
19676       "         \"lines\"},\n"
19677       "    test{-1, 93463,\n"
19678       "         \"world\"},\n"
19679       "    test{7,  5,\n"
19680       "         \"!!\"   },\n"
19681       "};",
19682       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19683              "i am a very long line that really, in any just world, ought "
19684              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19685              "test{7, 5, \"!!\"},};",
19686              Style));
19687 
19688   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19689   Style = getLLVMStyleWithColumns(50);
19690   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19691   verifyFormat("static A x = {\n"
19692                "    {{init1, init2, init3, init4},\n"
19693                "     {init1, init2, init3, init4}}\n"
19694                "};",
19695                Style);
19696   Style.ColumnLimit = 100;
19697   EXPECT_EQ(
19698       "test demo[] = {\n"
19699       "    {56, 23,\n"
19700       "     \"hello world i am a very long line that really, in any just world"
19701       ", ought to be split over \"\n"
19702       "     \"multiple lines\"  },\n"
19703       "    {-1, 93463, \"world\"},\n"
19704       "    {7,  5,     \"!!\"   },\n"
19705       "};",
19706       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19707              "that really, in any just world, ought to be split over multiple "
19708              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19709              Style));
19710 }
19711 
19712 TEST_F(FormatTest, UnderstandsPragmas) {
19713   verifyFormat("#pragma omp reduction(| : var)");
19714   verifyFormat("#pragma omp reduction(+ : var)");
19715 
19716   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19717             "(including parentheses).",
19718             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19719                    "(including parentheses)."));
19720 }
19721 
19722 TEST_F(FormatTest, UnderstandPragmaOption) {
19723   verifyFormat("#pragma option -C -A");
19724 
19725   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19726 }
19727 
19728 TEST_F(FormatTest, UnderstandPragmaRegion) {
19729   auto Style = getLLVMStyleWithColumns(0);
19730   verifyFormat("#pragma region TEST(FOO : BAR)", Style);
19731 
19732   EXPECT_EQ("#pragma region TEST(FOO : BAR)",
19733             format("#pragma region TEST(FOO : BAR)", Style));
19734 }
19735 
19736 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19737   FormatStyle Style = getLLVMStyleWithColumns(20);
19738 
19739   // See PR41213
19740   EXPECT_EQ("/*\n"
19741             " *\t9012345\n"
19742             " * /8901\n"
19743             " */",
19744             format("/*\n"
19745                    " *\t9012345 /8901\n"
19746                    " */",
19747                    Style));
19748   EXPECT_EQ("/*\n"
19749             " *345678\n"
19750             " *\t/8901\n"
19751             " */",
19752             format("/*\n"
19753                    " *345678\t/8901\n"
19754                    " */",
19755                    Style));
19756 
19757   verifyFormat("int a; // the\n"
19758                "       // comment",
19759                Style);
19760   EXPECT_EQ("int a; /* first line\n"
19761             "        * second\n"
19762             "        * line third\n"
19763             "        * line\n"
19764             "        */",
19765             format("int a; /* first line\n"
19766                    "        * second\n"
19767                    "        * line third\n"
19768                    "        * line\n"
19769                    "        */",
19770                    Style));
19771   EXPECT_EQ("int a; // first line\n"
19772             "       // second\n"
19773             "       // line third\n"
19774             "       // line",
19775             format("int a; // first line\n"
19776                    "       // second line\n"
19777                    "       // third line",
19778                    Style));
19779 
19780   Style.PenaltyExcessCharacter = 90;
19781   verifyFormat("int a; // the comment", Style);
19782   EXPECT_EQ("int a; // the comment\n"
19783             "       // aaa",
19784             format("int a; // the comment aaa", Style));
19785   EXPECT_EQ("int a; /* first line\n"
19786             "        * second line\n"
19787             "        * third line\n"
19788             "        */",
19789             format("int a; /* first line\n"
19790                    "        * second line\n"
19791                    "        * third line\n"
19792                    "        */",
19793                    Style));
19794   EXPECT_EQ("int a; // first line\n"
19795             "       // second line\n"
19796             "       // third line",
19797             format("int a; // first line\n"
19798                    "       // second line\n"
19799                    "       // third line",
19800                    Style));
19801   // FIXME: Investigate why this is not getting the same layout as the test
19802   // above.
19803   EXPECT_EQ("int a; /* first line\n"
19804             "        * second line\n"
19805             "        * third line\n"
19806             "        */",
19807             format("int a; /* first line second line third line"
19808                    "\n*/",
19809                    Style));
19810 
19811   EXPECT_EQ("// foo bar baz bazfoo\n"
19812             "// foo bar foo bar\n",
19813             format("// foo bar baz bazfoo\n"
19814                    "// foo bar foo           bar\n",
19815                    Style));
19816   EXPECT_EQ("// foo bar baz bazfoo\n"
19817             "// foo bar foo bar\n",
19818             format("// foo bar baz      bazfoo\n"
19819                    "// foo            bar foo bar\n",
19820                    Style));
19821 
19822   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19823   // next one.
19824   EXPECT_EQ("// foo bar baz bazfoo\n"
19825             "// bar foo bar\n",
19826             format("// foo bar baz      bazfoo bar\n"
19827                    "// foo            bar\n",
19828                    Style));
19829 
19830   EXPECT_EQ("// foo bar baz bazfoo\n"
19831             "// foo bar baz bazfoo\n"
19832             "// bar foo bar\n",
19833             format("// foo bar baz      bazfoo\n"
19834                    "// foo bar baz      bazfoo bar\n"
19835                    "// foo bar\n",
19836                    Style));
19837 
19838   EXPECT_EQ("// foo bar baz bazfoo\n"
19839             "// foo bar baz bazfoo\n"
19840             "// bar foo bar\n",
19841             format("// foo bar baz      bazfoo\n"
19842                    "// foo bar baz      bazfoo bar\n"
19843                    "// foo           bar\n",
19844                    Style));
19845 
19846   // Make sure we do not keep protruding characters if strict mode reflow is
19847   // cheaper than keeping protruding characters.
19848   Style.ColumnLimit = 21;
19849   EXPECT_EQ(
19850       "// foo foo foo foo\n"
19851       "// foo foo foo foo\n"
19852       "// foo foo foo foo\n",
19853       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19854 
19855   EXPECT_EQ("int a = /* long block\n"
19856             "           comment */\n"
19857             "    42;",
19858             format("int a = /* long block comment */ 42;", Style));
19859 }
19860 
19861 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19862   FormatStyle Style = getLLVMStyle();
19863   Style.ColumnLimit = 8;
19864   Style.PenaltyExcessCharacter = 15;
19865   verifyFormat("int foo(\n"
19866                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19867                Style);
19868   Style.PenaltyBreakOpenParenthesis = 200;
19869   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19870             format("int foo(\n"
19871                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19872                    Style));
19873 }
19874 
19875 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19876   FormatStyle Style = getLLVMStyle();
19877   Style.ColumnLimit = 5;
19878   Style.PenaltyExcessCharacter = 150;
19879   verifyFormat("foo((\n"
19880                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19881 
19882                Style);
19883   Style.PenaltyBreakOpenParenthesis = 100000;
19884   EXPECT_EQ("foo((int)\n"
19885             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19886             format("foo((\n"
19887                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19888                    Style));
19889 }
19890 
19891 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19892   FormatStyle Style = getLLVMStyle();
19893   Style.ColumnLimit = 4;
19894   Style.PenaltyExcessCharacter = 100;
19895   verifyFormat("for (\n"
19896                "    int iiiiiiiiiiiiiiiii =\n"
19897                "        0;\n"
19898                "    iiiiiiiiiiiiiiiii <\n"
19899                "    2;\n"
19900                "    iiiiiiiiiiiiiiiii++) {\n"
19901                "}",
19902 
19903                Style);
19904   Style.PenaltyBreakOpenParenthesis = 1250;
19905   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19906             "         0;\n"
19907             "     iiiiiiiiiiiiiiiii <\n"
19908             "     2;\n"
19909             "     iiiiiiiiiiiiiiiii++) {\n"
19910             "}",
19911             format("for (\n"
19912                    "    int iiiiiiiiiiiiiiiii =\n"
19913                    "        0;\n"
19914                    "    iiiiiiiiiiiiiiiii <\n"
19915                    "    2;\n"
19916                    "    iiiiiiiiiiiiiiiii++) {\n"
19917                    "}",
19918                    Style));
19919 }
19920 
19921 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19922   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19923   EXPECT_EQ(Styles[0], Styles[i])                                              \
19924       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19925 
19926 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19927   SmallVector<FormatStyle, 3> Styles;
19928   Styles.resize(3);
19929 
19930   Styles[0] = getLLVMStyle();
19931   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19932   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19933   EXPECT_ALL_STYLES_EQUAL(Styles);
19934 
19935   Styles[0] = getGoogleStyle();
19936   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19937   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19938   EXPECT_ALL_STYLES_EQUAL(Styles);
19939 
19940   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19941   EXPECT_TRUE(
19942       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19943   EXPECT_TRUE(
19944       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19945   EXPECT_ALL_STYLES_EQUAL(Styles);
19946 
19947   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19948   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19949   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19950   EXPECT_ALL_STYLES_EQUAL(Styles);
19951 
19952   Styles[0] = getMozillaStyle();
19953   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19954   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19955   EXPECT_ALL_STYLES_EQUAL(Styles);
19956 
19957   Styles[0] = getWebKitStyle();
19958   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19959   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19960   EXPECT_ALL_STYLES_EQUAL(Styles);
19961 
19962   Styles[0] = getGNUStyle();
19963   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19964   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19965   EXPECT_ALL_STYLES_EQUAL(Styles);
19966 
19967   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19968 }
19969 
19970 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19971   SmallVector<FormatStyle, 8> Styles;
19972   Styles.resize(2);
19973 
19974   Styles[0] = getGoogleStyle();
19975   Styles[1] = getLLVMStyle();
19976   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19977   EXPECT_ALL_STYLES_EQUAL(Styles);
19978 
19979   Styles.resize(5);
19980   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19981   Styles[1] = getLLVMStyle();
19982   Styles[1].Language = FormatStyle::LK_JavaScript;
19983   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19984 
19985   Styles[2] = getLLVMStyle();
19986   Styles[2].Language = FormatStyle::LK_JavaScript;
19987   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19988                                   "BasedOnStyle: Google",
19989                                   &Styles[2])
19990                    .value());
19991 
19992   Styles[3] = getLLVMStyle();
19993   Styles[3].Language = FormatStyle::LK_JavaScript;
19994   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19995                                   "Language: JavaScript",
19996                                   &Styles[3])
19997                    .value());
19998 
19999   Styles[4] = getLLVMStyle();
20000   Styles[4].Language = FormatStyle::LK_JavaScript;
20001   EXPECT_EQ(0, parseConfiguration("---\n"
20002                                   "BasedOnStyle: LLVM\n"
20003                                   "IndentWidth: 123\n"
20004                                   "---\n"
20005                                   "BasedOnStyle: Google\n"
20006                                   "Language: JavaScript",
20007                                   &Styles[4])
20008                    .value());
20009   EXPECT_ALL_STYLES_EQUAL(Styles);
20010 }
20011 
20012 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
20013   Style.FIELD = false;                                                         \
20014   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
20015   EXPECT_TRUE(Style.FIELD);                                                    \
20016   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
20017   EXPECT_FALSE(Style.FIELD);
20018 
20019 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
20020 
20021 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
20022   Style.STRUCT.FIELD = false;                                                  \
20023   EXPECT_EQ(0,                                                                 \
20024             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
20025                 .value());                                                     \
20026   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
20027   EXPECT_EQ(0,                                                                 \
20028             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
20029                 .value());                                                     \
20030   EXPECT_FALSE(Style.STRUCT.FIELD);
20031 
20032 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
20033   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
20034 
20035 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
20036   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
20037   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
20038   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
20039 
20040 TEST_F(FormatTest, ParsesConfigurationBools) {
20041   FormatStyle Style = {};
20042   Style.Language = FormatStyle::LK_Cpp;
20043   CHECK_PARSE_BOOL(AlignTrailingComments);
20044   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
20045   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
20046   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
20047   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
20048   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
20049   CHECK_PARSE_BOOL(BinPackArguments);
20050   CHECK_PARSE_BOOL(BinPackParameters);
20051   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
20052   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
20053   CHECK_PARSE_BOOL(BreakStringLiterals);
20054   CHECK_PARSE_BOOL(CompactNamespaces);
20055   CHECK_PARSE_BOOL(DeriveLineEnding);
20056   CHECK_PARSE_BOOL(DerivePointerAlignment);
20057   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
20058   CHECK_PARSE_BOOL(DisableFormat);
20059   CHECK_PARSE_BOOL(IndentAccessModifiers);
20060   CHECK_PARSE_BOOL(IndentCaseLabels);
20061   CHECK_PARSE_BOOL(IndentCaseBlocks);
20062   CHECK_PARSE_BOOL(IndentGotoLabels);
20063   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
20064   CHECK_PARSE_BOOL(IndentRequiresClause);
20065   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
20066   CHECK_PARSE_BOOL(InsertBraces);
20067   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
20068   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
20069   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
20070   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
20071   CHECK_PARSE_BOOL(ReflowComments);
20072   CHECK_PARSE_BOOL(RemoveBracesLLVM);
20073   CHECK_PARSE_BOOL(SortUsingDeclarations);
20074   CHECK_PARSE_BOOL(SpacesInParentheses);
20075   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
20076   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
20077   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
20078   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
20079   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
20080   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
20081   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
20082   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
20083   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
20084   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
20085   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
20086   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
20087   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
20088   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
20089   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
20090   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
20091   CHECK_PARSE_BOOL(UseCRLF);
20092 
20093   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
20094   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
20095   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
20096   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
20097   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
20098   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
20099   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
20100   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
20101   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
20102   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
20103   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
20104   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
20105   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
20106   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
20107   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
20108   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
20109   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
20110   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
20111   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
20112   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
20113                           AfterFunctionDeclarationName);
20114   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
20115                           AfterFunctionDefinitionName);
20116   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
20117   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
20118   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
20119 }
20120 
20121 #undef CHECK_PARSE_BOOL
20122 
20123 TEST_F(FormatTest, ParsesConfiguration) {
20124   FormatStyle Style = {};
20125   Style.Language = FormatStyle::LK_Cpp;
20126   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
20127   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
20128               ConstructorInitializerIndentWidth, 1234u);
20129   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
20130   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
20131   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
20132   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
20133   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
20134               PenaltyBreakBeforeFirstCallParameter, 1234u);
20135   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
20136               PenaltyBreakTemplateDeclaration, 1234u);
20137   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
20138               1234u);
20139   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
20140   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
20141               PenaltyReturnTypeOnItsOwnLine, 1234u);
20142   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
20143               SpacesBeforeTrailingComments, 1234u);
20144   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
20145   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
20146   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
20147 
20148   Style.QualifierAlignment = FormatStyle::QAS_Right;
20149   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
20150               FormatStyle::QAS_Leave);
20151   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
20152               FormatStyle::QAS_Right);
20153   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
20154               FormatStyle::QAS_Left);
20155   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
20156               FormatStyle::QAS_Custom);
20157 
20158   Style.QualifierOrder.clear();
20159   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
20160               std::vector<std::string>({"const", "volatile", "type"}));
20161   Style.QualifierOrder.clear();
20162   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
20163               std::vector<std::string>({"const", "type"}));
20164   Style.QualifierOrder.clear();
20165   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
20166               std::vector<std::string>({"volatile", "type"}));
20167 
20168 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
20169   do {                                                                         \
20170     Style.FIELD.Enabled = true;                                                \
20171     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
20172                 FormatStyle::AlignConsecutiveStyle(                            \
20173                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
20174                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20175                      /*PadOperators=*/true}));                                 \
20176     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
20177                 FormatStyle::AlignConsecutiveStyle(                            \
20178                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
20179                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20180                      /*PadOperators=*/true}));                                 \
20181     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
20182                 FormatStyle::AlignConsecutiveStyle(                            \
20183                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
20184                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20185                      /*PadOperators=*/true}));                                 \
20186     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
20187                 FormatStyle::AlignConsecutiveStyle(                            \
20188                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
20189                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
20190                      /*PadOperators=*/true}));                                 \
20191     /* For backwards compability, false / true should still parse */           \
20192     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
20193                 FormatStyle::AlignConsecutiveStyle(                            \
20194                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
20195                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20196                      /*PadOperators=*/true}));                                 \
20197     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
20198                 FormatStyle::AlignConsecutiveStyle(                            \
20199                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
20200                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20201                      /*PadOperators=*/true}));                                 \
20202                                                                                \
20203     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
20204     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
20205     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
20206     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
20207     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
20208   } while (false)
20209 
20210   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
20211   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
20212   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
20213   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
20214 
20215 #undef CHECK_ALIGN_CONSECUTIVE
20216 
20217   Style.PointerAlignment = FormatStyle::PAS_Middle;
20218   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
20219               FormatStyle::PAS_Left);
20220   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
20221               FormatStyle::PAS_Right);
20222   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
20223               FormatStyle::PAS_Middle);
20224   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
20225   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
20226               FormatStyle::RAS_Pointer);
20227   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
20228               FormatStyle::RAS_Left);
20229   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
20230               FormatStyle::RAS_Right);
20231   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
20232               FormatStyle::RAS_Middle);
20233   // For backward compatibility:
20234   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
20235               FormatStyle::PAS_Left);
20236   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
20237               FormatStyle::PAS_Right);
20238   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
20239               FormatStyle::PAS_Middle);
20240 
20241   Style.Standard = FormatStyle::LS_Auto;
20242   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
20243   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
20244   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
20245   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
20246   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
20247   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
20248   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
20249   // Legacy aliases:
20250   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
20251   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
20252   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
20253   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
20254 
20255   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
20256   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
20257               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
20258   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
20259               FormatStyle::BOS_None);
20260   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
20261               FormatStyle::BOS_All);
20262   // For backward compatibility:
20263   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
20264               FormatStyle::BOS_None);
20265   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
20266               FormatStyle::BOS_All);
20267 
20268   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20269   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
20270               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20271   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
20272               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
20273   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
20274               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
20275   // For backward compatibility:
20276   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
20277               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20278 
20279   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
20280   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
20281               FormatStyle::BILS_AfterComma);
20282   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
20283               FormatStyle::BILS_BeforeComma);
20284   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
20285               FormatStyle::BILS_AfterColon);
20286   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
20287               FormatStyle::BILS_BeforeColon);
20288   // For backward compatibility:
20289   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
20290               FormatStyle::BILS_BeforeComma);
20291 
20292   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20293   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
20294               FormatStyle::PCIS_Never);
20295   CHECK_PARSE("PackConstructorInitializers: BinPack",
20296               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20297   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
20298               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20299   CHECK_PARSE("PackConstructorInitializers: NextLine",
20300               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20301   // For backward compatibility:
20302   CHECK_PARSE("BasedOnStyle: Google\n"
20303               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20304               "AllowAllConstructorInitializersOnNextLine: false",
20305               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20306   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20307   CHECK_PARSE("BasedOnStyle: Google\n"
20308               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
20309               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20310   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20311               "AllowAllConstructorInitializersOnNextLine: true",
20312               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20313   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20314   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20315               "AllowAllConstructorInitializersOnNextLine: false",
20316               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20317 
20318   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
20319   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
20320               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
20321   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
20322               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
20323   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
20324               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
20325   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
20326               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
20327 
20328   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20329   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
20330               FormatStyle::BAS_Align);
20331   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
20332               FormatStyle::BAS_DontAlign);
20333   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
20334               FormatStyle::BAS_AlwaysBreak);
20335   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
20336               FormatStyle::BAS_BlockIndent);
20337   // For backward compatibility:
20338   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
20339               FormatStyle::BAS_DontAlign);
20340   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
20341               FormatStyle::BAS_Align);
20342 
20343   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
20344   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
20345               FormatStyle::ENAS_DontAlign);
20346   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
20347               FormatStyle::ENAS_Left);
20348   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
20349               FormatStyle::ENAS_Right);
20350   // For backward compatibility:
20351   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
20352               FormatStyle::ENAS_Left);
20353   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
20354               FormatStyle::ENAS_Right);
20355 
20356   Style.AlignOperands = FormatStyle::OAS_Align;
20357   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
20358               FormatStyle::OAS_DontAlign);
20359   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
20360   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
20361               FormatStyle::OAS_AlignAfterOperator);
20362   // For backward compatibility:
20363   CHECK_PARSE("AlignOperands: false", AlignOperands,
20364               FormatStyle::OAS_DontAlign);
20365   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
20366 
20367   Style.UseTab = FormatStyle::UT_ForIndentation;
20368   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
20369   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
20370   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
20371   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
20372               FormatStyle::UT_ForContinuationAndIndentation);
20373   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
20374               FormatStyle::UT_AlignWithSpaces);
20375   // For backward compatibility:
20376   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
20377   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
20378 
20379   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
20380   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
20381               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20382   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
20383               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
20384   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
20385               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20386   // For backward compatibility:
20387   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
20388               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20389   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
20390               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20391 
20392   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
20393   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
20394               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20395   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
20396               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
20397   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
20398               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
20399   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
20400               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20401   // For backward compatibility:
20402   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
20403               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20404   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
20405               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20406 
20407   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
20408   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
20409               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
20410   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
20411               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
20412   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
20413               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
20414   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
20415               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
20416 
20417   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20418   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
20419               FormatStyle::SBPO_Never);
20420   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
20421               FormatStyle::SBPO_Always);
20422   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
20423               FormatStyle::SBPO_ControlStatements);
20424   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
20425               SpaceBeforeParens,
20426               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20427   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
20428               FormatStyle::SBPO_NonEmptyParentheses);
20429   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
20430               FormatStyle::SBPO_Custom);
20431   // For backward compatibility:
20432   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
20433               FormatStyle::SBPO_Never);
20434   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
20435               FormatStyle::SBPO_ControlStatements);
20436   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
20437               SpaceBeforeParens,
20438               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20439 
20440   Style.ColumnLimit = 123;
20441   FormatStyle BaseStyle = getLLVMStyle();
20442   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
20443   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
20444 
20445   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
20446   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
20447               FormatStyle::BS_Attach);
20448   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
20449               FormatStyle::BS_Linux);
20450   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
20451               FormatStyle::BS_Mozilla);
20452   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
20453               FormatStyle::BS_Stroustrup);
20454   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
20455               FormatStyle::BS_Allman);
20456   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
20457               FormatStyle::BS_Whitesmiths);
20458   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
20459   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
20460               FormatStyle::BS_WebKit);
20461   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
20462               FormatStyle::BS_Custom);
20463 
20464   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
20465   CHECK_PARSE("BraceWrapping:\n"
20466               "  AfterControlStatement: MultiLine",
20467               BraceWrapping.AfterControlStatement,
20468               FormatStyle::BWACS_MultiLine);
20469   CHECK_PARSE("BraceWrapping:\n"
20470               "  AfterControlStatement: Always",
20471               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20472   CHECK_PARSE("BraceWrapping:\n"
20473               "  AfterControlStatement: Never",
20474               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20475   // For backward compatibility:
20476   CHECK_PARSE("BraceWrapping:\n"
20477               "  AfterControlStatement: true",
20478               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20479   CHECK_PARSE("BraceWrapping:\n"
20480               "  AfterControlStatement: false",
20481               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20482 
20483   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
20484   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
20485               FormatStyle::RTBS_None);
20486   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
20487               FormatStyle::RTBS_All);
20488   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
20489               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
20490   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
20491               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
20492   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
20493               AlwaysBreakAfterReturnType,
20494               FormatStyle::RTBS_TopLevelDefinitions);
20495 
20496   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20497   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
20498               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
20499   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
20500               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20501   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
20502               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20503   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
20504               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20505   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
20506               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20507 
20508   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
20509   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
20510               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
20511   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
20512               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
20513   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
20514               AlwaysBreakAfterDefinitionReturnType,
20515               FormatStyle::DRTBS_TopLevel);
20516 
20517   Style.NamespaceIndentation = FormatStyle::NI_All;
20518   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
20519               FormatStyle::NI_None);
20520   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
20521               FormatStyle::NI_Inner);
20522   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
20523               FormatStyle::NI_All);
20524 
20525   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
20526   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
20527               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20528   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
20529               AllowShortIfStatementsOnASingleLine,
20530               FormatStyle::SIS_WithoutElse);
20531   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
20532               AllowShortIfStatementsOnASingleLine,
20533               FormatStyle::SIS_OnlyFirstIf);
20534   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
20535               AllowShortIfStatementsOnASingleLine,
20536               FormatStyle::SIS_AllIfsAndElse);
20537   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
20538               AllowShortIfStatementsOnASingleLine,
20539               FormatStyle::SIS_OnlyFirstIf);
20540   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
20541               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20542   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
20543               AllowShortIfStatementsOnASingleLine,
20544               FormatStyle::SIS_WithoutElse);
20545 
20546   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
20547   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
20548               FormatStyle::IEBS_AfterExternBlock);
20549   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
20550               FormatStyle::IEBS_Indent);
20551   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
20552               FormatStyle::IEBS_NoIndent);
20553   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
20554               FormatStyle::IEBS_Indent);
20555   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20556               FormatStyle::IEBS_NoIndent);
20557 
20558   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20559   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20560               FormatStyle::BFCS_Both);
20561   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20562               FormatStyle::BFCS_None);
20563   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20564               FormatStyle::BFCS_Before);
20565   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20566               FormatStyle::BFCS_After);
20567 
20568   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20569   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20570               FormatStyle::SJSIO_After);
20571   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20572               FormatStyle::SJSIO_Before);
20573 
20574   // FIXME: This is required because parsing a configuration simply overwrites
20575   // the first N elements of the list instead of resetting it.
20576   Style.ForEachMacros.clear();
20577   std::vector<std::string> BoostForeach;
20578   BoostForeach.push_back("BOOST_FOREACH");
20579   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20580   std::vector<std::string> BoostAndQForeach;
20581   BoostAndQForeach.push_back("BOOST_FOREACH");
20582   BoostAndQForeach.push_back("Q_FOREACH");
20583   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20584               BoostAndQForeach);
20585 
20586   Style.IfMacros.clear();
20587   std::vector<std::string> CustomIfs;
20588   CustomIfs.push_back("MYIF");
20589   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20590 
20591   Style.AttributeMacros.clear();
20592   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20593               std::vector<std::string>{"__capability"});
20594   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20595               std::vector<std::string>({"attr1", "attr2"}));
20596 
20597   Style.StatementAttributeLikeMacros.clear();
20598   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20599               StatementAttributeLikeMacros,
20600               std::vector<std::string>({"emit", "Q_EMIT"}));
20601 
20602   Style.StatementMacros.clear();
20603   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20604               std::vector<std::string>{"QUNUSED"});
20605   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20606               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20607 
20608   Style.NamespaceMacros.clear();
20609   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20610               std::vector<std::string>{"TESTSUITE"});
20611   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20612               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20613 
20614   Style.WhitespaceSensitiveMacros.clear();
20615   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20616               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20617   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20618               WhitespaceSensitiveMacros,
20619               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20620   Style.WhitespaceSensitiveMacros.clear();
20621   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20622               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20623   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20624               WhitespaceSensitiveMacros,
20625               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20626 
20627   Style.IncludeStyle.IncludeCategories.clear();
20628   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20629       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20630   CHECK_PARSE("IncludeCategories:\n"
20631               "  - Regex: abc/.*\n"
20632               "    Priority: 2\n"
20633               "  - Regex: .*\n"
20634               "    Priority: 1\n"
20635               "    CaseSensitive: true\n",
20636               IncludeStyle.IncludeCategories, ExpectedCategories);
20637   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20638               "abc$");
20639   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20640               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20641 
20642   Style.SortIncludes = FormatStyle::SI_Never;
20643   CHECK_PARSE("SortIncludes: true", SortIncludes,
20644               FormatStyle::SI_CaseSensitive);
20645   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20646   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20647               FormatStyle::SI_CaseInsensitive);
20648   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20649               FormatStyle::SI_CaseSensitive);
20650   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20651 
20652   Style.RawStringFormats.clear();
20653   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20654       {
20655           FormatStyle::LK_TextProto,
20656           {"pb", "proto"},
20657           {"PARSE_TEXT_PROTO"},
20658           /*CanonicalDelimiter=*/"",
20659           "llvm",
20660       },
20661       {
20662           FormatStyle::LK_Cpp,
20663           {"cc", "cpp"},
20664           {"C_CODEBLOCK", "CPPEVAL"},
20665           /*CanonicalDelimiter=*/"cc",
20666           /*BasedOnStyle=*/"",
20667       },
20668   };
20669 
20670   CHECK_PARSE("RawStringFormats:\n"
20671               "  - Language: TextProto\n"
20672               "    Delimiters:\n"
20673               "      - 'pb'\n"
20674               "      - 'proto'\n"
20675               "    EnclosingFunctions:\n"
20676               "      - 'PARSE_TEXT_PROTO'\n"
20677               "    BasedOnStyle: llvm\n"
20678               "  - Language: Cpp\n"
20679               "    Delimiters:\n"
20680               "      - 'cc'\n"
20681               "      - 'cpp'\n"
20682               "    EnclosingFunctions:\n"
20683               "      - 'C_CODEBLOCK'\n"
20684               "      - 'CPPEVAL'\n"
20685               "    CanonicalDelimiter: 'cc'",
20686               RawStringFormats, ExpectedRawStringFormats);
20687 
20688   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20689               "  Minimum: 0\n"
20690               "  Maximum: 0",
20691               SpacesInLineCommentPrefix.Minimum, 0u);
20692   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20693   Style.SpacesInLineCommentPrefix.Minimum = 1;
20694   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20695               "  Minimum: 2",
20696               SpacesInLineCommentPrefix.Minimum, 0u);
20697   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20698               "  Maximum: -1",
20699               SpacesInLineCommentPrefix.Maximum, -1u);
20700   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20701               "  Minimum: 2",
20702               SpacesInLineCommentPrefix.Minimum, 2u);
20703   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20704               "  Maximum: 1",
20705               SpacesInLineCommentPrefix.Maximum, 1u);
20706   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20707 
20708   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20709   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20710   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20711               FormatStyle::SIAS_Always);
20712   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20713   // For backward compatibility:
20714   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20715   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20716 
20717   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20718               FormatStyle::RCPS_WithPreceding);
20719   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20720               FormatStyle::RCPS_WithFollowing);
20721   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20722               FormatStyle::RCPS_SingleLine);
20723   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20724               FormatStyle::RCPS_OwnLine);
20725 
20726   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20727               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20728   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20729               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20730   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20731               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20732   // For backward compatibility:
20733   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20734               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20735   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20736               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20737 }
20738 
20739 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20740   FormatStyle Style = {};
20741   Style.Language = FormatStyle::LK_Cpp;
20742   CHECK_PARSE("Language: Cpp\n"
20743               "IndentWidth: 12",
20744               IndentWidth, 12u);
20745   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20746                                "IndentWidth: 34",
20747                                &Style),
20748             ParseError::Unsuitable);
20749   FormatStyle BinPackedTCS = {};
20750   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20751   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20752                                "InsertTrailingCommas: Wrapped",
20753                                &BinPackedTCS),
20754             ParseError::BinPackTrailingCommaConflict);
20755   EXPECT_EQ(12u, Style.IndentWidth);
20756   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20757   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20758 
20759   Style.Language = FormatStyle::LK_JavaScript;
20760   CHECK_PARSE("Language: JavaScript\n"
20761               "IndentWidth: 12",
20762               IndentWidth, 12u);
20763   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20764   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20765                                "IndentWidth: 34",
20766                                &Style),
20767             ParseError::Unsuitable);
20768   EXPECT_EQ(23u, Style.IndentWidth);
20769   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20770   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20771 
20772   CHECK_PARSE("BasedOnStyle: LLVM\n"
20773               "IndentWidth: 67",
20774               IndentWidth, 67u);
20775 
20776   CHECK_PARSE("---\n"
20777               "Language: JavaScript\n"
20778               "IndentWidth: 12\n"
20779               "---\n"
20780               "Language: Cpp\n"
20781               "IndentWidth: 34\n"
20782               "...\n",
20783               IndentWidth, 12u);
20784 
20785   Style.Language = FormatStyle::LK_Cpp;
20786   CHECK_PARSE("---\n"
20787               "Language: JavaScript\n"
20788               "IndentWidth: 12\n"
20789               "---\n"
20790               "Language: Cpp\n"
20791               "IndentWidth: 34\n"
20792               "...\n",
20793               IndentWidth, 34u);
20794   CHECK_PARSE("---\n"
20795               "IndentWidth: 78\n"
20796               "---\n"
20797               "Language: JavaScript\n"
20798               "IndentWidth: 56\n"
20799               "...\n",
20800               IndentWidth, 78u);
20801 
20802   Style.ColumnLimit = 123;
20803   Style.IndentWidth = 234;
20804   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20805   Style.TabWidth = 345;
20806   EXPECT_FALSE(parseConfiguration("---\n"
20807                                   "IndentWidth: 456\n"
20808                                   "BreakBeforeBraces: Allman\n"
20809                                   "---\n"
20810                                   "Language: JavaScript\n"
20811                                   "IndentWidth: 111\n"
20812                                   "TabWidth: 111\n"
20813                                   "---\n"
20814                                   "Language: Cpp\n"
20815                                   "BreakBeforeBraces: Stroustrup\n"
20816                                   "TabWidth: 789\n"
20817                                   "...\n",
20818                                   &Style));
20819   EXPECT_EQ(123u, Style.ColumnLimit);
20820   EXPECT_EQ(456u, Style.IndentWidth);
20821   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20822   EXPECT_EQ(789u, Style.TabWidth);
20823 
20824   EXPECT_EQ(parseConfiguration("---\n"
20825                                "Language: JavaScript\n"
20826                                "IndentWidth: 56\n"
20827                                "---\n"
20828                                "IndentWidth: 78\n"
20829                                "...\n",
20830                                &Style),
20831             ParseError::Error);
20832   EXPECT_EQ(parseConfiguration("---\n"
20833                                "Language: JavaScript\n"
20834                                "IndentWidth: 56\n"
20835                                "---\n"
20836                                "Language: JavaScript\n"
20837                                "IndentWidth: 78\n"
20838                                "...\n",
20839                                &Style),
20840             ParseError::Error);
20841 
20842   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20843 }
20844 
20845 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20846   FormatStyle Style = {};
20847   Style.Language = FormatStyle::LK_JavaScript;
20848   Style.BreakBeforeTernaryOperators = true;
20849   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20850   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20851 
20852   Style.BreakBeforeTernaryOperators = true;
20853   EXPECT_EQ(0, parseConfiguration("---\n"
20854                                   "BasedOnStyle: Google\n"
20855                                   "---\n"
20856                                   "Language: JavaScript\n"
20857                                   "IndentWidth: 76\n"
20858                                   "...\n",
20859                                   &Style)
20860                    .value());
20861   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20862   EXPECT_EQ(76u, Style.IndentWidth);
20863   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20864 }
20865 
20866 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20867   FormatStyle Style = getLLVMStyle();
20868   std::string YAML = configurationAsText(Style);
20869   FormatStyle ParsedStyle = {};
20870   ParsedStyle.Language = FormatStyle::LK_Cpp;
20871   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20872   EXPECT_EQ(Style, ParsedStyle);
20873 }
20874 
20875 TEST_F(FormatTest, WorksFor8bitEncodings) {
20876   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20877             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20878             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20879             "\"\xef\xee\xf0\xf3...\"",
20880             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20881                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20882                    "\xef\xee\xf0\xf3...\"",
20883                    getLLVMStyleWithColumns(12)));
20884 }
20885 
20886 TEST_F(FormatTest, HandlesUTF8BOM) {
20887   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20888   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20889             format("\xef\xbb\xbf#include <iostream>"));
20890   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20891             format("\xef\xbb\xbf\n#include <iostream>"));
20892 }
20893 
20894 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20895 #if !defined(_MSC_VER)
20896 
20897 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20898   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20899                getLLVMStyleWithColumns(35));
20900   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20901                getLLVMStyleWithColumns(31));
20902   verifyFormat("// Однажды в студёную зимнюю пору...",
20903                getLLVMStyleWithColumns(36));
20904   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20905   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20906                getLLVMStyleWithColumns(39));
20907   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20908                getLLVMStyleWithColumns(35));
20909 }
20910 
20911 TEST_F(FormatTest, SplitsUTF8Strings) {
20912   // Non-printable characters' width is currently considered to be the length in
20913   // bytes in UTF8. The characters can be displayed in very different manner
20914   // (zero-width, single width with a substitution glyph, expanded to their code
20915   // (e.g. "<8d>"), so there's no single correct way to handle them.
20916   EXPECT_EQ("\"aaaaÄ\"\n"
20917             "\"\xc2\x8d\";",
20918             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20919   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20920             "\"\xc2\x8d\";",
20921             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20922   EXPECT_EQ("\"Однажды, в \"\n"
20923             "\"студёную \"\n"
20924             "\"зимнюю \"\n"
20925             "\"пору,\"",
20926             format("\"Однажды, в студёную зимнюю пору,\"",
20927                    getLLVMStyleWithColumns(13)));
20928   EXPECT_EQ(
20929       "\"一 二 三 \"\n"
20930       "\"四 五六 \"\n"
20931       "\"七 八 九 \"\n"
20932       "\"十\"",
20933       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20934   EXPECT_EQ("\"一\t\"\n"
20935             "\"二 \t\"\n"
20936             "\"三 四 \"\n"
20937             "\"五\t\"\n"
20938             "\"六 \t\"\n"
20939             "\"七 \"\n"
20940             "\"八九十\tqq\"",
20941             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20942                    getLLVMStyleWithColumns(11)));
20943 
20944   // UTF8 character in an escape sequence.
20945   EXPECT_EQ("\"aaaaaa\"\n"
20946             "\"\\\xC2\x8D\"",
20947             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20948 }
20949 
20950 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20951   EXPECT_EQ("const char *sssss =\n"
20952             "    \"一二三四五六七八\\\n"
20953             " 九 十\";",
20954             format("const char *sssss = \"一二三四五六七八\\\n"
20955                    " 九 十\";",
20956                    getLLVMStyleWithColumns(30)));
20957 }
20958 
20959 TEST_F(FormatTest, SplitsUTF8LineComments) {
20960   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20961             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20962   EXPECT_EQ("// Я из лесу\n"
20963             "// вышел; был\n"
20964             "// сильный\n"
20965             "// мороз.",
20966             format("// Я из лесу вышел; был сильный мороз.",
20967                    getLLVMStyleWithColumns(13)));
20968   EXPECT_EQ("// 一二三\n"
20969             "// 四五六七\n"
20970             "// 八  九\n"
20971             "// 十",
20972             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20973 }
20974 
20975 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20976   EXPECT_EQ("/* Гляжу,\n"
20977             " * поднимается\n"
20978             " * медленно в\n"
20979             " * гору\n"
20980             " * Лошадка,\n"
20981             " * везущая\n"
20982             " * хворосту\n"
20983             " * воз. */",
20984             format("/* Гляжу, поднимается медленно в гору\n"
20985                    " * Лошадка, везущая хворосту воз. */",
20986                    getLLVMStyleWithColumns(13)));
20987   EXPECT_EQ(
20988       "/* 一二三\n"
20989       " * 四五六七\n"
20990       " * 八  九\n"
20991       " * 十  */",
20992       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20993   EXPECT_EQ("/* �������� ��������\n"
20994             " * ��������\n"
20995             " * ������-�� */",
20996             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20997 }
20998 
20999 #endif // _MSC_VER
21000 
21001 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
21002   FormatStyle Style = getLLVMStyle();
21003 
21004   Style.ConstructorInitializerIndentWidth = 4;
21005   verifyFormat(
21006       "SomeClass::Constructor()\n"
21007       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
21008       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
21009       Style);
21010 
21011   Style.ConstructorInitializerIndentWidth = 2;
21012   verifyFormat(
21013       "SomeClass::Constructor()\n"
21014       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
21015       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
21016       Style);
21017 
21018   Style.ConstructorInitializerIndentWidth = 0;
21019   verifyFormat(
21020       "SomeClass::Constructor()\n"
21021       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
21022       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
21023       Style);
21024   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
21025   verifyFormat(
21026       "SomeLongTemplateVariableName<\n"
21027       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
21028       Style);
21029   verifyFormat("bool smaller = 1 < "
21030                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
21031                "                       "
21032                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
21033                Style);
21034 
21035   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
21036   verifyFormat("SomeClass::Constructor() :\n"
21037                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
21038                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
21039                Style);
21040 }
21041 
21042 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
21043   FormatStyle Style = getLLVMStyle();
21044   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
21045   Style.ConstructorInitializerIndentWidth = 4;
21046   verifyFormat("SomeClass::Constructor()\n"
21047                "    : a(a)\n"
21048                "    , b(b)\n"
21049                "    , c(c) {}",
21050                Style);
21051   verifyFormat("SomeClass::Constructor()\n"
21052                "    : a(a) {}",
21053                Style);
21054 
21055   Style.ColumnLimit = 0;
21056   verifyFormat("SomeClass::Constructor()\n"
21057                "    : a(a) {}",
21058                Style);
21059   verifyFormat("SomeClass::Constructor() noexcept\n"
21060                "    : a(a) {}",
21061                Style);
21062   verifyFormat("SomeClass::Constructor()\n"
21063                "    : a(a)\n"
21064                "    , b(b)\n"
21065                "    , c(c) {}",
21066                Style);
21067   verifyFormat("SomeClass::Constructor()\n"
21068                "    : a(a) {\n"
21069                "  foo();\n"
21070                "  bar();\n"
21071                "}",
21072                Style);
21073 
21074   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
21075   verifyFormat("SomeClass::Constructor()\n"
21076                "    : a(a)\n"
21077                "    , b(b)\n"
21078                "    , c(c) {\n}",
21079                Style);
21080   verifyFormat("SomeClass::Constructor()\n"
21081                "    : a(a) {\n}",
21082                Style);
21083 
21084   Style.ColumnLimit = 80;
21085   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
21086   Style.ConstructorInitializerIndentWidth = 2;
21087   verifyFormat("SomeClass::Constructor()\n"
21088                "  : a(a)\n"
21089                "  , b(b)\n"
21090                "  , c(c) {}",
21091                Style);
21092 
21093   Style.ConstructorInitializerIndentWidth = 0;
21094   verifyFormat("SomeClass::Constructor()\n"
21095                ": a(a)\n"
21096                ", b(b)\n"
21097                ", c(c) {}",
21098                Style);
21099 
21100   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
21101   Style.ConstructorInitializerIndentWidth = 4;
21102   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
21103   verifyFormat(
21104       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
21105       Style);
21106   verifyFormat(
21107       "SomeClass::Constructor()\n"
21108       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
21109       Style);
21110   Style.ConstructorInitializerIndentWidth = 4;
21111   Style.ColumnLimit = 60;
21112   verifyFormat("SomeClass::Constructor()\n"
21113                "    : aaaaaaaa(aaaaaaaa)\n"
21114                "    , aaaaaaaa(aaaaaaaa)\n"
21115                "    , aaaaaaaa(aaaaaaaa) {}",
21116                Style);
21117 }
21118 
21119 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
21120   FormatStyle Style = getLLVMStyle();
21121   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
21122   Style.ConstructorInitializerIndentWidth = 4;
21123   verifyFormat("SomeClass::Constructor()\n"
21124                "    : a{a}\n"
21125                "    , b{b} {}",
21126                Style);
21127   verifyFormat("SomeClass::Constructor()\n"
21128                "    : a{a}\n"
21129                "#if CONDITION\n"
21130                "    , b{b}\n"
21131                "#endif\n"
21132                "{\n}",
21133                Style);
21134   Style.ConstructorInitializerIndentWidth = 2;
21135   verifyFormat("SomeClass::Constructor()\n"
21136                "#if CONDITION\n"
21137                "  : a{a}\n"
21138                "#endif\n"
21139                "  , b{b}\n"
21140                "  , c{c} {\n}",
21141                Style);
21142   Style.ConstructorInitializerIndentWidth = 0;
21143   verifyFormat("SomeClass::Constructor()\n"
21144                ": a{a}\n"
21145                "#ifdef CONDITION\n"
21146                ", b{b}\n"
21147                "#else\n"
21148                ", c{c}\n"
21149                "#endif\n"
21150                ", d{d} {\n}",
21151                Style);
21152   Style.ConstructorInitializerIndentWidth = 4;
21153   verifyFormat("SomeClass::Constructor()\n"
21154                "    : a{a}\n"
21155                "#if WINDOWS\n"
21156                "#if DEBUG\n"
21157                "    , b{0}\n"
21158                "#else\n"
21159                "    , b{1}\n"
21160                "#endif\n"
21161                "#else\n"
21162                "#if DEBUG\n"
21163                "    , b{2}\n"
21164                "#else\n"
21165                "    , b{3}\n"
21166                "#endif\n"
21167                "#endif\n"
21168                "{\n}",
21169                Style);
21170   verifyFormat("SomeClass::Constructor()\n"
21171                "    : a{a}\n"
21172                "#if WINDOWS\n"
21173                "    , b{0}\n"
21174                "#if DEBUG\n"
21175                "    , c{0}\n"
21176                "#else\n"
21177                "    , c{1}\n"
21178                "#endif\n"
21179                "#else\n"
21180                "#if DEBUG\n"
21181                "    , c{2}\n"
21182                "#else\n"
21183                "    , c{3}\n"
21184                "#endif\n"
21185                "    , b{1}\n"
21186                "#endif\n"
21187                "{\n}",
21188                Style);
21189 }
21190 
21191 TEST_F(FormatTest, Destructors) {
21192   verifyFormat("void F(int &i) { i.~int(); }");
21193   verifyFormat("void F(int &i) { i->~int(); }");
21194 }
21195 
21196 TEST_F(FormatTest, FormatsWithWebKitStyle) {
21197   FormatStyle Style = getWebKitStyle();
21198 
21199   // Don't indent in outer namespaces.
21200   verifyFormat("namespace outer {\n"
21201                "int i;\n"
21202                "namespace inner {\n"
21203                "    int i;\n"
21204                "} // namespace inner\n"
21205                "} // namespace outer\n"
21206                "namespace other_outer {\n"
21207                "int i;\n"
21208                "}",
21209                Style);
21210 
21211   // Don't indent case labels.
21212   verifyFormat("switch (variable) {\n"
21213                "case 1:\n"
21214                "case 2:\n"
21215                "    doSomething();\n"
21216                "    break;\n"
21217                "default:\n"
21218                "    ++variable;\n"
21219                "}",
21220                Style);
21221 
21222   // Wrap before binary operators.
21223   EXPECT_EQ("void f()\n"
21224             "{\n"
21225             "    if (aaaaaaaaaaaaaaaa\n"
21226             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
21227             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21228             "        return;\n"
21229             "}",
21230             format("void f() {\n"
21231                    "if (aaaaaaaaaaaaaaaa\n"
21232                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
21233                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21234                    "return;\n"
21235                    "}",
21236                    Style));
21237 
21238   // Allow functions on a single line.
21239   verifyFormat("void f() { return; }", Style);
21240 
21241   // Allow empty blocks on a single line and insert a space in empty blocks.
21242   EXPECT_EQ("void f() { }", format("void f() {}", Style));
21243   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
21244   // However, don't merge non-empty short loops.
21245   EXPECT_EQ("while (true) {\n"
21246             "    continue;\n"
21247             "}",
21248             format("while (true) { continue; }", Style));
21249 
21250   // Constructor initializers are formatted one per line with the "," on the
21251   // new line.
21252   verifyFormat("Constructor()\n"
21253                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
21254                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
21255                "          aaaaaaaaaaaaaa)\n"
21256                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
21257                "{\n"
21258                "}",
21259                Style);
21260   verifyFormat("SomeClass::Constructor()\n"
21261                "    : a(a)\n"
21262                "{\n"
21263                "}",
21264                Style);
21265   EXPECT_EQ("SomeClass::Constructor()\n"
21266             "    : a(a)\n"
21267             "{\n"
21268             "}",
21269             format("SomeClass::Constructor():a(a){}", Style));
21270   verifyFormat("SomeClass::Constructor()\n"
21271                "    : a(a)\n"
21272                "    , b(b)\n"
21273                "    , c(c)\n"
21274                "{\n"
21275                "}",
21276                Style);
21277   verifyFormat("SomeClass::Constructor()\n"
21278                "    : a(a)\n"
21279                "{\n"
21280                "    foo();\n"
21281                "    bar();\n"
21282                "}",
21283                Style);
21284 
21285   // Access specifiers should be aligned left.
21286   verifyFormat("class C {\n"
21287                "public:\n"
21288                "    int i;\n"
21289                "};",
21290                Style);
21291 
21292   // Do not align comments.
21293   verifyFormat("int a; // Do not\n"
21294                "double b; // align comments.",
21295                Style);
21296 
21297   // Do not align operands.
21298   EXPECT_EQ("ASSERT(aaaa\n"
21299             "    || bbbb);",
21300             format("ASSERT ( aaaa\n||bbbb);", Style));
21301 
21302   // Accept input's line breaks.
21303   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
21304             "    || bbbbbbbbbbbbbbb) {\n"
21305             "    i++;\n"
21306             "}",
21307             format("if (aaaaaaaaaaaaaaa\n"
21308                    "|| bbbbbbbbbbbbbbb) { i++; }",
21309                    Style));
21310   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
21311             "    i++;\n"
21312             "}",
21313             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
21314 
21315   // Don't automatically break all macro definitions (llvm.org/PR17842).
21316   verifyFormat("#define aNumber 10", Style);
21317   // However, generally keep the line breaks that the user authored.
21318   EXPECT_EQ("#define aNumber \\\n"
21319             "    10",
21320             format("#define aNumber \\\n"
21321                    " 10",
21322                    Style));
21323 
21324   // Keep empty and one-element array literals on a single line.
21325   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
21326             "                                  copyItems:YES];",
21327             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
21328                    "copyItems:YES];",
21329                    Style));
21330   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
21331             "                                  copyItems:YES];",
21332             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
21333                    "             copyItems:YES];",
21334                    Style));
21335   // FIXME: This does not seem right, there should be more indentation before
21336   // the array literal's entries. Nested blocks have the same problem.
21337   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21338             "    @\"a\",\n"
21339             "    @\"a\"\n"
21340             "]\n"
21341             "                                  copyItems:YES];",
21342             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21343                    "     @\"a\",\n"
21344                    "     @\"a\"\n"
21345                    "     ]\n"
21346                    "       copyItems:YES];",
21347                    Style));
21348   EXPECT_EQ(
21349       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21350       "                                  copyItems:YES];",
21351       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21352              "   copyItems:YES];",
21353              Style));
21354 
21355   verifyFormat("[self.a b:c c:d];", Style);
21356   EXPECT_EQ("[self.a b:c\n"
21357             "        c:d];",
21358             format("[self.a b:c\n"
21359                    "c:d];",
21360                    Style));
21361 }
21362 
21363 TEST_F(FormatTest, FormatsLambdas) {
21364   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
21365   verifyFormat(
21366       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
21367   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
21368   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
21369   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
21370   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
21371   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
21372   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
21373   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
21374   verifyFormat("int x = f(*+[] {});");
21375   verifyFormat("void f() {\n"
21376                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
21377                "}\n");
21378   verifyFormat("void f() {\n"
21379                "  other(x.begin(), //\n"
21380                "        x.end(),   //\n"
21381                "        [&](int, int) { return 1; });\n"
21382                "}\n");
21383   verifyFormat("void f() {\n"
21384                "  other.other.other.other.other(\n"
21385                "      x.begin(), x.end(),\n"
21386                "      [something, rather](int, int, int, int, int, int, int) { "
21387                "return 1; });\n"
21388                "}\n");
21389   verifyFormat(
21390       "void f() {\n"
21391       "  other.other.other.other.other(\n"
21392       "      x.begin(), x.end(),\n"
21393       "      [something, rather](int, int, int, int, int, int, int) {\n"
21394       "        //\n"
21395       "      });\n"
21396       "}\n");
21397   verifyFormat("SomeFunction([]() { // A cool function...\n"
21398                "  return 43;\n"
21399                "});");
21400   EXPECT_EQ("SomeFunction([]() {\n"
21401             "#define A a\n"
21402             "  return 43;\n"
21403             "});",
21404             format("SomeFunction([](){\n"
21405                    "#define A a\n"
21406                    "return 43;\n"
21407                    "});"));
21408   verifyFormat("void f() {\n"
21409                "  SomeFunction([](decltype(x), A *a) {});\n"
21410                "  SomeFunction([](typeof(x), A *a) {});\n"
21411                "  SomeFunction([](_Atomic(x), A *a) {});\n"
21412                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
21413                "}");
21414   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21415                "    [](const aaaaaaaaaa &a) { return a; });");
21416   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
21417                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
21418                "});");
21419   verifyFormat("Constructor()\n"
21420                "    : Field([] { // comment\n"
21421                "        int i;\n"
21422                "      }) {}");
21423   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
21424                "  return some_parameter.size();\n"
21425                "};");
21426   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
21427                "    [](const string &s) { return s; };");
21428   verifyFormat("int i = aaaaaa ? 1 //\n"
21429                "               : [] {\n"
21430                "                   return 2; //\n"
21431                "                 }();");
21432   verifyFormat("llvm::errs() << \"number of twos is \"\n"
21433                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
21434                "                  return x == 2; // force break\n"
21435                "                });");
21436   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21437                "    [=](int iiiiiiiiiiii) {\n"
21438                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
21439                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
21440                "    });",
21441                getLLVMStyleWithColumns(60));
21442 
21443   verifyFormat("SomeFunction({[&] {\n"
21444                "                // comment\n"
21445                "              },\n"
21446                "              [&] {\n"
21447                "                // comment\n"
21448                "              }});");
21449   verifyFormat("SomeFunction({[&] {\n"
21450                "  // comment\n"
21451                "}});");
21452   verifyFormat(
21453       "virtual aaaaaaaaaaaaaaaa(\n"
21454       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
21455       "    aaaaa aaaaaaaaa);");
21456 
21457   // Lambdas with return types.
21458   verifyFormat("int c = []() -> int { return 2; }();\n");
21459   verifyFormat("int c = []() -> int * { return 2; }();\n");
21460   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
21461   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
21462   verifyFormat("foo([]() noexcept -> int {});");
21463   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
21464   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
21465   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
21466   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
21467   verifyFormat("[a, a]() -> a<1> {};");
21468   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
21469   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
21470   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
21471   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
21472   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
21473   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
21474   verifyFormat("[]() -> foo<!5> { return {}; };");
21475   verifyFormat("[]() -> foo<~5> { return {}; };");
21476   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
21477   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
21478   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
21479   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
21480   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
21481   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
21482   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
21483   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
21484   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
21485   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
21486   verifyFormat("namespace bar {\n"
21487                "// broken:\n"
21488                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
21489                "} // namespace bar");
21490   verifyFormat("namespace bar {\n"
21491                "// broken:\n"
21492                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
21493                "} // namespace bar");
21494   verifyFormat("namespace bar {\n"
21495                "// broken:\n"
21496                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
21497                "} // namespace bar");
21498   verifyFormat("namespace bar {\n"
21499                "// broken:\n"
21500                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
21501                "} // namespace bar");
21502   verifyFormat("namespace bar {\n"
21503                "// broken:\n"
21504                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
21505                "} // namespace bar");
21506   verifyFormat("namespace bar {\n"
21507                "// broken:\n"
21508                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
21509                "} // namespace bar");
21510   verifyFormat("namespace bar {\n"
21511                "// broken:\n"
21512                "auto foo{[]() -> foo<!5> { return {}; }};\n"
21513                "} // namespace bar");
21514   verifyFormat("namespace bar {\n"
21515                "// broken:\n"
21516                "auto foo{[]() -> foo<~5> { return {}; }};\n"
21517                "} // namespace bar");
21518   verifyFormat("namespace bar {\n"
21519                "// broken:\n"
21520                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
21521                "} // namespace bar");
21522   verifyFormat("namespace bar {\n"
21523                "// broken:\n"
21524                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
21525                "} // namespace bar");
21526   verifyFormat("namespace bar {\n"
21527                "// broken:\n"
21528                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
21529                "} // namespace bar");
21530   verifyFormat("namespace bar {\n"
21531                "// broken:\n"
21532                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
21533                "} // namespace bar");
21534   verifyFormat("namespace bar {\n"
21535                "// broken:\n"
21536                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
21537                "} // namespace bar");
21538   verifyFormat("namespace bar {\n"
21539                "// broken:\n"
21540                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
21541                "} // namespace bar");
21542   verifyFormat("namespace bar {\n"
21543                "// broken:\n"
21544                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
21545                "} // namespace bar");
21546   verifyFormat("namespace bar {\n"
21547                "// broken:\n"
21548                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
21549                "} // namespace bar");
21550   verifyFormat("namespace bar {\n"
21551                "// broken:\n"
21552                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
21553                "} // namespace bar");
21554   verifyFormat("namespace bar {\n"
21555                "// broken:\n"
21556                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21557                "} // namespace bar");
21558   verifyFormat("[]() -> a<1> {};");
21559   verifyFormat("[]() -> a<1> { ; };");
21560   verifyFormat("[]() -> a<1> { ; }();");
21561   verifyFormat("[a, a]() -> a<true> {};");
21562   verifyFormat("[]() -> a<true> {};");
21563   verifyFormat("[]() -> a<true> { ; };");
21564   verifyFormat("[]() -> a<true> { ; }();");
21565   verifyFormat("[a, a]() -> a<false> {};");
21566   verifyFormat("[]() -> a<false> {};");
21567   verifyFormat("[]() -> a<false> { ; };");
21568   verifyFormat("[]() -> a<false> { ; }();");
21569   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21570   verifyFormat("namespace bar {\n"
21571                "auto foo{[]() -> foo<false> { ; }};\n"
21572                "} // namespace bar");
21573   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21574                "                   int j) -> int {\n"
21575                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21576                "};");
21577   verifyFormat(
21578       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21579       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21580       "      return aaaaaaaaaaaaaaaaa;\n"
21581       "    });",
21582       getLLVMStyleWithColumns(70));
21583   verifyFormat("[]() //\n"
21584                "    -> int {\n"
21585                "  return 1; //\n"
21586                "};");
21587   verifyFormat("[]() -> Void<T...> {};");
21588   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21589   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21590   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21591   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21592   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21593   verifyFormat("return int{[x = x]() { return x; }()};");
21594 
21595   // Lambdas with explicit template argument lists.
21596   verifyFormat(
21597       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21598   verifyFormat("auto L = []<class T>(T) {\n"
21599                "  {\n"
21600                "    f();\n"
21601                "    g();\n"
21602                "  }\n"
21603                "};\n");
21604   verifyFormat("auto L = []<class... T>(T...) {\n"
21605                "  {\n"
21606                "    f();\n"
21607                "    g();\n"
21608                "  }\n"
21609                "};\n");
21610   verifyFormat("auto L = []<typename... T>(T...) {\n"
21611                "  {\n"
21612                "    f();\n"
21613                "    g();\n"
21614                "  }\n"
21615                "};\n");
21616   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21617                "  {\n"
21618                "    f();\n"
21619                "    g();\n"
21620                "  }\n"
21621                "};\n");
21622   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21623                "  {\n"
21624                "    f();\n"
21625                "    g();\n"
21626                "  }\n"
21627                "};\n");
21628 
21629   // Multiple lambdas in the same parentheses change indentation rules. These
21630   // lambdas are forced to start on new lines.
21631   verifyFormat("SomeFunction(\n"
21632                "    []() {\n"
21633                "      //\n"
21634                "    },\n"
21635                "    []() {\n"
21636                "      //\n"
21637                "    });");
21638 
21639   // A lambda passed as arg0 is always pushed to the next line.
21640   verifyFormat("SomeFunction(\n"
21641                "    [this] {\n"
21642                "      //\n"
21643                "    },\n"
21644                "    1);\n");
21645 
21646   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21647   // the arg0 case above.
21648   auto Style = getGoogleStyle();
21649   Style.BinPackArguments = false;
21650   verifyFormat("SomeFunction(\n"
21651                "    a,\n"
21652                "    [this] {\n"
21653                "      //\n"
21654                "    },\n"
21655                "    b);\n",
21656                Style);
21657   verifyFormat("SomeFunction(\n"
21658                "    a,\n"
21659                "    [this] {\n"
21660                "      //\n"
21661                "    },\n"
21662                "    b);\n");
21663 
21664   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21665   // the BinPackArguments value (as long as the code is wide enough).
21666   verifyFormat(
21667       "something->SomeFunction(\n"
21668       "    a,\n"
21669       "    [this] {\n"
21670       "      "
21671       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21672       "    },\n"
21673       "    b);\n");
21674 
21675   // A multi-line lambda is pulled up as long as the introducer fits on the
21676   // previous line and there are no further args.
21677   verifyFormat("function(1, [this, that] {\n"
21678                "  //\n"
21679                "});\n");
21680   verifyFormat("function([this, that] {\n"
21681                "  //\n"
21682                "});\n");
21683   // FIXME: this format is not ideal and we should consider forcing the first
21684   // arg onto its own line.
21685   verifyFormat("function(a, b, c, //\n"
21686                "         d, [this, that] {\n"
21687                "           //\n"
21688                "         });\n");
21689 
21690   // Multiple lambdas are treated correctly even when there is a short arg0.
21691   verifyFormat("SomeFunction(\n"
21692                "    1,\n"
21693                "    [this] {\n"
21694                "      //\n"
21695                "    },\n"
21696                "    [this] {\n"
21697                "      //\n"
21698                "    },\n"
21699                "    1);\n");
21700 
21701   // More complex introducers.
21702   verifyFormat("return [i, args...] {};");
21703 
21704   // Not lambdas.
21705   verifyFormat("constexpr char hello[]{\"hello\"};");
21706   verifyFormat("double &operator[](int i) { return 0; }\n"
21707                "int i;");
21708   verifyFormat("std::unique_ptr<int[]> foo() {}");
21709   verifyFormat("int i = a[a][a]->f();");
21710   verifyFormat("int i = (*b)[a]->f();");
21711 
21712   // Other corner cases.
21713   verifyFormat("void f() {\n"
21714                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21715                "  );\n"
21716                "}");
21717   verifyFormat("auto k = *[](int *j) { return j; }(&i);");
21718 
21719   // Lambdas created through weird macros.
21720   verifyFormat("void f() {\n"
21721                "  MACRO((const AA &a) { return 1; });\n"
21722                "  MACRO((AA &a) { return 1; });\n"
21723                "}");
21724 
21725   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21726                "      doo_dah();\n"
21727                "      doo_dah();\n"
21728                "    })) {\n"
21729                "}");
21730   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21731                "                doo_dah();\n"
21732                "                doo_dah();\n"
21733                "              })) {\n"
21734                "}");
21735   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21736                "                doo_dah();\n"
21737                "                doo_dah();\n"
21738                "              })) {\n"
21739                "}");
21740   verifyFormat("auto lambda = []() {\n"
21741                "  int a = 2\n"
21742                "#if A\n"
21743                "          + 2\n"
21744                "#endif\n"
21745                "      ;\n"
21746                "};");
21747 
21748   // Lambdas with complex multiline introducers.
21749   verifyFormat(
21750       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21751       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21752       "        -> ::std::unordered_set<\n"
21753       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21754       "      //\n"
21755       "    });");
21756 
21757   FormatStyle DoNotMerge = getLLVMStyle();
21758   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21759   verifyFormat("auto c = []() {\n"
21760                "  return b;\n"
21761                "};",
21762                "auto c = []() { return b; };", DoNotMerge);
21763   verifyFormat("auto c = []() {\n"
21764                "};",
21765                " auto c = []() {};", DoNotMerge);
21766 
21767   FormatStyle MergeEmptyOnly = getLLVMStyle();
21768   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21769   verifyFormat("auto c = []() {\n"
21770                "  return b;\n"
21771                "};",
21772                "auto c = []() {\n"
21773                "  return b;\n"
21774                " };",
21775                MergeEmptyOnly);
21776   verifyFormat("auto c = []() {};",
21777                "auto c = []() {\n"
21778                "};",
21779                MergeEmptyOnly);
21780 
21781   FormatStyle MergeInline = getLLVMStyle();
21782   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21783   verifyFormat("auto c = []() {\n"
21784                "  return b;\n"
21785                "};",
21786                "auto c = []() { return b; };", MergeInline);
21787   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21788                MergeInline);
21789   verifyFormat("function([]() { return b; }, a)",
21790                "function([]() { return b; }, a)", MergeInline);
21791   verifyFormat("function(a, []() { return b; })",
21792                "function(a, []() { return b; })", MergeInline);
21793 
21794   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21795   // AllowShortLambdasOnASingleLine
21796   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21797   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21798   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21799   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21800       FormatStyle::ShortLambdaStyle::SLS_None;
21801   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21802                "    []()\n"
21803                "    {\n"
21804                "      return 17;\n"
21805                "    });",
21806                LLVMWithBeforeLambdaBody);
21807   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21808                "    []()\n"
21809                "    {\n"
21810                "    });",
21811                LLVMWithBeforeLambdaBody);
21812   verifyFormat("auto fct_SLS_None = []()\n"
21813                "{\n"
21814                "  return 17;\n"
21815                "};",
21816                LLVMWithBeforeLambdaBody);
21817   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21818                "    []()\n"
21819                "    {\n"
21820                "      return Call(\n"
21821                "          []()\n"
21822                "          {\n"
21823                "            return 17;\n"
21824                "          });\n"
21825                "    });",
21826                LLVMWithBeforeLambdaBody);
21827   verifyFormat("void Fct() {\n"
21828                "  return {[]()\n"
21829                "          {\n"
21830                "            return 17;\n"
21831                "          }};\n"
21832                "}",
21833                LLVMWithBeforeLambdaBody);
21834 
21835   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21836       FormatStyle::ShortLambdaStyle::SLS_Empty;
21837   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21838                "    []()\n"
21839                "    {\n"
21840                "      return 17;\n"
21841                "    });",
21842                LLVMWithBeforeLambdaBody);
21843   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21844                LLVMWithBeforeLambdaBody);
21845   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21846                "ongFunctionName_SLS_Empty(\n"
21847                "    []() {});",
21848                LLVMWithBeforeLambdaBody);
21849   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21850                "                                []()\n"
21851                "                                {\n"
21852                "                                  return 17;\n"
21853                "                                });",
21854                LLVMWithBeforeLambdaBody);
21855   verifyFormat("auto fct_SLS_Empty = []()\n"
21856                "{\n"
21857                "  return 17;\n"
21858                "};",
21859                LLVMWithBeforeLambdaBody);
21860   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21861                "    []()\n"
21862                "    {\n"
21863                "      return Call([]() {});\n"
21864                "    });",
21865                LLVMWithBeforeLambdaBody);
21866   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21867                "                           []()\n"
21868                "                           {\n"
21869                "                             return Call([]() {});\n"
21870                "                           });",
21871                LLVMWithBeforeLambdaBody);
21872   verifyFormat(
21873       "FctWithLongLineInLambda_SLS_Empty(\n"
21874       "    []()\n"
21875       "    {\n"
21876       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21877       "                               AndShouldNotBeConsiderAsInline,\n"
21878       "                               LambdaBodyMustBeBreak);\n"
21879       "    });",
21880       LLVMWithBeforeLambdaBody);
21881 
21882   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21883       FormatStyle::ShortLambdaStyle::SLS_Inline;
21884   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21885                LLVMWithBeforeLambdaBody);
21886   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21887                LLVMWithBeforeLambdaBody);
21888   verifyFormat("auto fct_SLS_Inline = []()\n"
21889                "{\n"
21890                "  return 17;\n"
21891                "};",
21892                LLVMWithBeforeLambdaBody);
21893   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21894                "17; }); });",
21895                LLVMWithBeforeLambdaBody);
21896   verifyFormat(
21897       "FctWithLongLineInLambda_SLS_Inline(\n"
21898       "    []()\n"
21899       "    {\n"
21900       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21901       "                               AndShouldNotBeConsiderAsInline,\n"
21902       "                               LambdaBodyMustBeBreak);\n"
21903       "    });",
21904       LLVMWithBeforeLambdaBody);
21905   verifyFormat("FctWithMultipleParams_SLS_Inline("
21906                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21907                "                                 []() { return 17; });",
21908                LLVMWithBeforeLambdaBody);
21909   verifyFormat(
21910       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21911       LLVMWithBeforeLambdaBody);
21912 
21913   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21914       FormatStyle::ShortLambdaStyle::SLS_All;
21915   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21916                LLVMWithBeforeLambdaBody);
21917   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21918                LLVMWithBeforeLambdaBody);
21919   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21920                LLVMWithBeforeLambdaBody);
21921   verifyFormat("FctWithOneParam_SLS_All(\n"
21922                "    []()\n"
21923                "    {\n"
21924                "      // A cool function...\n"
21925                "      return 43;\n"
21926                "    });",
21927                LLVMWithBeforeLambdaBody);
21928   verifyFormat("FctWithMultipleParams_SLS_All("
21929                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21930                "                              []() { return 17; });",
21931                LLVMWithBeforeLambdaBody);
21932   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21933                LLVMWithBeforeLambdaBody);
21934   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21935                LLVMWithBeforeLambdaBody);
21936   verifyFormat(
21937       "FctWithLongLineInLambda_SLS_All(\n"
21938       "    []()\n"
21939       "    {\n"
21940       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21941       "                               AndShouldNotBeConsiderAsInline,\n"
21942       "                               LambdaBodyMustBeBreak);\n"
21943       "    });",
21944       LLVMWithBeforeLambdaBody);
21945   verifyFormat(
21946       "auto fct_SLS_All = []()\n"
21947       "{\n"
21948       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21949       "                           AndShouldNotBeConsiderAsInline,\n"
21950       "                           LambdaBodyMustBeBreak);\n"
21951       "};",
21952       LLVMWithBeforeLambdaBody);
21953   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21954   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21955                LLVMWithBeforeLambdaBody);
21956   verifyFormat(
21957       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21958       "                                FirstParam,\n"
21959       "                                SecondParam,\n"
21960       "                                ThirdParam,\n"
21961       "                                FourthParam);",
21962       LLVMWithBeforeLambdaBody);
21963   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21964                "    []() { return "
21965                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21966                "    FirstParam,\n"
21967                "    SecondParam,\n"
21968                "    ThirdParam,\n"
21969                "    FourthParam);",
21970                LLVMWithBeforeLambdaBody);
21971   verifyFormat(
21972       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21973       "                                SecondParam,\n"
21974       "                                ThirdParam,\n"
21975       "                                FourthParam,\n"
21976       "                                []() { return SomeValueNotSoLong; });",
21977       LLVMWithBeforeLambdaBody);
21978   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21979                "    []()\n"
21980                "    {\n"
21981                "      return "
21982                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21983                "eConsiderAsInline;\n"
21984                "    });",
21985                LLVMWithBeforeLambdaBody);
21986   verifyFormat(
21987       "FctWithLongLineInLambda_SLS_All(\n"
21988       "    []()\n"
21989       "    {\n"
21990       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21991       "                               AndShouldNotBeConsiderAsInline,\n"
21992       "                               LambdaBodyMustBeBreak);\n"
21993       "    });",
21994       LLVMWithBeforeLambdaBody);
21995   verifyFormat("FctWithTwoParams_SLS_All(\n"
21996                "    []()\n"
21997                "    {\n"
21998                "      // A cool function...\n"
21999                "      return 43;\n"
22000                "    },\n"
22001                "    87);",
22002                LLVMWithBeforeLambdaBody);
22003   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
22004                LLVMWithBeforeLambdaBody);
22005   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
22006                LLVMWithBeforeLambdaBody);
22007   verifyFormat(
22008       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
22009       LLVMWithBeforeLambdaBody);
22010   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
22011                "}); }, x);",
22012                LLVMWithBeforeLambdaBody);
22013   verifyFormat("TwoNestedLambdas_SLS_All(\n"
22014                "    []()\n"
22015                "    {\n"
22016                "      // A cool function...\n"
22017                "      return Call([]() { return 17; });\n"
22018                "    });",
22019                LLVMWithBeforeLambdaBody);
22020   verifyFormat("TwoNestedLambdas_SLS_All(\n"
22021                "    []()\n"
22022                "    {\n"
22023                "      return Call(\n"
22024                "          []()\n"
22025                "          {\n"
22026                "            // A cool function...\n"
22027                "            return 17;\n"
22028                "          });\n"
22029                "    });",
22030                LLVMWithBeforeLambdaBody);
22031 
22032   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
22033       FormatStyle::ShortLambdaStyle::SLS_None;
22034 
22035   verifyFormat("auto select = [this]() -> const Library::Object *\n"
22036                "{\n"
22037                "  return MyAssignment::SelectFromList(this);\n"
22038                "};\n",
22039                LLVMWithBeforeLambdaBody);
22040 
22041   verifyFormat("auto select = [this]() -> const Library::Object &\n"
22042                "{\n"
22043                "  return MyAssignment::SelectFromList(this);\n"
22044                "};\n",
22045                LLVMWithBeforeLambdaBody);
22046 
22047   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
22048                "{\n"
22049                "  return MyAssignment::SelectFromList(this);\n"
22050                "};\n",
22051                LLVMWithBeforeLambdaBody);
22052 
22053   verifyFormat("namespace test {\n"
22054                "class Test {\n"
22055                "public:\n"
22056                "  Test() = default;\n"
22057                "};\n"
22058                "} // namespace test",
22059                LLVMWithBeforeLambdaBody);
22060 
22061   // Lambdas with different indentation styles.
22062   Style = getLLVMStyleWithColumns(100);
22063   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
22064             "  return promise.then(\n"
22065             "      [this, &someVariable, someObject = "
22066             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22067             "        return someObject.startAsyncAction().then(\n"
22068             "            [this, &someVariable](AsyncActionResult result) "
22069             "mutable { result.processMore(); });\n"
22070             "      });\n"
22071             "}\n",
22072             format("SomeResult doSomething(SomeObject promise) {\n"
22073                    "  return promise.then([this, &someVariable, someObject = "
22074                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22075                    "    return someObject.startAsyncAction().then([this, "
22076                    "&someVariable](AsyncActionResult result) mutable {\n"
22077                    "      result.processMore();\n"
22078                    "    });\n"
22079                    "  });\n"
22080                    "}\n",
22081                    Style));
22082   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
22083   verifyFormat("test() {\n"
22084                "  ([]() -> {\n"
22085                "    int b = 32;\n"
22086                "    return 3;\n"
22087                "  }).foo();\n"
22088                "}",
22089                Style);
22090   verifyFormat("test() {\n"
22091                "  []() -> {\n"
22092                "    int b = 32;\n"
22093                "    return 3;\n"
22094                "  }\n"
22095                "}",
22096                Style);
22097   verifyFormat("std::sort(v.begin(), v.end(),\n"
22098                "          [](const auto &someLongArgumentName, const auto "
22099                "&someOtherLongArgumentName) {\n"
22100                "  return someLongArgumentName.someMemberVariable < "
22101                "someOtherLongArgumentName.someMemberVariable;\n"
22102                "});",
22103                Style);
22104   verifyFormat("test() {\n"
22105                "  (\n"
22106                "      []() -> {\n"
22107                "        int b = 32;\n"
22108                "        return 3;\n"
22109                "      },\n"
22110                "      foo, bar)\n"
22111                "      .foo();\n"
22112                "}",
22113                Style);
22114   verifyFormat("test() {\n"
22115                "  ([]() -> {\n"
22116                "    int b = 32;\n"
22117                "    return 3;\n"
22118                "  })\n"
22119                "      .foo()\n"
22120                "      .bar();\n"
22121                "}",
22122                Style);
22123   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
22124             "  return promise.then(\n"
22125             "      [this, &someVariable, someObject = "
22126             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22127             "    return someObject.startAsyncAction().then(\n"
22128             "        [this, &someVariable](AsyncActionResult result) mutable { "
22129             "result.processMore(); });\n"
22130             "  });\n"
22131             "}\n",
22132             format("SomeResult doSomething(SomeObject promise) {\n"
22133                    "  return promise.then([this, &someVariable, someObject = "
22134                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22135                    "    return someObject.startAsyncAction().then([this, "
22136                    "&someVariable](AsyncActionResult result) mutable {\n"
22137                    "      result.processMore();\n"
22138                    "    });\n"
22139                    "  });\n"
22140                    "}\n",
22141                    Style));
22142   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
22143             "  return promise.then([this, &someVariable] {\n"
22144             "    return someObject.startAsyncAction().then(\n"
22145             "        [this, &someVariable](AsyncActionResult result) mutable { "
22146             "result.processMore(); });\n"
22147             "  });\n"
22148             "}\n",
22149             format("SomeResult doSomething(SomeObject promise) {\n"
22150                    "  return promise.then([this, &someVariable] {\n"
22151                    "    return someObject.startAsyncAction().then([this, "
22152                    "&someVariable](AsyncActionResult result) mutable {\n"
22153                    "      result.processMore();\n"
22154                    "    });\n"
22155                    "  });\n"
22156                    "}\n",
22157                    Style));
22158   Style = getGoogleStyle();
22159   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
22160   EXPECT_EQ("#define A                                       \\\n"
22161             "  [] {                                          \\\n"
22162             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
22163             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
22164             "      }",
22165             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
22166                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
22167                    Style));
22168   // TODO: The current formatting has a minor issue that's not worth fixing
22169   // right now whereby the closing brace is indented relative to the signature
22170   // instead of being aligned. This only happens with macros.
22171 }
22172 
22173 TEST_F(FormatTest, LambdaWithLineComments) {
22174   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
22175   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
22176   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
22177   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
22178       FormatStyle::ShortLambdaStyle::SLS_All;
22179 
22180   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
22181   verifyFormat("auto k = []() // comment\n"
22182                "{ return; }",
22183                LLVMWithBeforeLambdaBody);
22184   verifyFormat("auto k = []() /* comment */ { return; }",
22185                LLVMWithBeforeLambdaBody);
22186   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
22187                LLVMWithBeforeLambdaBody);
22188   verifyFormat("auto k = []() // X\n"
22189                "{ return; }",
22190                LLVMWithBeforeLambdaBody);
22191   verifyFormat(
22192       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
22193       "{ return; }",
22194       LLVMWithBeforeLambdaBody);
22195 
22196   LLVMWithBeforeLambdaBody.ColumnLimit = 0;
22197 
22198   verifyFormat("foo([]()\n"
22199                "    {\n"
22200                "      bar();    //\n"
22201                "      return 1; // comment\n"
22202                "    }());",
22203                "foo([]() {\n"
22204                "  bar(); //\n"
22205                "  return 1; // comment\n"
22206                "}());",
22207                LLVMWithBeforeLambdaBody);
22208   verifyFormat("foo(\n"
22209                "    1, MACRO {\n"
22210                "      baz();\n"
22211                "      bar(); // comment\n"
22212                "    },\n"
22213                "    []() {});",
22214                "foo(\n"
22215                "  1, MACRO { baz(); bar(); // comment\n"
22216                "  }, []() {}\n"
22217                ");",
22218                LLVMWithBeforeLambdaBody);
22219 }
22220 
22221 TEST_F(FormatTest, EmptyLinesInLambdas) {
22222   verifyFormat("auto lambda = []() {\n"
22223                "  x(); //\n"
22224                "};",
22225                "auto lambda = []() {\n"
22226                "\n"
22227                "  x(); //\n"
22228                "\n"
22229                "};");
22230 }
22231 
22232 TEST_F(FormatTest, FormatsBlocks) {
22233   FormatStyle ShortBlocks = getLLVMStyle();
22234   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22235   verifyFormat("int (^Block)(int, int);", ShortBlocks);
22236   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
22237   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
22238   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
22239   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
22240   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
22241 
22242   verifyFormat("foo(^{ bar(); });", ShortBlocks);
22243   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
22244   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
22245 
22246   verifyFormat("[operation setCompletionBlock:^{\n"
22247                "  [self onOperationDone];\n"
22248                "}];");
22249   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
22250                "  [self onOperationDone];\n"
22251                "}]};");
22252   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
22253                "  f();\n"
22254                "}];");
22255   verifyFormat("int a = [operation block:^int(int *i) {\n"
22256                "  return 1;\n"
22257                "}];");
22258   verifyFormat("[myObject doSomethingWith:arg1\n"
22259                "                      aaa:^int(int *a) {\n"
22260                "                        return 1;\n"
22261                "                      }\n"
22262                "                      bbb:f(a * bbbbbbbb)];");
22263 
22264   verifyFormat("[operation setCompletionBlock:^{\n"
22265                "  [self.delegate newDataAvailable];\n"
22266                "}];",
22267                getLLVMStyleWithColumns(60));
22268   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
22269                "  NSString *path = [self sessionFilePath];\n"
22270                "  if (path) {\n"
22271                "    // ...\n"
22272                "  }\n"
22273                "});");
22274   verifyFormat("[[SessionService sharedService]\n"
22275                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22276                "      if (window) {\n"
22277                "        [self windowDidLoad:window];\n"
22278                "      } else {\n"
22279                "        [self errorLoadingWindow];\n"
22280                "      }\n"
22281                "    }];");
22282   verifyFormat("void (^largeBlock)(void) = ^{\n"
22283                "  // ...\n"
22284                "};\n",
22285                getLLVMStyleWithColumns(40));
22286   verifyFormat("[[SessionService sharedService]\n"
22287                "    loadWindowWithCompletionBlock: //\n"
22288                "        ^(SessionWindow *window) {\n"
22289                "          if (window) {\n"
22290                "            [self windowDidLoad:window];\n"
22291                "          } else {\n"
22292                "            [self errorLoadingWindow];\n"
22293                "          }\n"
22294                "        }];",
22295                getLLVMStyleWithColumns(60));
22296   verifyFormat("[myObject doSomethingWith:arg1\n"
22297                "    firstBlock:^(Foo *a) {\n"
22298                "      // ...\n"
22299                "      int i;\n"
22300                "    }\n"
22301                "    secondBlock:^(Bar *b) {\n"
22302                "      // ...\n"
22303                "      int i;\n"
22304                "    }\n"
22305                "    thirdBlock:^Foo(Bar *b) {\n"
22306                "      // ...\n"
22307                "      int i;\n"
22308                "    }];");
22309   verifyFormat("[myObject doSomethingWith:arg1\n"
22310                "               firstBlock:-1\n"
22311                "              secondBlock:^(Bar *b) {\n"
22312                "                // ...\n"
22313                "                int i;\n"
22314                "              }];");
22315 
22316   verifyFormat("f(^{\n"
22317                "  @autoreleasepool {\n"
22318                "    if (a) {\n"
22319                "      g();\n"
22320                "    }\n"
22321                "  }\n"
22322                "});");
22323   verifyFormat("Block b = ^int *(A *a, B *b) {}");
22324   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
22325                "};");
22326 
22327   FormatStyle FourIndent = getLLVMStyle();
22328   FourIndent.ObjCBlockIndentWidth = 4;
22329   verifyFormat("[operation setCompletionBlock:^{\n"
22330                "    [self onOperationDone];\n"
22331                "}];",
22332                FourIndent);
22333 }
22334 
22335 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
22336   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
22337 
22338   verifyFormat("[[SessionService sharedService] "
22339                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22340                "  if (window) {\n"
22341                "    [self windowDidLoad:window];\n"
22342                "  } else {\n"
22343                "    [self errorLoadingWindow];\n"
22344                "  }\n"
22345                "}];",
22346                ZeroColumn);
22347   EXPECT_EQ("[[SessionService sharedService]\n"
22348             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22349             "      if (window) {\n"
22350             "        [self windowDidLoad:window];\n"
22351             "      } else {\n"
22352             "        [self errorLoadingWindow];\n"
22353             "      }\n"
22354             "    }];",
22355             format("[[SessionService sharedService]\n"
22356                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22357                    "                if (window) {\n"
22358                    "    [self windowDidLoad:window];\n"
22359                    "  } else {\n"
22360                    "    [self errorLoadingWindow];\n"
22361                    "  }\n"
22362                    "}];",
22363                    ZeroColumn));
22364   verifyFormat("[myObject doSomethingWith:arg1\n"
22365                "    firstBlock:^(Foo *a) {\n"
22366                "      // ...\n"
22367                "      int i;\n"
22368                "    }\n"
22369                "    secondBlock:^(Bar *b) {\n"
22370                "      // ...\n"
22371                "      int i;\n"
22372                "    }\n"
22373                "    thirdBlock:^Foo(Bar *b) {\n"
22374                "      // ...\n"
22375                "      int i;\n"
22376                "    }];",
22377                ZeroColumn);
22378   verifyFormat("f(^{\n"
22379                "  @autoreleasepool {\n"
22380                "    if (a) {\n"
22381                "      g();\n"
22382                "    }\n"
22383                "  }\n"
22384                "});",
22385                ZeroColumn);
22386   verifyFormat("void (^largeBlock)(void) = ^{\n"
22387                "  // ...\n"
22388                "};",
22389                ZeroColumn);
22390 
22391   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22392   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
22393             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22394   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22395   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
22396             "  int i;\n"
22397             "};",
22398             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22399 }
22400 
22401 TEST_F(FormatTest, SupportsCRLF) {
22402   EXPECT_EQ("int a;\r\n"
22403             "int b;\r\n"
22404             "int c;\r\n",
22405             format("int a;\r\n"
22406                    "  int b;\r\n"
22407                    "    int c;\r\n",
22408                    getLLVMStyle()));
22409   EXPECT_EQ("int a;\r\n"
22410             "int b;\r\n"
22411             "int c;\r\n",
22412             format("int a;\r\n"
22413                    "  int b;\n"
22414                    "    int c;\r\n",
22415                    getLLVMStyle()));
22416   EXPECT_EQ("int a;\n"
22417             "int b;\n"
22418             "int c;\n",
22419             format("int a;\r\n"
22420                    "  int b;\n"
22421                    "    int c;\n",
22422                    getLLVMStyle()));
22423   EXPECT_EQ("\"aaaaaaa \"\r\n"
22424             "\"bbbbbbb\";\r\n",
22425             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
22426   EXPECT_EQ("#define A \\\r\n"
22427             "  b;      \\\r\n"
22428             "  c;      \\\r\n"
22429             "  d;\r\n",
22430             format("#define A \\\r\n"
22431                    "  b; \\\r\n"
22432                    "  c; d; \r\n",
22433                    getGoogleStyle()));
22434 
22435   EXPECT_EQ("/*\r\n"
22436             "multi line block comments\r\n"
22437             "should not introduce\r\n"
22438             "an extra carriage return\r\n"
22439             "*/\r\n",
22440             format("/*\r\n"
22441                    "multi line block comments\r\n"
22442                    "should not introduce\r\n"
22443                    "an extra carriage return\r\n"
22444                    "*/\r\n"));
22445   EXPECT_EQ("/*\r\n"
22446             "\r\n"
22447             "*/",
22448             format("/*\r\n"
22449                    "    \r\r\r\n"
22450                    "*/"));
22451 
22452   FormatStyle style = getLLVMStyle();
22453 
22454   style.DeriveLineEnding = true;
22455   style.UseCRLF = false;
22456   EXPECT_EQ("union FooBarBazQux {\n"
22457             "  int foo;\n"
22458             "  int bar;\n"
22459             "  int baz;\n"
22460             "};",
22461             format("union FooBarBazQux {\r\n"
22462                    "  int foo;\n"
22463                    "  int bar;\r\n"
22464                    "  int baz;\n"
22465                    "};",
22466                    style));
22467   style.UseCRLF = true;
22468   EXPECT_EQ("union FooBarBazQux {\r\n"
22469             "  int foo;\r\n"
22470             "  int bar;\r\n"
22471             "  int baz;\r\n"
22472             "};",
22473             format("union FooBarBazQux {\r\n"
22474                    "  int foo;\n"
22475                    "  int bar;\r\n"
22476                    "  int baz;\n"
22477                    "};",
22478                    style));
22479 
22480   style.DeriveLineEnding = false;
22481   style.UseCRLF = false;
22482   EXPECT_EQ("union FooBarBazQux {\n"
22483             "  int foo;\n"
22484             "  int bar;\n"
22485             "  int baz;\n"
22486             "  int qux;\n"
22487             "};",
22488             format("union FooBarBazQux {\r\n"
22489                    "  int foo;\n"
22490                    "  int bar;\r\n"
22491                    "  int baz;\n"
22492                    "  int qux;\r\n"
22493                    "};",
22494                    style));
22495   style.UseCRLF = true;
22496   EXPECT_EQ("union FooBarBazQux {\r\n"
22497             "  int foo;\r\n"
22498             "  int bar;\r\n"
22499             "  int baz;\r\n"
22500             "  int qux;\r\n"
22501             "};",
22502             format("union FooBarBazQux {\r\n"
22503                    "  int foo;\n"
22504                    "  int bar;\r\n"
22505                    "  int baz;\n"
22506                    "  int qux;\n"
22507                    "};",
22508                    style));
22509 
22510   style.DeriveLineEnding = true;
22511   style.UseCRLF = false;
22512   EXPECT_EQ("union FooBarBazQux {\r\n"
22513             "  int foo;\r\n"
22514             "  int bar;\r\n"
22515             "  int baz;\r\n"
22516             "  int qux;\r\n"
22517             "};",
22518             format("union FooBarBazQux {\r\n"
22519                    "  int foo;\n"
22520                    "  int bar;\r\n"
22521                    "  int baz;\n"
22522                    "  int qux;\r\n"
22523                    "};",
22524                    style));
22525   style.UseCRLF = true;
22526   EXPECT_EQ("union FooBarBazQux {\n"
22527             "  int foo;\n"
22528             "  int bar;\n"
22529             "  int baz;\n"
22530             "  int qux;\n"
22531             "};",
22532             format("union FooBarBazQux {\r\n"
22533                    "  int foo;\n"
22534                    "  int bar;\r\n"
22535                    "  int baz;\n"
22536                    "  int qux;\n"
22537                    "};",
22538                    style));
22539 }
22540 
22541 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
22542   verifyFormat("MY_CLASS(C) {\n"
22543                "  int i;\n"
22544                "  int j;\n"
22545                "};");
22546 }
22547 
22548 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
22549   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
22550   TwoIndent.ContinuationIndentWidth = 2;
22551 
22552   EXPECT_EQ("int i =\n"
22553             "  longFunction(\n"
22554             "    arg);",
22555             format("int i = longFunction(arg);", TwoIndent));
22556 
22557   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
22558   SixIndent.ContinuationIndentWidth = 6;
22559 
22560   EXPECT_EQ("int i =\n"
22561             "      longFunction(\n"
22562             "            arg);",
22563             format("int i = longFunction(arg);", SixIndent));
22564 }
22565 
22566 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
22567   FormatStyle Style = getLLVMStyle();
22568   verifyFormat("int Foo::getter(\n"
22569                "    //\n"
22570                ") const {\n"
22571                "  return foo;\n"
22572                "}",
22573                Style);
22574   verifyFormat("void Foo::setter(\n"
22575                "    //\n"
22576                ") {\n"
22577                "  foo = 1;\n"
22578                "}",
22579                Style);
22580 }
22581 
22582 TEST_F(FormatTest, SpacesInAngles) {
22583   FormatStyle Spaces = getLLVMStyle();
22584   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22585 
22586   verifyFormat("vector< ::std::string > x1;", Spaces);
22587   verifyFormat("Foo< int, Bar > x2;", Spaces);
22588   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22589 
22590   verifyFormat("static_cast< int >(arg);", Spaces);
22591   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22592   verifyFormat("f< int, float >();", Spaces);
22593   verifyFormat("template <> g() {}", Spaces);
22594   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22595   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22596   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22597                Spaces);
22598 
22599   Spaces.Standard = FormatStyle::LS_Cpp03;
22600   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22601   verifyFormat("A< A< int > >();", Spaces);
22602 
22603   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22604   verifyFormat("A<A<int> >();", Spaces);
22605 
22606   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22607   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22608                Spaces);
22609   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22610                Spaces);
22611 
22612   verifyFormat("A<A<int> >();", Spaces);
22613   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22614   verifyFormat("A< A< int > >();", Spaces);
22615 
22616   Spaces.Standard = FormatStyle::LS_Cpp11;
22617   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22618   verifyFormat("A< A< int > >();", Spaces);
22619 
22620   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22621   verifyFormat("vector<::std::string> x4;", Spaces);
22622   verifyFormat("vector<int> x5;", Spaces);
22623   verifyFormat("Foo<int, Bar> x6;", Spaces);
22624   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22625 
22626   verifyFormat("A<A<int>>();", Spaces);
22627 
22628   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22629   verifyFormat("vector<::std::string> x4;", Spaces);
22630   verifyFormat("vector< ::std::string > x4;", Spaces);
22631   verifyFormat("vector<int> x5;", Spaces);
22632   verifyFormat("vector< int > x5;", Spaces);
22633   verifyFormat("Foo<int, Bar> x6;", Spaces);
22634   verifyFormat("Foo< int, Bar > x6;", Spaces);
22635   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22636   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22637 
22638   verifyFormat("A<A<int>>();", Spaces);
22639   verifyFormat("A< A< int > >();", Spaces);
22640   verifyFormat("A<A<int > >();", Spaces);
22641   verifyFormat("A< A< int>>();", Spaces);
22642 
22643   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22644   verifyFormat("// clang-format off\n"
22645                "foo<<<1, 1>>>();\n"
22646                "// clang-format on\n",
22647                Spaces);
22648   verifyFormat("// clang-format off\n"
22649                "foo< < <1, 1> > >();\n"
22650                "// clang-format on\n",
22651                Spaces);
22652 }
22653 
22654 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22655   FormatStyle Style = getLLVMStyle();
22656   Style.SpaceAfterTemplateKeyword = false;
22657   verifyFormat("template<int> void foo();", Style);
22658 }
22659 
22660 TEST_F(FormatTest, TripleAngleBrackets) {
22661   verifyFormat("f<<<1, 1>>>();");
22662   verifyFormat("f<<<1, 1, 1, s>>>();");
22663   verifyFormat("f<<<a, b, c, d>>>();");
22664   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22665   verifyFormat("f<param><<<1, 1>>>();");
22666   verifyFormat("f<1><<<1, 1>>>();");
22667   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22668   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22669                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22670   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22671                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22672 }
22673 
22674 TEST_F(FormatTest, MergeLessLessAtEnd) {
22675   verifyFormat("<<");
22676   EXPECT_EQ("< < <", format("\\\n<<<"));
22677   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22678                "aaallvm::outs() <<");
22679   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22680                "aaaallvm::outs()\n    <<");
22681 }
22682 
22683 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22684   std::string code = "#if A\n"
22685                      "#if B\n"
22686                      "a.\n"
22687                      "#endif\n"
22688                      "    a = 1;\n"
22689                      "#else\n"
22690                      "#endif\n"
22691                      "#if C\n"
22692                      "#else\n"
22693                      "#endif\n";
22694   EXPECT_EQ(code, format(code));
22695 }
22696 
22697 TEST_F(FormatTest, HandleConflictMarkers) {
22698   // Git/SVN conflict markers.
22699   EXPECT_EQ("int a;\n"
22700             "void f() {\n"
22701             "  callme(some(parameter1,\n"
22702             "<<<<<<< text by the vcs\n"
22703             "              parameter2),\n"
22704             "||||||| text by the vcs\n"
22705             "              parameter2),\n"
22706             "         parameter3,\n"
22707             "======= text by the vcs\n"
22708             "              parameter2, parameter3),\n"
22709             ">>>>>>> text by the vcs\n"
22710             "         otherparameter);\n",
22711             format("int a;\n"
22712                    "void f() {\n"
22713                    "  callme(some(parameter1,\n"
22714                    "<<<<<<< text by the vcs\n"
22715                    "  parameter2),\n"
22716                    "||||||| text by the vcs\n"
22717                    "  parameter2),\n"
22718                    "  parameter3,\n"
22719                    "======= text by the vcs\n"
22720                    "  parameter2,\n"
22721                    "  parameter3),\n"
22722                    ">>>>>>> text by the vcs\n"
22723                    "  otherparameter);\n"));
22724 
22725   // Perforce markers.
22726   EXPECT_EQ("void f() {\n"
22727             "  function(\n"
22728             ">>>> text by the vcs\n"
22729             "      parameter,\n"
22730             "==== text by the vcs\n"
22731             "      parameter,\n"
22732             "==== text by the vcs\n"
22733             "      parameter,\n"
22734             "<<<< text by the vcs\n"
22735             "      parameter);\n",
22736             format("void f() {\n"
22737                    "  function(\n"
22738                    ">>>> text by the vcs\n"
22739                    "  parameter,\n"
22740                    "==== text by the vcs\n"
22741                    "  parameter,\n"
22742                    "==== text by the vcs\n"
22743                    "  parameter,\n"
22744                    "<<<< text by the vcs\n"
22745                    "  parameter);\n"));
22746 
22747   EXPECT_EQ("<<<<<<<\n"
22748             "|||||||\n"
22749             "=======\n"
22750             ">>>>>>>",
22751             format("<<<<<<<\n"
22752                    "|||||||\n"
22753                    "=======\n"
22754                    ">>>>>>>"));
22755 
22756   EXPECT_EQ("<<<<<<<\n"
22757             "|||||||\n"
22758             "int i;\n"
22759             "=======\n"
22760             ">>>>>>>",
22761             format("<<<<<<<\n"
22762                    "|||||||\n"
22763                    "int i;\n"
22764                    "=======\n"
22765                    ">>>>>>>"));
22766 
22767   // FIXME: Handle parsing of macros around conflict markers correctly:
22768   EXPECT_EQ("#define Macro \\\n"
22769             "<<<<<<<\n"
22770             "Something \\\n"
22771             "|||||||\n"
22772             "Else \\\n"
22773             "=======\n"
22774             "Other \\\n"
22775             ">>>>>>>\n"
22776             "    End int i;\n",
22777             format("#define Macro \\\n"
22778                    "<<<<<<<\n"
22779                    "  Something \\\n"
22780                    "|||||||\n"
22781                    "  Else \\\n"
22782                    "=======\n"
22783                    "  Other \\\n"
22784                    ">>>>>>>\n"
22785                    "  End\n"
22786                    "int i;\n"));
22787 
22788   verifyFormat(R"(====
22789 #ifdef A
22790 a
22791 #else
22792 b
22793 #endif
22794 )");
22795 }
22796 
22797 TEST_F(FormatTest, DisableRegions) {
22798   EXPECT_EQ("int i;\n"
22799             "// clang-format off\n"
22800             "  int j;\n"
22801             "// clang-format on\n"
22802             "int k;",
22803             format(" int  i;\n"
22804                    "   // clang-format off\n"
22805                    "  int j;\n"
22806                    " // clang-format on\n"
22807                    "   int   k;"));
22808   EXPECT_EQ("int i;\n"
22809             "/* clang-format off */\n"
22810             "  int j;\n"
22811             "/* clang-format on */\n"
22812             "int k;",
22813             format(" int  i;\n"
22814                    "   /* clang-format off */\n"
22815                    "  int j;\n"
22816                    " /* clang-format on */\n"
22817                    "   int   k;"));
22818 
22819   // Don't reflow comments within disabled regions.
22820   EXPECT_EQ("// clang-format off\n"
22821             "// long long long long long long line\n"
22822             "/* clang-format on */\n"
22823             "/* long long long\n"
22824             " * long long long\n"
22825             " * line */\n"
22826             "int i;\n"
22827             "/* clang-format off */\n"
22828             "/* long long long long long long line */\n",
22829             format("// clang-format off\n"
22830                    "// long long long long long long line\n"
22831                    "/* clang-format on */\n"
22832                    "/* long long long long long long line */\n"
22833                    "int i;\n"
22834                    "/* clang-format off */\n"
22835                    "/* long long long long long long line */\n",
22836                    getLLVMStyleWithColumns(20)));
22837 }
22838 
22839 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22840   format("? ) =");
22841   verifyNoCrash("#define a\\\n /**/}");
22842 }
22843 
22844 TEST_F(FormatTest, FormatsTableGenCode) {
22845   FormatStyle Style = getLLVMStyle();
22846   Style.Language = FormatStyle::LK_TableGen;
22847   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22848 }
22849 
22850 TEST_F(FormatTest, ArrayOfTemplates) {
22851   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22852             format("auto a = new unique_ptr<int > [ 10];"));
22853 
22854   FormatStyle Spaces = getLLVMStyle();
22855   Spaces.SpacesInSquareBrackets = true;
22856   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22857             format("auto a = new unique_ptr<int > [10];", Spaces));
22858 }
22859 
22860 TEST_F(FormatTest, ArrayAsTemplateType) {
22861   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22862             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22863 
22864   FormatStyle Spaces = getLLVMStyle();
22865   Spaces.SpacesInSquareBrackets = true;
22866   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22867             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22868 }
22869 
22870 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22871 
22872 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22873   llvm::vfs::InMemoryFileSystem FS;
22874   auto Style1 = getStyle("file", "", "Google", "", &FS);
22875   ASSERT_TRUE((bool)Style1);
22876   ASSERT_EQ(*Style1, getGoogleStyle());
22877 }
22878 
22879 TEST(FormatStyle, GetStyleOfFile) {
22880   llvm::vfs::InMemoryFileSystem FS;
22881   // Test 1: format file in the same directory.
22882   ASSERT_TRUE(
22883       FS.addFile("/a/.clang-format", 0,
22884                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22885   ASSERT_TRUE(
22886       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22887   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22888   ASSERT_TRUE((bool)Style1);
22889   ASSERT_EQ(*Style1, getLLVMStyle());
22890 
22891   // Test 2.1: fallback to default.
22892   ASSERT_TRUE(
22893       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22894   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22895   ASSERT_TRUE((bool)Style2);
22896   ASSERT_EQ(*Style2, getMozillaStyle());
22897 
22898   // Test 2.2: no format on 'none' fallback style.
22899   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22900   ASSERT_TRUE((bool)Style2);
22901   ASSERT_EQ(*Style2, getNoStyle());
22902 
22903   // Test 2.3: format if config is found with no based style while fallback is
22904   // 'none'.
22905   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22906                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22907   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22908   ASSERT_TRUE((bool)Style2);
22909   ASSERT_EQ(*Style2, getLLVMStyle());
22910 
22911   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22912   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22913   ASSERT_TRUE((bool)Style2);
22914   ASSERT_EQ(*Style2, getLLVMStyle());
22915 
22916   // Test 3: format file in parent directory.
22917   ASSERT_TRUE(
22918       FS.addFile("/c/.clang-format", 0,
22919                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22920   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22921                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22922   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22923   ASSERT_TRUE((bool)Style3);
22924   ASSERT_EQ(*Style3, getGoogleStyle());
22925 
22926   // Test 4: error on invalid fallback style
22927   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22928   ASSERT_FALSE((bool)Style4);
22929   llvm::consumeError(Style4.takeError());
22930 
22931   // Test 5: error on invalid yaml on command line
22932   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22933   ASSERT_FALSE((bool)Style5);
22934   llvm::consumeError(Style5.takeError());
22935 
22936   // Test 6: error on invalid style
22937   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22938   ASSERT_FALSE((bool)Style6);
22939   llvm::consumeError(Style6.takeError());
22940 
22941   // Test 7: found config file, error on parsing it
22942   ASSERT_TRUE(
22943       FS.addFile("/d/.clang-format", 0,
22944                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22945                                                   "InvalidKey: InvalidValue")));
22946   ASSERT_TRUE(
22947       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22948   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22949   ASSERT_FALSE((bool)Style7a);
22950   llvm::consumeError(Style7a.takeError());
22951 
22952   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22953   ASSERT_TRUE((bool)Style7b);
22954 
22955   // Test 8: inferred per-language defaults apply.
22956   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22957   ASSERT_TRUE((bool)StyleTd);
22958   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22959 
22960   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22961   // fallback style.
22962   ASSERT_TRUE(FS.addFile(
22963       "/e/sub/.clang-format", 0,
22964       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22965                                        "ColumnLimit: 20")));
22966   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22967                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22968   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22969   ASSERT_TRUE(static_cast<bool>(Style9));
22970   ASSERT_EQ(*Style9, [] {
22971     auto Style = getNoStyle();
22972     Style.ColumnLimit = 20;
22973     return Style;
22974   }());
22975 
22976   // Test 9.1.2: propagate more than one level with no parent file.
22977   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22978                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22979   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22980                          llvm::MemoryBuffer::getMemBuffer(
22981                              "BasedOnStyle: InheritParentConfig\n"
22982                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22983   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22984 
22985   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22986   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22987   ASSERT_TRUE(static_cast<bool>(Style9));
22988   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22989     auto Style = getNoStyle();
22990     Style.ColumnLimit = 20;
22991     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22992     return Style;
22993   }());
22994 
22995   // Test 9.2: with LLVM fallback style
22996   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22997   ASSERT_TRUE(static_cast<bool>(Style9));
22998   ASSERT_EQ(*Style9, [] {
22999     auto Style = getLLVMStyle();
23000     Style.ColumnLimit = 20;
23001     return Style;
23002   }());
23003 
23004   // Test 9.3: with a parent file
23005   ASSERT_TRUE(
23006       FS.addFile("/e/.clang-format", 0,
23007                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
23008                                                   "UseTab: Always")));
23009   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
23010   ASSERT_TRUE(static_cast<bool>(Style9));
23011   ASSERT_EQ(*Style9, [] {
23012     auto Style = getGoogleStyle();
23013     Style.ColumnLimit = 20;
23014     Style.UseTab = FormatStyle::UT_Always;
23015     return Style;
23016   }());
23017 
23018   // Test 9.4: propagate more than one level with a parent file.
23019   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
23020     auto Style = getGoogleStyle();
23021     Style.ColumnLimit = 20;
23022     Style.UseTab = FormatStyle::UT_Always;
23023     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
23024     return Style;
23025   }();
23026 
23027   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
23028   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
23029   ASSERT_TRUE(static_cast<bool>(Style9));
23030   ASSERT_EQ(*Style9, SubSubStyle);
23031 
23032   // Test 9.5: use InheritParentConfig as style name
23033   Style9 =
23034       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
23035   ASSERT_TRUE(static_cast<bool>(Style9));
23036   ASSERT_EQ(*Style9, SubSubStyle);
23037 
23038   // Test 9.6: use command line style with inheritance
23039   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
23040                     "none", "", &FS);
23041   ASSERT_TRUE(static_cast<bool>(Style9));
23042   ASSERT_EQ(*Style9, SubSubStyle);
23043 
23044   // Test 9.7: use command line style with inheritance and own config
23045   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
23046                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
23047                     "/e/sub/code.cpp", "none", "", &FS);
23048   ASSERT_TRUE(static_cast<bool>(Style9));
23049   ASSERT_EQ(*Style9, SubSubStyle);
23050 
23051   // Test 9.8: use inheritance from a file without BasedOnStyle
23052   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
23053                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
23054   ASSERT_TRUE(
23055       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
23056                  llvm::MemoryBuffer::getMemBuffer(
23057                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
23058   // Make sure we do not use the fallback style
23059   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
23060   ASSERT_TRUE(static_cast<bool>(Style9));
23061   ASSERT_EQ(*Style9, [] {
23062     auto Style = getLLVMStyle();
23063     Style.ColumnLimit = 123;
23064     return Style;
23065   }());
23066 
23067   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
23068   ASSERT_TRUE(static_cast<bool>(Style9));
23069   ASSERT_EQ(*Style9, [] {
23070     auto Style = getLLVMStyle();
23071     Style.ColumnLimit = 123;
23072     Style.IndentWidth = 7;
23073     return Style;
23074   }());
23075 
23076   // Test 9.9: use inheritance from a specific config file.
23077   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
23078                     "none", "", &FS);
23079   ASSERT_TRUE(static_cast<bool>(Style9));
23080   ASSERT_EQ(*Style9, SubSubStyle);
23081 }
23082 
23083 TEST(FormatStyle, GetStyleOfSpecificFile) {
23084   llvm::vfs::InMemoryFileSystem FS;
23085   // Specify absolute path to a format file in a parent directory.
23086   ASSERT_TRUE(
23087       FS.addFile("/e/.clang-format", 0,
23088                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
23089   ASSERT_TRUE(
23090       FS.addFile("/e/explicit.clang-format", 0,
23091                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
23092   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
23093                          llvm::MemoryBuffer::getMemBuffer("int i;")));
23094   auto Style = getStyle("file:/e/explicit.clang-format",
23095                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
23096   ASSERT_TRUE(static_cast<bool>(Style));
23097   ASSERT_EQ(*Style, getGoogleStyle());
23098 
23099   // Specify relative path to a format file.
23100   ASSERT_TRUE(
23101       FS.addFile("../../e/explicit.clang-format", 0,
23102                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
23103   Style = getStyle("file:../../e/explicit.clang-format",
23104                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
23105   ASSERT_TRUE(static_cast<bool>(Style));
23106   ASSERT_EQ(*Style, getGoogleStyle());
23107 
23108   // Specify path to a format file that does not exist.
23109   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
23110                    "LLVM", "", &FS);
23111   ASSERT_FALSE(static_cast<bool>(Style));
23112   llvm::consumeError(Style.takeError());
23113 
23114   // Specify path to a file on the filesystem.
23115   SmallString<128> FormatFilePath;
23116   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
23117       "FormatFileTest", "tpl", FormatFilePath);
23118   EXPECT_FALSE((bool)ECF);
23119   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
23120   EXPECT_FALSE((bool)ECF);
23121   FormatFileTest << "BasedOnStyle: Google\n";
23122   FormatFileTest.close();
23123 
23124   SmallString<128> TestFilePath;
23125   std::error_code ECT =
23126       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
23127   EXPECT_FALSE((bool)ECT);
23128   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
23129   CodeFileTest << "int i;\n";
23130   CodeFileTest.close();
23131 
23132   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
23133   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
23134 
23135   llvm::sys::fs::remove(FormatFilePath.c_str());
23136   llvm::sys::fs::remove(TestFilePath.c_str());
23137   ASSERT_TRUE(static_cast<bool>(Style));
23138   ASSERT_EQ(*Style, getGoogleStyle());
23139 }
23140 
23141 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
23142   // Column limit is 20.
23143   std::string Code = "Type *a =\n"
23144                      "    new Type();\n"
23145                      "g(iiiii, 0, jjjjj,\n"
23146                      "  0, kkkkk, 0, mm);\n"
23147                      "int  bad     = format   ;";
23148   std::string Expected = "auto a = new Type();\n"
23149                          "g(iiiii, nullptr,\n"
23150                          "  jjjjj, nullptr,\n"
23151                          "  kkkkk, nullptr,\n"
23152                          "  mm);\n"
23153                          "int  bad     = format   ;";
23154   FileID ID = Context.createInMemoryFile("format.cpp", Code);
23155   tooling::Replacements Replaces = toReplacements(
23156       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
23157                             "auto "),
23158        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
23159                             "nullptr"),
23160        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
23161                             "nullptr"),
23162        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
23163                             "nullptr")});
23164 
23165   FormatStyle Style = getLLVMStyle();
23166   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
23167   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
23168   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
23169       << llvm::toString(FormattedReplaces.takeError()) << "\n";
23170   auto Result = applyAllReplacements(Code, *FormattedReplaces);
23171   EXPECT_TRUE(static_cast<bool>(Result));
23172   EXPECT_EQ(Expected, *Result);
23173 }
23174 
23175 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
23176   std::string Code = "#include \"a.h\"\n"
23177                      "#include \"c.h\"\n"
23178                      "\n"
23179                      "int main() {\n"
23180                      "  return 0;\n"
23181                      "}";
23182   std::string Expected = "#include \"a.h\"\n"
23183                          "#include \"b.h\"\n"
23184                          "#include \"c.h\"\n"
23185                          "\n"
23186                          "int main() {\n"
23187                          "  return 0;\n"
23188                          "}";
23189   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
23190   tooling::Replacements Replaces = toReplacements(
23191       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
23192                             "#include \"b.h\"\n")});
23193 
23194   FormatStyle Style = getLLVMStyle();
23195   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
23196   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
23197   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
23198       << llvm::toString(FormattedReplaces.takeError()) << "\n";
23199   auto Result = applyAllReplacements(Code, *FormattedReplaces);
23200   EXPECT_TRUE(static_cast<bool>(Result));
23201   EXPECT_EQ(Expected, *Result);
23202 }
23203 
23204 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
23205   EXPECT_EQ("using std::cin;\n"
23206             "using std::cout;",
23207             format("using std::cout;\n"
23208                    "using std::cin;",
23209                    getGoogleStyle()));
23210 }
23211 
23212 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
23213   FormatStyle Style = getLLVMStyle();
23214   Style.Standard = FormatStyle::LS_Cpp03;
23215   // cpp03 recognize this string as identifier u8 and literal character 'a'
23216   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
23217 }
23218 
23219 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
23220   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
23221   // all modes, including C++11, C++14 and C++17
23222   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
23223 }
23224 
23225 TEST_F(FormatTest, DoNotFormatLikelyXml) {
23226   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
23227   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
23228 }
23229 
23230 TEST_F(FormatTest, StructuredBindings) {
23231   // Structured bindings is a C++17 feature.
23232   // all modes, including C++11, C++14 and C++17
23233   verifyFormat("auto [a, b] = f();");
23234   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
23235   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
23236   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
23237   EXPECT_EQ("auto const volatile [a, b] = f();",
23238             format("auto  const   volatile[a, b] = f();"));
23239   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
23240   EXPECT_EQ("auto &[a, b, c] = f();",
23241             format("auto   &[  a  ,  b,c   ] = f();"));
23242   EXPECT_EQ("auto &&[a, b, c] = f();",
23243             format("auto   &&[  a  ,  b,c   ] = f();"));
23244   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
23245   EXPECT_EQ("auto const volatile &&[a, b] = f();",
23246             format("auto  const  volatile  &&[a, b] = f();"));
23247   EXPECT_EQ("auto const &&[a, b] = f();",
23248             format("auto  const   &&  [a, b] = f();"));
23249   EXPECT_EQ("const auto &[a, b] = f();",
23250             format("const  auto  &  [a, b] = f();"));
23251   EXPECT_EQ("const auto volatile &&[a, b] = f();",
23252             format("const  auto   volatile  &&[a, b] = f();"));
23253   EXPECT_EQ("volatile const auto &&[a, b] = f();",
23254             format("volatile  const  auto   &&[a, b] = f();"));
23255   EXPECT_EQ("const auto &&[a, b] = f();",
23256             format("const  auto  &&  [a, b] = f();"));
23257 
23258   // Make sure we don't mistake structured bindings for lambdas.
23259   FormatStyle PointerMiddle = getLLVMStyle();
23260   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
23261   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
23262   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
23263   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
23264   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
23265   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
23266   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
23267   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
23268   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
23269   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
23270   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
23271   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
23272   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
23273 
23274   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
23275             format("for (const auto   &&   [a, b] : some_range) {\n}"));
23276   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
23277             format("for (const auto   &   [a, b] : some_range) {\n}"));
23278   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
23279             format("for (const auto[a, b] : some_range) {\n}"));
23280   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
23281   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
23282   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
23283   EXPECT_EQ("auto const &[x, y](expr);",
23284             format("auto  const  &  [x,y]  (expr);"));
23285   EXPECT_EQ("auto const &&[x, y](expr);",
23286             format("auto  const  &&  [x,y]  (expr);"));
23287   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
23288   EXPECT_EQ("auto const &[x, y]{expr};",
23289             format("auto  const  &  [x,y]  {expr};"));
23290   EXPECT_EQ("auto const &&[x, y]{expr};",
23291             format("auto  const  &&  [x,y]  {expr};"));
23292 
23293   FormatStyle Spaces = getLLVMStyle();
23294   Spaces.SpacesInSquareBrackets = true;
23295   verifyFormat("auto [ a, b ] = f();", Spaces);
23296   verifyFormat("auto &&[ a, b ] = f();", Spaces);
23297   verifyFormat("auto &[ a, b ] = f();", Spaces);
23298   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
23299   verifyFormat("auto const &[ a, b ] = f();", Spaces);
23300 }
23301 
23302 TEST_F(FormatTest, FileAndCode) {
23303   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
23304   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
23305   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
23306   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
23307   EXPECT_EQ(FormatStyle::LK_ObjC,
23308             guessLanguage("foo.h", "@interface Foo\n@end\n"));
23309   EXPECT_EQ(
23310       FormatStyle::LK_ObjC,
23311       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
23312   EXPECT_EQ(FormatStyle::LK_ObjC,
23313             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
23314   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
23315   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
23316   EXPECT_EQ(FormatStyle::LK_ObjC,
23317             guessLanguage("foo", "@interface Foo\n@end\n"));
23318   EXPECT_EQ(FormatStyle::LK_ObjC,
23319             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
23320   EXPECT_EQ(
23321       FormatStyle::LK_ObjC,
23322       guessLanguage("foo.h",
23323                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
23324   EXPECT_EQ(
23325       FormatStyle::LK_Cpp,
23326       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
23327   // Only one of the two preprocessor regions has ObjC-like code.
23328   EXPECT_EQ(FormatStyle::LK_ObjC,
23329             guessLanguage("foo.h", "#if A\n"
23330                                    "#define B() C\n"
23331                                    "#else\n"
23332                                    "#define B() [NSString a:@\"\"]\n"
23333                                    "#endif\n"));
23334 }
23335 
23336 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
23337   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
23338   EXPECT_EQ(FormatStyle::LK_ObjC,
23339             guessLanguage("foo.h", "array[[calculator getIndex]];"));
23340   EXPECT_EQ(FormatStyle::LK_Cpp,
23341             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
23342   EXPECT_EQ(
23343       FormatStyle::LK_Cpp,
23344       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
23345   EXPECT_EQ(FormatStyle::LK_ObjC,
23346             guessLanguage("foo.h", "[[noreturn foo] bar];"));
23347   EXPECT_EQ(FormatStyle::LK_Cpp,
23348             guessLanguage("foo.h", "[[clang::fallthrough]];"));
23349   EXPECT_EQ(FormatStyle::LK_ObjC,
23350             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
23351   EXPECT_EQ(FormatStyle::LK_Cpp,
23352             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
23353   EXPECT_EQ(FormatStyle::LK_Cpp,
23354             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
23355   EXPECT_EQ(FormatStyle::LK_ObjC,
23356             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
23357   EXPECT_EQ(FormatStyle::LK_Cpp,
23358             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
23359   EXPECT_EQ(
23360       FormatStyle::LK_Cpp,
23361       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
23362   EXPECT_EQ(
23363       FormatStyle::LK_Cpp,
23364       guessLanguage("foo.h",
23365                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
23366   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
23367 }
23368 
23369 TEST_F(FormatTest, GuessLanguageWithCaret) {
23370   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
23371   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
23372   EXPECT_EQ(FormatStyle::LK_ObjC,
23373             guessLanguage("foo.h", "int(^)(char, float);"));
23374   EXPECT_EQ(FormatStyle::LK_ObjC,
23375             guessLanguage("foo.h", "int(^foo)(char, float);"));
23376   EXPECT_EQ(FormatStyle::LK_ObjC,
23377             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
23378   EXPECT_EQ(FormatStyle::LK_ObjC,
23379             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
23380   EXPECT_EQ(
23381       FormatStyle::LK_ObjC,
23382       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
23383 }
23384 
23385 TEST_F(FormatTest, GuessLanguageWithPragmas) {
23386   EXPECT_EQ(FormatStyle::LK_Cpp,
23387             guessLanguage("foo.h", "__pragma(warning(disable:))"));
23388   EXPECT_EQ(FormatStyle::LK_Cpp,
23389             guessLanguage("foo.h", "#pragma(warning(disable:))"));
23390   EXPECT_EQ(FormatStyle::LK_Cpp,
23391             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
23392 }
23393 
23394 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
23395   // ASM symbolic names are identifiers that must be surrounded by [] without
23396   // space in between:
23397   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
23398 
23399   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
23400   verifyFormat(R"(//
23401 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
23402 )");
23403 
23404   // A list of several ASM symbolic names.
23405   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
23406 
23407   // ASM symbolic names in inline ASM with inputs and outputs.
23408   verifyFormat(R"(//
23409 asm("cmoveq %1, %2, %[result]"
23410     : [result] "=r"(result)
23411     : "r"(test), "r"(new), "[result]"(old));
23412 )");
23413 
23414   // ASM symbolic names in inline ASM with no outputs.
23415   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
23416 }
23417 
23418 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
23419   EXPECT_EQ(FormatStyle::LK_Cpp,
23420             guessLanguage("foo.h", "void f() {\n"
23421                                    "  asm (\"mov %[e], %[d]\"\n"
23422                                    "     : [d] \"=rm\" (d)\n"
23423                                    "       [e] \"rm\" (*e));\n"
23424                                    "}"));
23425   EXPECT_EQ(FormatStyle::LK_Cpp,
23426             guessLanguage("foo.h", "void f() {\n"
23427                                    "  _asm (\"mov %[e], %[d]\"\n"
23428                                    "     : [d] \"=rm\" (d)\n"
23429                                    "       [e] \"rm\" (*e));\n"
23430                                    "}"));
23431   EXPECT_EQ(FormatStyle::LK_Cpp,
23432             guessLanguage("foo.h", "void f() {\n"
23433                                    "  __asm (\"mov %[e], %[d]\"\n"
23434                                    "     : [d] \"=rm\" (d)\n"
23435                                    "       [e] \"rm\" (*e));\n"
23436                                    "}"));
23437   EXPECT_EQ(FormatStyle::LK_Cpp,
23438             guessLanguage("foo.h", "void f() {\n"
23439                                    "  __asm__ (\"mov %[e], %[d]\"\n"
23440                                    "     : [d] \"=rm\" (d)\n"
23441                                    "       [e] \"rm\" (*e));\n"
23442                                    "}"));
23443   EXPECT_EQ(FormatStyle::LK_Cpp,
23444             guessLanguage("foo.h", "void f() {\n"
23445                                    "  asm (\"mov %[e], %[d]\"\n"
23446                                    "     : [d] \"=rm\" (d),\n"
23447                                    "       [e] \"rm\" (*e));\n"
23448                                    "}"));
23449   EXPECT_EQ(FormatStyle::LK_Cpp,
23450             guessLanguage("foo.h", "void f() {\n"
23451                                    "  asm volatile (\"mov %[e], %[d]\"\n"
23452                                    "     : [d] \"=rm\" (d)\n"
23453                                    "       [e] \"rm\" (*e));\n"
23454                                    "}"));
23455 }
23456 
23457 TEST_F(FormatTest, GuessLanguageWithChildLines) {
23458   EXPECT_EQ(FormatStyle::LK_Cpp,
23459             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
23460   EXPECT_EQ(FormatStyle::LK_ObjC,
23461             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
23462   EXPECT_EQ(
23463       FormatStyle::LK_Cpp,
23464       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
23465   EXPECT_EQ(
23466       FormatStyle::LK_ObjC,
23467       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
23468 }
23469 
23470 TEST_F(FormatTest, TypenameMacros) {
23471   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
23472 
23473   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
23474   FormatStyle Google = getGoogleStyleWithColumns(0);
23475   Google.TypenameMacros = TypenameMacros;
23476   verifyFormat("struct foo {\n"
23477                "  int bar;\n"
23478                "  TAILQ_ENTRY(a) bleh;\n"
23479                "};",
23480                Google);
23481 
23482   FormatStyle Macros = getLLVMStyle();
23483   Macros.TypenameMacros = TypenameMacros;
23484 
23485   verifyFormat("STACK_OF(int) a;", Macros);
23486   verifyFormat("STACK_OF(int) *a;", Macros);
23487   verifyFormat("STACK_OF(int const *) *a;", Macros);
23488   verifyFormat("STACK_OF(int *const) *a;", Macros);
23489   verifyFormat("STACK_OF(int, string) a;", Macros);
23490   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
23491   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
23492   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
23493   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
23494   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
23495   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
23496 
23497   Macros.PointerAlignment = FormatStyle::PAS_Left;
23498   verifyFormat("STACK_OF(int)* a;", Macros);
23499   verifyFormat("STACK_OF(int*)* a;", Macros);
23500   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
23501   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
23502   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
23503 }
23504 
23505 TEST_F(FormatTest, AtomicQualifier) {
23506   // Check that we treate _Atomic as a type and not a function call
23507   FormatStyle Google = getGoogleStyleWithColumns(0);
23508   verifyFormat("struct foo {\n"
23509                "  int a1;\n"
23510                "  _Atomic(a) a2;\n"
23511                "  _Atomic(_Atomic(int) *const) a3;\n"
23512                "};",
23513                Google);
23514   verifyFormat("_Atomic(uint64_t) a;");
23515   verifyFormat("_Atomic(uint64_t) *a;");
23516   verifyFormat("_Atomic(uint64_t const *) *a;");
23517   verifyFormat("_Atomic(uint64_t *const) *a;");
23518   verifyFormat("_Atomic(const uint64_t *) *a;");
23519   verifyFormat("_Atomic(uint64_t) a;");
23520   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
23521   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
23522   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
23523   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
23524 
23525   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
23526   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
23527   FormatStyle Style = getLLVMStyle();
23528   Style.PointerAlignment = FormatStyle::PAS_Left;
23529   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
23530   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
23531   verifyFormat("_Atomic(int)* a;", Style);
23532   verifyFormat("_Atomic(int*)* a;", Style);
23533   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
23534 
23535   Style.SpacesInCStyleCastParentheses = true;
23536   Style.SpacesInParentheses = false;
23537   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
23538   Style.SpacesInCStyleCastParentheses = false;
23539   Style.SpacesInParentheses = true;
23540   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
23541   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
23542 }
23543 
23544 TEST_F(FormatTest, AmbersandInLamda) {
23545   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
23546   FormatStyle AlignStyle = getLLVMStyle();
23547   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
23548   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23549   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
23550   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23551 }
23552 
23553 TEST_F(FormatTest, SpacesInConditionalStatement) {
23554   FormatStyle Spaces = getLLVMStyle();
23555   Spaces.IfMacros.clear();
23556   Spaces.IfMacros.push_back("MYIF");
23557   Spaces.SpacesInConditionalStatement = true;
23558   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
23559   verifyFormat("if ( !a )\n  return;", Spaces);
23560   verifyFormat("if ( a )\n  return;", Spaces);
23561   verifyFormat("if constexpr ( a )\n  return;", Spaces);
23562   verifyFormat("MYIF ( a )\n  return;", Spaces);
23563   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
23564   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
23565   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
23566   verifyFormat("while ( a )\n  return;", Spaces);
23567   verifyFormat("while ( (a && b) )\n  return;", Spaces);
23568   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
23569   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
23570   // Check that space on the left of "::" is inserted as expected at beginning
23571   // of condition.
23572   verifyFormat("while ( ::func() )\n  return;", Spaces);
23573 
23574   // Check impact of ControlStatementsExceptControlMacros is honored.
23575   Spaces.SpaceBeforeParens =
23576       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
23577   verifyFormat("MYIF( a )\n  return;", Spaces);
23578   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
23579   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
23580 }
23581 
23582 TEST_F(FormatTest, AlternativeOperators) {
23583   // Test case for ensuring alternate operators are not
23584   // combined with their right most neighbour.
23585   verifyFormat("int a and b;");
23586   verifyFormat("int a and_eq b;");
23587   verifyFormat("int a bitand b;");
23588   verifyFormat("int a bitor b;");
23589   verifyFormat("int a compl b;");
23590   verifyFormat("int a not b;");
23591   verifyFormat("int a not_eq b;");
23592   verifyFormat("int a or b;");
23593   verifyFormat("int a xor b;");
23594   verifyFormat("int a xor_eq b;");
23595   verifyFormat("return this not_eq bitand other;");
23596   verifyFormat("bool operator not_eq(const X bitand other)");
23597 
23598   verifyFormat("int a and 5;");
23599   verifyFormat("int a and_eq 5;");
23600   verifyFormat("int a bitand 5;");
23601   verifyFormat("int a bitor 5;");
23602   verifyFormat("int a compl 5;");
23603   verifyFormat("int a not 5;");
23604   verifyFormat("int a not_eq 5;");
23605   verifyFormat("int a or 5;");
23606   verifyFormat("int a xor 5;");
23607   verifyFormat("int a xor_eq 5;");
23608 
23609   verifyFormat("int a compl(5);");
23610   verifyFormat("int a not(5);");
23611 
23612   /* FIXME handle alternate tokens
23613    * https://en.cppreference.com/w/cpp/language/operator_alternative
23614   // alternative tokens
23615   verifyFormat("compl foo();");     //  ~foo();
23616   verifyFormat("foo() <%%>;");      // foo();
23617   verifyFormat("void foo() <%%>;"); // void foo(){}
23618   verifyFormat("int a <:1:>;");     // int a[1];[
23619   verifyFormat("%:define ABC abc"); // #define ABC abc
23620   verifyFormat("%:%:");             // ##
23621   */
23622 }
23623 
23624 TEST_F(FormatTest, STLWhileNotDefineChed) {
23625   verifyFormat("#if defined(while)\n"
23626                "#define while EMIT WARNING C4005\n"
23627                "#endif // while");
23628 }
23629 
23630 TEST_F(FormatTest, OperatorSpacing) {
23631   FormatStyle Style = getLLVMStyle();
23632   Style.PointerAlignment = FormatStyle::PAS_Right;
23633   verifyFormat("Foo::operator*();", Style);
23634   verifyFormat("Foo::operator void *();", Style);
23635   verifyFormat("Foo::operator void **();", Style);
23636   verifyFormat("Foo::operator void *&();", Style);
23637   verifyFormat("Foo::operator void *&&();", Style);
23638   verifyFormat("Foo::operator void const *();", Style);
23639   verifyFormat("Foo::operator void const **();", Style);
23640   verifyFormat("Foo::operator void const *&();", Style);
23641   verifyFormat("Foo::operator void const *&&();", Style);
23642   verifyFormat("Foo::operator()(void *);", Style);
23643   verifyFormat("Foo::operator*(void *);", Style);
23644   verifyFormat("Foo::operator*();", Style);
23645   verifyFormat("Foo::operator**();", Style);
23646   verifyFormat("Foo::operator&();", Style);
23647   verifyFormat("Foo::operator<int> *();", Style);
23648   verifyFormat("Foo::operator<Foo> *();", Style);
23649   verifyFormat("Foo::operator<int> **();", Style);
23650   verifyFormat("Foo::operator<Foo> **();", Style);
23651   verifyFormat("Foo::operator<int> &();", Style);
23652   verifyFormat("Foo::operator<Foo> &();", Style);
23653   verifyFormat("Foo::operator<int> &&();", Style);
23654   verifyFormat("Foo::operator<Foo> &&();", Style);
23655   verifyFormat("Foo::operator<int> *&();", Style);
23656   verifyFormat("Foo::operator<Foo> *&();", Style);
23657   verifyFormat("Foo::operator<int> *&&();", Style);
23658   verifyFormat("Foo::operator<Foo> *&&();", Style);
23659   verifyFormat("operator*(int (*)(), class Foo);", Style);
23660 
23661   verifyFormat("Foo::operator&();", Style);
23662   verifyFormat("Foo::operator void &();", Style);
23663   verifyFormat("Foo::operator void const &();", Style);
23664   verifyFormat("Foo::operator()(void &);", Style);
23665   verifyFormat("Foo::operator&(void &);", Style);
23666   verifyFormat("Foo::operator&();", Style);
23667   verifyFormat("operator&(int (&)(), class Foo);", Style);
23668   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23669 
23670   verifyFormat("Foo::operator&&();", Style);
23671   verifyFormat("Foo::operator**();", Style);
23672   verifyFormat("Foo::operator void &&();", Style);
23673   verifyFormat("Foo::operator void const &&();", Style);
23674   verifyFormat("Foo::operator()(void &&);", Style);
23675   verifyFormat("Foo::operator&&(void &&);", Style);
23676   verifyFormat("Foo::operator&&();", Style);
23677   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23678   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23679   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23680                Style);
23681   verifyFormat("operator void **()", Style);
23682   verifyFormat("operator const FooRight<Object> &()", Style);
23683   verifyFormat("operator const FooRight<Object> *()", Style);
23684   verifyFormat("operator const FooRight<Object> **()", Style);
23685   verifyFormat("operator const FooRight<Object> *&()", Style);
23686   verifyFormat("operator const FooRight<Object> *&&()", Style);
23687 
23688   Style.PointerAlignment = FormatStyle::PAS_Left;
23689   verifyFormat("Foo::operator*();", Style);
23690   verifyFormat("Foo::operator**();", Style);
23691   verifyFormat("Foo::operator void*();", Style);
23692   verifyFormat("Foo::operator void**();", Style);
23693   verifyFormat("Foo::operator void*&();", Style);
23694   verifyFormat("Foo::operator void*&&();", Style);
23695   verifyFormat("Foo::operator void const*();", Style);
23696   verifyFormat("Foo::operator void const**();", Style);
23697   verifyFormat("Foo::operator void const*&();", Style);
23698   verifyFormat("Foo::operator void const*&&();", Style);
23699   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23700   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23701   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23702   verifyFormat("Foo::operator()(void*);", Style);
23703   verifyFormat("Foo::operator*(void*);", Style);
23704   verifyFormat("Foo::operator*();", Style);
23705   verifyFormat("Foo::operator<int>*();", Style);
23706   verifyFormat("Foo::operator<Foo>*();", Style);
23707   verifyFormat("Foo::operator<int>**();", Style);
23708   verifyFormat("Foo::operator<Foo>**();", Style);
23709   verifyFormat("Foo::operator<Foo>*&();", Style);
23710   verifyFormat("Foo::operator<int>&();", Style);
23711   verifyFormat("Foo::operator<Foo>&();", Style);
23712   verifyFormat("Foo::operator<int>&&();", Style);
23713   verifyFormat("Foo::operator<Foo>&&();", Style);
23714   verifyFormat("Foo::operator<int>*&();", Style);
23715   verifyFormat("Foo::operator<Foo>*&();", Style);
23716   verifyFormat("operator*(int (*)(), class Foo);", Style);
23717 
23718   verifyFormat("Foo::operator&();", Style);
23719   verifyFormat("Foo::operator void&();", Style);
23720   verifyFormat("Foo::operator void const&();", Style);
23721   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23722   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23723   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23724   verifyFormat("Foo::operator()(void&);", Style);
23725   verifyFormat("Foo::operator&(void&);", Style);
23726   verifyFormat("Foo::operator&();", Style);
23727   verifyFormat("operator&(int (&)(), class Foo);", Style);
23728   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23729   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23730 
23731   verifyFormat("Foo::operator&&();", Style);
23732   verifyFormat("Foo::operator void&&();", Style);
23733   verifyFormat("Foo::operator void const&&();", Style);
23734   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23735   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23736   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23737   verifyFormat("Foo::operator()(void&&);", Style);
23738   verifyFormat("Foo::operator&&(void&&);", Style);
23739   verifyFormat("Foo::operator&&();", Style);
23740   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23741   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23742   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23743                Style);
23744   verifyFormat("operator void**()", Style);
23745   verifyFormat("operator const FooLeft<Object>&()", Style);
23746   verifyFormat("operator const FooLeft<Object>*()", Style);
23747   verifyFormat("operator const FooLeft<Object>**()", Style);
23748   verifyFormat("operator const FooLeft<Object>*&()", Style);
23749   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23750 
23751   // PR45107
23752   verifyFormat("operator Vector<String>&();", Style);
23753   verifyFormat("operator const Vector<String>&();", Style);
23754   verifyFormat("operator foo::Bar*();", Style);
23755   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23756   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23757                Style);
23758 
23759   Style.PointerAlignment = FormatStyle::PAS_Middle;
23760   verifyFormat("Foo::operator*();", Style);
23761   verifyFormat("Foo::operator void *();", Style);
23762   verifyFormat("Foo::operator()(void *);", Style);
23763   verifyFormat("Foo::operator*(void *);", Style);
23764   verifyFormat("Foo::operator*();", Style);
23765   verifyFormat("operator*(int (*)(), class Foo);", Style);
23766 
23767   verifyFormat("Foo::operator&();", Style);
23768   verifyFormat("Foo::operator void &();", Style);
23769   verifyFormat("Foo::operator void const &();", Style);
23770   verifyFormat("Foo::operator()(void &);", Style);
23771   verifyFormat("Foo::operator&(void &);", Style);
23772   verifyFormat("Foo::operator&();", Style);
23773   verifyFormat("operator&(int (&)(), class Foo);", Style);
23774 
23775   verifyFormat("Foo::operator&&();", Style);
23776   verifyFormat("Foo::operator void &&();", Style);
23777   verifyFormat("Foo::operator void const &&();", Style);
23778   verifyFormat("Foo::operator()(void &&);", Style);
23779   verifyFormat("Foo::operator&&(void &&);", Style);
23780   verifyFormat("Foo::operator&&();", Style);
23781   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23782 }
23783 
23784 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23785   FormatStyle Style = getLLVMStyle();
23786   // PR46157
23787   verifyFormat("foo(operator+, -42);", Style);
23788   verifyFormat("foo(operator++, -42);", Style);
23789   verifyFormat("foo(operator--, -42);", Style);
23790   verifyFormat("foo(-42, operator--);", Style);
23791   verifyFormat("foo(-42, operator, );", Style);
23792   verifyFormat("foo(operator, , -42);", Style);
23793 }
23794 
23795 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23796   FormatStyle Style = getLLVMStyle();
23797   Style.WhitespaceSensitiveMacros.push_back("FOO");
23798 
23799   // Don't use the helpers here, since 'mess up' will change the whitespace
23800   // and these are all whitespace sensitive by definition
23801   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23802             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23803   EXPECT_EQ(
23804       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23805       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23806   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23807             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23808   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23809             "       Still=Intentional);",
23810             format("FOO(String-ized&Messy+But,: :\n"
23811                    "       Still=Intentional);",
23812                    Style));
23813   Style.AlignConsecutiveAssignments.Enabled = true;
23814   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23815             "       Still=Intentional);",
23816             format("FOO(String-ized=&Messy+But,: :\n"
23817                    "       Still=Intentional);",
23818                    Style));
23819 
23820   Style.ColumnLimit = 21;
23821   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23822             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23823 }
23824 
23825 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23826   // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
23827   // test its interaction with line wrapping
23828   FormatStyle Style = getLLVMStyleWithColumns(80);
23829   verifyFormat("namespace {\n"
23830                "int i;\n"
23831                "int j;\n"
23832                "} // namespace",
23833                Style);
23834 
23835   verifyFormat("namespace AAA {\n"
23836                "int i;\n"
23837                "int j;\n"
23838                "} // namespace AAA",
23839                Style);
23840 
23841   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23842             "int i;\n"
23843             "int j;\n"
23844             "} // namespace Averyveryveryverylongnamespace",
23845             format("namespace Averyveryveryverylongnamespace {\n"
23846                    "int i;\n"
23847                    "int j;\n"
23848                    "}",
23849                    Style));
23850 
23851   EXPECT_EQ(
23852       "namespace "
23853       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23854       "    went::mad::now {\n"
23855       "int i;\n"
23856       "int j;\n"
23857       "} // namespace\n"
23858       "  // "
23859       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23860       "went::mad::now",
23861       format("namespace "
23862              "would::it::save::you::a::lot::of::time::if_::i::"
23863              "just::gave::up::and_::went::mad::now {\n"
23864              "int i;\n"
23865              "int j;\n"
23866              "}",
23867              Style));
23868 
23869   // This used to duplicate the comment again and again on subsequent runs
23870   EXPECT_EQ(
23871       "namespace "
23872       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23873       "    went::mad::now {\n"
23874       "int i;\n"
23875       "int j;\n"
23876       "} // namespace\n"
23877       "  // "
23878       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23879       "went::mad::now",
23880       format("namespace "
23881              "would::it::save::you::a::lot::of::time::if_::i::"
23882              "just::gave::up::and_::went::mad::now {\n"
23883              "int i;\n"
23884              "int j;\n"
23885              "} // namespace\n"
23886              "  // "
23887              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23888              "and_::went::mad::now",
23889              Style));
23890 }
23891 
23892 TEST_F(FormatTest, LikelyUnlikely) {
23893   FormatStyle Style = getLLVMStyle();
23894 
23895   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23896                "  return 29;\n"
23897                "}",
23898                Style);
23899 
23900   verifyFormat("if (argc > 5) [[likely]] {\n"
23901                "  return 29;\n"
23902                "}",
23903                Style);
23904 
23905   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23906                "  return 29;\n"
23907                "} else [[likely]] {\n"
23908                "  return 42;\n"
23909                "}\n",
23910                Style);
23911 
23912   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23913                "  return 29;\n"
23914                "} else if (argc > 10) [[likely]] {\n"
23915                "  return 99;\n"
23916                "} else {\n"
23917                "  return 42;\n"
23918                "}\n",
23919                Style);
23920 
23921   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23922                "  return 29;\n"
23923                "}",
23924                Style);
23925 
23926   verifyFormat("if (argc > 5) [[unlikely]]\n"
23927                "  return 29;\n",
23928                Style);
23929   verifyFormat("if (argc > 5) [[likely]]\n"
23930                "  return 29;\n",
23931                Style);
23932 
23933   verifyFormat("while (limit > 0) [[unlikely]] {\n"
23934                "  --limit;\n"
23935                "}",
23936                Style);
23937   verifyFormat("for (auto &limit : limits) [[likely]] {\n"
23938                "  --limit;\n"
23939                "}",
23940                Style);
23941 
23942   verifyFormat("for (auto &limit : limits) [[unlikely]]\n"
23943                "  --limit;",
23944                Style);
23945   verifyFormat("while (limit > 0) [[likely]]\n"
23946                "  --limit;",
23947                Style);
23948 
23949   Style.AttributeMacros.push_back("UNLIKELY");
23950   Style.AttributeMacros.push_back("LIKELY");
23951   verifyFormat("if (argc > 5) UNLIKELY\n"
23952                "  return 29;\n",
23953                Style);
23954 
23955   verifyFormat("if (argc > 5) UNLIKELY {\n"
23956                "  return 29;\n"
23957                "}",
23958                Style);
23959   verifyFormat("if (argc > 5) UNLIKELY {\n"
23960                "  return 29;\n"
23961                "} else [[likely]] {\n"
23962                "  return 42;\n"
23963                "}\n",
23964                Style);
23965   verifyFormat("if (argc > 5) UNLIKELY {\n"
23966                "  return 29;\n"
23967                "} else LIKELY {\n"
23968                "  return 42;\n"
23969                "}\n",
23970                Style);
23971   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23972                "  return 29;\n"
23973                "} else LIKELY {\n"
23974                "  return 42;\n"
23975                "}\n",
23976                Style);
23977 
23978   verifyFormat("for (auto &limit : limits) UNLIKELY {\n"
23979                "  --limit;\n"
23980                "}",
23981                Style);
23982   verifyFormat("while (limit > 0) LIKELY {\n"
23983                "  --limit;\n"
23984                "}",
23985                Style);
23986 
23987   verifyFormat("while (limit > 0) UNLIKELY\n"
23988                "  --limit;",
23989                Style);
23990   verifyFormat("for (auto &limit : limits) LIKELY\n"
23991                "  --limit;",
23992                Style);
23993 }
23994 
23995 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23996   verifyFormat("Constructor()\n"
23997                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23998                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
23999                "aaaaaaaaaaaaaaaaaat))");
24000   verifyFormat("Constructor()\n"
24001                "    : aaaaaaaaaaaaa(aaaaaa), "
24002                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
24003 
24004   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
24005   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
24006   verifyFormat("Constructor()\n"
24007                "    : aaaaaa(aaaaaa),\n"
24008                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
24009                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
24010                StyleWithWhitespacePenalty);
24011   verifyFormat("Constructor()\n"
24012                "    : aaaaaaaaaaaaa(aaaaaa), "
24013                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
24014                StyleWithWhitespacePenalty);
24015 }
24016 
24017 TEST_F(FormatTest, LLVMDefaultStyle) {
24018   FormatStyle Style = getLLVMStyle();
24019   verifyFormat("extern \"C\" {\n"
24020                "int foo();\n"
24021                "}",
24022                Style);
24023 }
24024 TEST_F(FormatTest, GNUDefaultStyle) {
24025   FormatStyle Style = getGNUStyle();
24026   verifyFormat("extern \"C\"\n"
24027                "{\n"
24028                "  int foo ();\n"
24029                "}",
24030                Style);
24031 }
24032 TEST_F(FormatTest, MozillaDefaultStyle) {
24033   FormatStyle Style = getMozillaStyle();
24034   verifyFormat("extern \"C\"\n"
24035                "{\n"
24036                "  int foo();\n"
24037                "}",
24038                Style);
24039 }
24040 TEST_F(FormatTest, GoogleDefaultStyle) {
24041   FormatStyle Style = getGoogleStyle();
24042   verifyFormat("extern \"C\" {\n"
24043                "int foo();\n"
24044                "}",
24045                Style);
24046 }
24047 TEST_F(FormatTest, ChromiumDefaultStyle) {
24048   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
24049   verifyFormat("extern \"C\" {\n"
24050                "int foo();\n"
24051                "}",
24052                Style);
24053 }
24054 TEST_F(FormatTest, MicrosoftDefaultStyle) {
24055   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
24056   verifyFormat("extern \"C\"\n"
24057                "{\n"
24058                "    int foo();\n"
24059                "}",
24060                Style);
24061 }
24062 TEST_F(FormatTest, WebKitDefaultStyle) {
24063   FormatStyle Style = getWebKitStyle();
24064   verifyFormat("extern \"C\" {\n"
24065                "int foo();\n"
24066                "}",
24067                Style);
24068 }
24069 
24070 TEST_F(FormatTest, Concepts) {
24071   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
24072             FormatStyle::BBCDS_Always);
24073   verifyFormat("template <typename T>\n"
24074                "concept True = true;");
24075 
24076   verifyFormat("template <typename T>\n"
24077                "concept C = ((false || foo()) && C2<T>) ||\n"
24078                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
24079                getLLVMStyleWithColumns(60));
24080 
24081   verifyFormat("template <typename T>\n"
24082                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
24083                "sizeof(T) <= 8;");
24084 
24085   verifyFormat("template <typename T>\n"
24086                "concept DelayedCheck = true && requires(T t) {\n"
24087                "                                 t.bar();\n"
24088                "                                 t.baz();\n"
24089                "                               } && sizeof(T) <= 8;");
24090 
24091   verifyFormat("template <typename T>\n"
24092                "concept DelayedCheck = true && requires(T t) { // Comment\n"
24093                "                                 t.bar();\n"
24094                "                                 t.baz();\n"
24095                "                               } && sizeof(T) <= 8;");
24096 
24097   verifyFormat("template <typename T>\n"
24098                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
24099                "sizeof(T) <= 8;");
24100 
24101   verifyFormat("template <typename T>\n"
24102                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
24103                "&& sizeof(T) <= 8;");
24104 
24105   verifyFormat(
24106       "template <typename T>\n"
24107       "concept DelayedCheck = static_cast<bool>(0) ||\n"
24108       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24109 
24110   verifyFormat("template <typename T>\n"
24111                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
24112                "&& sizeof(T) <= 8;");
24113 
24114   verifyFormat(
24115       "template <typename T>\n"
24116       "concept DelayedCheck = (bool)(0) ||\n"
24117       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24118 
24119   verifyFormat("template <typename T>\n"
24120                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
24121                "&& sizeof(T) <= 8;");
24122 
24123   verifyFormat("template <typename T>\n"
24124                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
24125                "sizeof(T) <= 8;");
24126 
24127   verifyFormat("template <typename T>\n"
24128                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
24129                "               requires(T t) {\n"
24130                "                 t.bar();\n"
24131                "                 t.baz();\n"
24132                "               } && sizeof(T) <= 8 && !(4 < 3);",
24133                getLLVMStyleWithColumns(60));
24134 
24135   verifyFormat("template <typename T>\n"
24136                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
24137 
24138   verifyFormat("template <typename T>\n"
24139                "concept C = foo();");
24140 
24141   verifyFormat("template <typename T>\n"
24142                "concept C = foo(T());");
24143 
24144   verifyFormat("template <typename T>\n"
24145                "concept C = foo(T{});");
24146 
24147   verifyFormat("template <typename T>\n"
24148                "concept Size = V<sizeof(T)>::Value > 5;");
24149 
24150   verifyFormat("template <typename T>\n"
24151                "concept True = S<T>::Value;");
24152 
24153   verifyFormat(
24154       "template <typename T>\n"
24155       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
24156       "            sizeof(T) <= 8;");
24157 
24158   // FIXME: This is misformatted because the fake l paren starts at bool, not at
24159   // the lambda l square.
24160   verifyFormat("template <typename T>\n"
24161                "concept C = [] -> bool { return true; }() && requires(T t) { "
24162                "t.bar(); } &&\n"
24163                "                      sizeof(T) <= 8;");
24164 
24165   verifyFormat(
24166       "template <typename T>\n"
24167       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
24168       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24169 
24170   verifyFormat("template <typename T>\n"
24171                "concept C = decltype([]() { return std::true_type{}; "
24172                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24173                getLLVMStyleWithColumns(120));
24174 
24175   verifyFormat("template <typename T>\n"
24176                "concept C = decltype([]() -> std::true_type { return {}; "
24177                "}())::value &&\n"
24178                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24179 
24180   verifyFormat("template <typename T>\n"
24181                "concept C = true;\n"
24182                "Foo Bar;");
24183 
24184   verifyFormat("template <typename T>\n"
24185                "concept Hashable = requires(T a) {\n"
24186                "                     { std::hash<T>{}(a) } -> "
24187                "std::convertible_to<std::size_t>;\n"
24188                "                   };");
24189 
24190   verifyFormat(
24191       "template <typename T>\n"
24192       "concept EqualityComparable = requires(T a, T b) {\n"
24193       "                               { a == b } -> std::same_as<bool>;\n"
24194       "                             };");
24195 
24196   verifyFormat(
24197       "template <typename T>\n"
24198       "concept EqualityComparable = requires(T a, T b) {\n"
24199       "                               { a == b } -> std::same_as<bool>;\n"
24200       "                               { a != b } -> std::same_as<bool>;\n"
24201       "                             };");
24202 
24203   verifyFormat("template <typename T>\n"
24204                "concept WeakEqualityComparable = requires(T a, T b) {\n"
24205                "                                   { a == b };\n"
24206                "                                   { a != b };\n"
24207                "                                 };");
24208 
24209   verifyFormat("template <typename T>\n"
24210                "concept HasSizeT = requires { typename T::size_t; };");
24211 
24212   verifyFormat("template <typename T>\n"
24213                "concept Semiregular =\n"
24214                "    DefaultConstructible<T> && CopyConstructible<T> && "
24215                "CopyAssignable<T> &&\n"
24216                "    requires(T a, std::size_t n) {\n"
24217                "      requires Same<T *, decltype(&a)>;\n"
24218                "      { a.~T() } noexcept;\n"
24219                "      requires Same<T *, decltype(new T)>;\n"
24220                "      requires Same<T *, decltype(new T[n])>;\n"
24221                "      { delete new T; };\n"
24222                "      { delete new T[n]; };\n"
24223                "    };");
24224 
24225   verifyFormat("template <typename T>\n"
24226                "concept Semiregular =\n"
24227                "    requires(T a, std::size_t n) {\n"
24228                "      requires Same<T *, decltype(&a)>;\n"
24229                "      { a.~T() } noexcept;\n"
24230                "      requires Same<T *, decltype(new T)>;\n"
24231                "      requires Same<T *, decltype(new T[n])>;\n"
24232                "      { delete new T; };\n"
24233                "      { delete new T[n]; };\n"
24234                "      { new T } -> std::same_as<T *>;\n"
24235                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
24236                "CopyAssignable<T>;");
24237 
24238   verifyFormat(
24239       "template <typename T>\n"
24240       "concept Semiregular =\n"
24241       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
24242       "                                 requires Same<T *, decltype(&a)>;\n"
24243       "                                 { a.~T() } noexcept;\n"
24244       "                                 requires Same<T *, decltype(new T)>;\n"
24245       "                                 requires Same<T *, decltype(new "
24246       "T[n])>;\n"
24247       "                                 { delete new T; };\n"
24248       "                                 { delete new T[n]; };\n"
24249       "                               } && CopyConstructible<T> && "
24250       "CopyAssignable<T>;");
24251 
24252   verifyFormat("template <typename T>\n"
24253                "concept Two = requires(T t) {\n"
24254                "                { t.foo() } -> std::same_as<Bar>;\n"
24255                "              } && requires(T &&t) {\n"
24256                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
24257                "                   };");
24258 
24259   verifyFormat(
24260       "template <typename T>\n"
24261       "concept C = requires(T x) {\n"
24262       "              { *x } -> std::convertible_to<typename T::inner>;\n"
24263       "              { x + 1 } noexcept -> std::same_as<int>;\n"
24264       "              { x * 1 } -> std::convertible_to<T>;\n"
24265       "            };");
24266 
24267   verifyFormat(
24268       "template <typename T, typename U = T>\n"
24269       "concept Swappable = requires(T &&t, U &&u) {\n"
24270       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
24271       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
24272       "                    };");
24273 
24274   verifyFormat("template <typename T, typename U>\n"
24275                "concept Common = requires(T &&t, U &&u) {\n"
24276                "                   typename CommonType<T, U>;\n"
24277                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
24278                "                 };");
24279 
24280   verifyFormat("template <typename T, typename U>\n"
24281                "concept Common = requires(T &&t, U &&u) {\n"
24282                "                   typename CommonType<T, U>;\n"
24283                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
24284                "                 };");
24285 
24286   verifyFormat(
24287       "template <typename T>\n"
24288       "concept C = requires(T t) {\n"
24289       "              requires Bar<T> && Foo<T>;\n"
24290       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24291       "            };");
24292 
24293   verifyFormat("template <typename T>\n"
24294                "concept HasFoo = requires(T t) {\n"
24295                "                   { t.foo() };\n"
24296                "                   t.foo();\n"
24297                "                 };\n"
24298                "template <typename T>\n"
24299                "concept HasBar = requires(T t) {\n"
24300                "                   { t.bar() };\n"
24301                "                   t.bar();\n"
24302                "                 };");
24303 
24304   verifyFormat("template <typename T>\n"
24305                "concept Large = sizeof(T) > 10;");
24306 
24307   verifyFormat("template <typename T, typename U>\n"
24308                "concept FooableWith = requires(T t, U u) {\n"
24309                "                        typename T::foo_type;\n"
24310                "                        { t.foo(u) } -> typename T::foo_type;\n"
24311                "                        t++;\n"
24312                "                      };\n"
24313                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
24314 
24315   verifyFormat("template <typename T>\n"
24316                "concept Context = is_specialization_of_v<context, T>;");
24317 
24318   verifyFormat("template <typename T>\n"
24319                "concept Node = std::is_object_v<T>;");
24320 
24321   verifyFormat("template <class T>\n"
24322                "concept integral = __is_integral(T);");
24323 
24324   verifyFormat("template <class T>\n"
24325                "concept is2D = __array_extent(T, 1) == 2;");
24326 
24327   verifyFormat("template <class T>\n"
24328                "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
24329 
24330   verifyFormat("template <class T, class T2>\n"
24331                "concept Same = __is_same_as<T, T2>;");
24332 
24333   verifyFormat(
24334       "template <class _InIt, class _OutIt>\n"
24335       "concept _Can_reread_dest =\n"
24336       "    std::forward_iterator<_OutIt> &&\n"
24337       "    std::same_as<std::iter_value_t<_InIt>, std::iter_value_t<_OutIt>>;");
24338 
24339   auto Style = getLLVMStyle();
24340   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
24341 
24342   verifyFormat(
24343       "template <typename T>\n"
24344       "concept C = requires(T t) {\n"
24345       "              requires Bar<T> && Foo<T>;\n"
24346       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24347       "            };",
24348       Style);
24349 
24350   verifyFormat("template <typename T>\n"
24351                "concept HasFoo = requires(T t) {\n"
24352                "                   { t.foo() };\n"
24353                "                   t.foo();\n"
24354                "                 };\n"
24355                "template <typename T>\n"
24356                "concept HasBar = requires(T t) {\n"
24357                "                   { t.bar() };\n"
24358                "                   t.bar();\n"
24359                "                 };",
24360                Style);
24361 
24362   verifyFormat("template <typename T> concept True = true;", Style);
24363 
24364   verifyFormat("template <typename T>\n"
24365                "concept C = decltype([]() -> std::true_type { return {}; "
24366                "}())::value &&\n"
24367                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24368                Style);
24369 
24370   verifyFormat("template <typename T>\n"
24371                "concept Semiregular =\n"
24372                "    DefaultConstructible<T> && CopyConstructible<T> && "
24373                "CopyAssignable<T> &&\n"
24374                "    requires(T a, std::size_t n) {\n"
24375                "      requires Same<T *, decltype(&a)>;\n"
24376                "      { a.~T() } noexcept;\n"
24377                "      requires Same<T *, decltype(new T)>;\n"
24378                "      requires Same<T *, decltype(new T[n])>;\n"
24379                "      { delete new T; };\n"
24380                "      { delete new T[n]; };\n"
24381                "    };",
24382                Style);
24383 
24384   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
24385 
24386   verifyFormat("template <typename T> concept C =\n"
24387                "    requires(T t) {\n"
24388                "      requires Bar<T> && Foo<T>;\n"
24389                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24390                "    };",
24391                Style);
24392 
24393   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
24394                "                                         { t.foo() };\n"
24395                "                                         t.foo();\n"
24396                "                                       };\n"
24397                "template <typename T> concept HasBar = requires(T t) {\n"
24398                "                                         { t.bar() };\n"
24399                "                                         t.bar();\n"
24400                "                                       };",
24401                Style);
24402 
24403   verifyFormat("template <typename T> concept True = true;", Style);
24404 
24405   verifyFormat(
24406       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
24407       "                                    return {};\n"
24408       "                                  }())::value &&\n"
24409       "                                  requires(T t) { t.bar(); } && "
24410       "sizeof(T) <= 8;",
24411       Style);
24412 
24413   verifyFormat("template <typename T> concept Semiregular =\n"
24414                "    DefaultConstructible<T> && CopyConstructible<T> && "
24415                "CopyAssignable<T> &&\n"
24416                "    requires(T a, std::size_t n) {\n"
24417                "      requires Same<T *, decltype(&a)>;\n"
24418                "      { a.~T() } noexcept;\n"
24419                "      requires Same<T *, decltype(new T)>;\n"
24420                "      requires Same<T *, decltype(new T[n])>;\n"
24421                "      { delete new T; };\n"
24422                "      { delete new T[n]; };\n"
24423                "    };",
24424                Style);
24425 
24426   // The following tests are invalid C++, we just want to make sure we don't
24427   // assert.
24428   verifyFormat("template <typename T>\n"
24429                "concept C = requires C2<T>;");
24430 
24431   verifyFormat("template <typename T>\n"
24432                "concept C = 5 + 4;");
24433 
24434   verifyFormat("template <typename T>\n"
24435                "concept C =\n"
24436                "class X;");
24437 
24438   verifyFormat("template <typename T>\n"
24439                "concept C = [] && true;");
24440 
24441   verifyFormat("template <typename T>\n"
24442                "concept C = [] && requires(T t) { typename T::size_type; };");
24443 }
24444 
24445 TEST_F(FormatTest, RequiresClausesPositions) {
24446   auto Style = getLLVMStyle();
24447   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
24448   EXPECT_EQ(Style.IndentRequiresClause, true);
24449 
24450   verifyFormat("template <typename T>\n"
24451                "  requires(Foo<T> && std::trait<T>)\n"
24452                "struct Bar;",
24453                Style);
24454 
24455   verifyFormat("template <typename T>\n"
24456                "  requires(Foo<T> && std::trait<T>)\n"
24457                "class Bar {\n"
24458                "public:\n"
24459                "  Bar(T t);\n"
24460                "  bool baz();\n"
24461                "};",
24462                Style);
24463 
24464   verifyFormat(
24465       "template <typename T>\n"
24466       "  requires requires(T &&t) {\n"
24467       "             typename T::I;\n"
24468       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
24469       "           }\n"
24470       "Bar(T) -> Bar<typename T::I>;",
24471       Style);
24472 
24473   verifyFormat("template <typename T>\n"
24474                "  requires(Foo<T> && std::trait<T>)\n"
24475                "constexpr T MyGlobal;",
24476                Style);
24477 
24478   verifyFormat("template <typename T>\n"
24479                "  requires Foo<T> && requires(T t) {\n"
24480                "                       { t.baz() } -> std::same_as<bool>;\n"
24481                "                       requires std::same_as<T::Factor, int>;\n"
24482                "                     }\n"
24483                "inline int bar(T t) {\n"
24484                "  return t.baz() ? T::Factor : 5;\n"
24485                "}",
24486                Style);
24487 
24488   verifyFormat("template <typename T>\n"
24489                "inline int bar(T t)\n"
24490                "  requires Foo<T> && requires(T t) {\n"
24491                "                       { t.baz() } -> std::same_as<bool>;\n"
24492                "                       requires std::same_as<T::Factor, int>;\n"
24493                "                     }\n"
24494                "{\n"
24495                "  return t.baz() ? T::Factor : 5;\n"
24496                "}",
24497                Style);
24498 
24499   verifyFormat("template <typename T>\n"
24500                "  requires F<T>\n"
24501                "int bar(T t) {\n"
24502                "  return 5;\n"
24503                "}",
24504                Style);
24505 
24506   verifyFormat("template <typename T>\n"
24507                "int bar(T t)\n"
24508                "  requires F<T>\n"
24509                "{\n"
24510                "  return 5;\n"
24511                "}",
24512                Style);
24513 
24514   verifyFormat("template <typename T>\n"
24515                "int bar(T t)\n"
24516                "  requires F<T>;",
24517                Style);
24518 
24519   Style.IndentRequiresClause = false;
24520   verifyFormat("template <typename T>\n"
24521                "requires F<T>\n"
24522                "int bar(T t) {\n"
24523                "  return 5;\n"
24524                "}",
24525                Style);
24526 
24527   verifyFormat("template <typename T>\n"
24528                "int bar(T t)\n"
24529                "requires F<T>\n"
24530                "{\n"
24531                "  return 5;\n"
24532                "}",
24533                Style);
24534 
24535   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
24536   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
24537                "template <typename T> requires Foo<T> void bar() {}\n"
24538                "template <typename T> void bar() requires Foo<T> {}\n"
24539                "template <typename T> void bar() requires Foo<T>;\n"
24540                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
24541                Style);
24542 
24543   auto ColumnStyle = Style;
24544   ColumnStyle.ColumnLimit = 40;
24545   verifyFormat("template <typename AAAAAAA>\n"
24546                "requires Foo<T> struct Bar {};\n"
24547                "template <typename AAAAAAA>\n"
24548                "requires Foo<T> void bar() {}\n"
24549                "template <typename AAAAAAA>\n"
24550                "void bar() requires Foo<T> {}\n"
24551                "template <typename AAAAAAA>\n"
24552                "requires Foo<T> Baz(T) -> Baz<T>;",
24553                ColumnStyle);
24554 
24555   verifyFormat("template <typename T>\n"
24556                "requires Foo<AAAAAAA> struct Bar {};\n"
24557                "template <typename T>\n"
24558                "requires Foo<AAAAAAA> void bar() {}\n"
24559                "template <typename T>\n"
24560                "void bar() requires Foo<AAAAAAA> {}\n"
24561                "template <typename T>\n"
24562                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
24563                ColumnStyle);
24564 
24565   verifyFormat("template <typename AAAAAAA>\n"
24566                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24567                "struct Bar {};\n"
24568                "template <typename AAAAAAA>\n"
24569                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24570                "void bar() {}\n"
24571                "template <typename AAAAAAA>\n"
24572                "void bar()\n"
24573                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24574                "template <typename AAAAAAA>\n"
24575                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24576                "template <typename AAAAAAA>\n"
24577                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24578                "Bar(T) -> Bar<T>;",
24579                ColumnStyle);
24580 
24581   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24582   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24583 
24584   verifyFormat("template <typename T>\n"
24585                "requires Foo<T> struct Bar {};\n"
24586                "template <typename T>\n"
24587                "requires Foo<T> void bar() {}\n"
24588                "template <typename T>\n"
24589                "void bar()\n"
24590                "requires Foo<T> {}\n"
24591                "template <typename T>\n"
24592                "void bar()\n"
24593                "requires Foo<T>;\n"
24594                "template <typename T>\n"
24595                "requires Foo<T> Bar(T) -> Bar<T>;",
24596                Style);
24597 
24598   verifyFormat("template <typename AAAAAAA>\n"
24599                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24600                "struct Bar {};\n"
24601                "template <typename AAAAAAA>\n"
24602                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24603                "void bar() {}\n"
24604                "template <typename AAAAAAA>\n"
24605                "void bar()\n"
24606                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24607                "template <typename AAAAAAA>\n"
24608                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24609                "template <typename AAAAAAA>\n"
24610                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24611                "Bar(T) -> Bar<T>;",
24612                ColumnStyle);
24613 
24614   Style.IndentRequiresClause = true;
24615   ColumnStyle.IndentRequiresClause = true;
24616 
24617   verifyFormat("template <typename T>\n"
24618                "  requires Foo<T> struct Bar {};\n"
24619                "template <typename T>\n"
24620                "  requires Foo<T> void bar() {}\n"
24621                "template <typename T>\n"
24622                "void bar()\n"
24623                "  requires Foo<T> {}\n"
24624                "template <typename T>\n"
24625                "  requires Foo<T> Bar(T) -> Bar<T>;",
24626                Style);
24627 
24628   verifyFormat("template <typename AAAAAAA>\n"
24629                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24630                "struct Bar {};\n"
24631                "template <typename AAAAAAA>\n"
24632                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24633                "void bar() {}\n"
24634                "template <typename AAAAAAA>\n"
24635                "void bar()\n"
24636                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24637                "template <typename AAAAAAA>\n"
24638                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24639                "template <typename AAAAAAA>\n"
24640                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24641                "Bar(T) -> Bar<T>;",
24642                ColumnStyle);
24643 
24644   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24645   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24646 
24647   verifyFormat("template <typename T> requires Foo<T>\n"
24648                "struct Bar {};\n"
24649                "template <typename T> requires Foo<T>\n"
24650                "void bar() {}\n"
24651                "template <typename T>\n"
24652                "void bar() requires Foo<T>\n"
24653                "{}\n"
24654                "template <typename T> void bar() requires Foo<T>;\n"
24655                "template <typename T> requires Foo<T>\n"
24656                "Bar(T) -> Bar<T>;",
24657                Style);
24658 
24659   verifyFormat("template <typename AAAAAAA>\n"
24660                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24661                "struct Bar {};\n"
24662                "template <typename AAAAAAA>\n"
24663                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24664                "void bar() {}\n"
24665                "template <typename AAAAAAA>\n"
24666                "void bar()\n"
24667                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24668                "{}\n"
24669                "template <typename AAAAAAA>\n"
24670                "requires Foo<AAAAAAAA>\n"
24671                "Bar(T) -> Bar<T>;\n"
24672                "template <typename AAAAAAA>\n"
24673                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24674                "Bar(T) -> Bar<T>;",
24675                ColumnStyle);
24676 }
24677 
24678 TEST_F(FormatTest, RequiresClauses) {
24679   verifyFormat("struct [[nodiscard]] zero_t {\n"
24680                "  template <class T>\n"
24681                "    requires requires { number_zero_v<T>; }\n"
24682                "  [[nodiscard]] constexpr operator T() const {\n"
24683                "    return number_zero_v<T>;\n"
24684                "  }\n"
24685                "};");
24686 
24687   auto Style = getLLVMStyle();
24688 
24689   verifyFormat(
24690       "template <typename T>\n"
24691       "  requires is_default_constructible_v<hash<T>> and\n"
24692       "           is_copy_constructible_v<hash<T>> and\n"
24693       "           is_move_constructible_v<hash<T>> and\n"
24694       "           is_copy_assignable_v<hash<T>> and "
24695       "is_move_assignable_v<hash<T>> and\n"
24696       "           is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
24697       "           is_callable_v<hash<T>(T)> and\n"
24698       "           is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n"
24699       "           is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n"
24700       "           is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
24701       "struct S {};",
24702       Style);
24703 
24704   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
24705   verifyFormat(
24706       "template <typename T>\n"
24707       "  requires is_default_constructible_v<hash<T>>\n"
24708       "           and is_copy_constructible_v<hash<T>>\n"
24709       "           and is_move_constructible_v<hash<T>>\n"
24710       "           and is_copy_assignable_v<hash<T>> and "
24711       "is_move_assignable_v<hash<T>>\n"
24712       "           and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
24713       "           and is_callable_v<hash<T>(T)>\n"
24714       "           and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n"
24715       "           and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n"
24716       "           and is_same_v<size_t, decltype(hash<T>(declval<const T "
24717       "&>()))>\n"
24718       "struct S {};",
24719       Style);
24720 
24721   Style = getLLVMStyle();
24722   Style.ConstructorInitializerIndentWidth = 4;
24723   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
24724   Style.PackConstructorInitializers = FormatStyle::PCIS_Never;
24725   verifyFormat("constexpr Foo(Foo const &other)\n"
24726                "  requires std::is_copy_constructible<T>\n"
24727                "    : value{other.value} {\n"
24728                "  do_magic();\n"
24729                "  do_more_magic();\n"
24730                "}",
24731                Style);
24732 
24733   // Not a clause, but we once hit an assert.
24734   verifyFormat("#if 0\n"
24735                "#else\n"
24736                "foo();\n"
24737                "#endif\n"
24738                "bar(requires);");
24739 }
24740 
24741 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24742   FormatStyle Style = getLLVMStyle();
24743   StringRef Source = "void Foo::slot() {\n"
24744                      "  unsigned char MyChar = 'x';\n"
24745                      "  emit signal(MyChar);\n"
24746                      "  Q_EMIT signal(MyChar);\n"
24747                      "}";
24748 
24749   EXPECT_EQ(Source, format(Source, Style));
24750 
24751   Style.AlignConsecutiveDeclarations.Enabled = true;
24752   EXPECT_EQ("void Foo::slot() {\n"
24753             "  unsigned char MyChar = 'x';\n"
24754             "  emit          signal(MyChar);\n"
24755             "  Q_EMIT signal(MyChar);\n"
24756             "}",
24757             format(Source, Style));
24758 
24759   Style.StatementAttributeLikeMacros.push_back("emit");
24760   EXPECT_EQ(Source, format(Source, Style));
24761 
24762   Style.StatementAttributeLikeMacros = {};
24763   EXPECT_EQ("void Foo::slot() {\n"
24764             "  unsigned char MyChar = 'x';\n"
24765             "  emit          signal(MyChar);\n"
24766             "  Q_EMIT        signal(MyChar);\n"
24767             "}",
24768             format(Source, Style));
24769 }
24770 
24771 TEST_F(FormatTest, IndentAccessModifiers) {
24772   FormatStyle Style = getLLVMStyle();
24773   Style.IndentAccessModifiers = true;
24774   // Members are *two* levels below the record;
24775   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24776   verifyFormat("class C {\n"
24777                "    int i;\n"
24778                "};\n",
24779                Style);
24780   verifyFormat("union C {\n"
24781                "    int i;\n"
24782                "    unsigned u;\n"
24783                "};\n",
24784                Style);
24785   // Access modifiers should be indented one level below the record.
24786   verifyFormat("class C {\n"
24787                "  public:\n"
24788                "    int i;\n"
24789                "};\n",
24790                Style);
24791   verifyFormat("struct S {\n"
24792                "  private:\n"
24793                "    class C {\n"
24794                "        int j;\n"
24795                "\n"
24796                "      public:\n"
24797                "        C();\n"
24798                "    };\n"
24799                "\n"
24800                "  public:\n"
24801                "    int i;\n"
24802                "};\n",
24803                Style);
24804   // Enumerations are not records and should be unaffected.
24805   Style.AllowShortEnumsOnASingleLine = false;
24806   verifyFormat("enum class E {\n"
24807                "  A,\n"
24808                "  B\n"
24809                "};\n",
24810                Style);
24811   // Test with a different indentation width;
24812   // also proves that the result is Style.AccessModifierOffset agnostic.
24813   Style.IndentWidth = 3;
24814   verifyFormat("class C {\n"
24815                "   public:\n"
24816                "      int i;\n"
24817                "};\n",
24818                Style);
24819 }
24820 
24821 TEST_F(FormatTest, LimitlessStringsAndComments) {
24822   auto Style = getLLVMStyleWithColumns(0);
24823   constexpr StringRef Code =
24824       "/**\n"
24825       " * This is a multiline comment with quite some long lines, at least for "
24826       "the LLVM Style.\n"
24827       " * We will redo this with strings and line comments. Just to  check if "
24828       "everything is working.\n"
24829       " */\n"
24830       "bool foo() {\n"
24831       "  /* Single line multi line comment. */\n"
24832       "  const std::string String = \"This is a multiline string with quite "
24833       "some long lines, at least for the LLVM Style.\"\n"
24834       "                             \"We already did it with multi line "
24835       "comments, and we will do it with line comments. Just to check if "
24836       "everything is working.\";\n"
24837       "  // This is a line comment (block) with quite some long lines, at "
24838       "least for the LLVM Style.\n"
24839       "  // We already did this with multi line comments and strings. Just to "
24840       "check if everything is working.\n"
24841       "  const std::string SmallString = \"Hello World\";\n"
24842       "  // Small line comment\n"
24843       "  return String.size() > SmallString.size();\n"
24844       "}";
24845   EXPECT_EQ(Code, format(Code, Style));
24846 }
24847 
24848 TEST_F(FormatTest, FormatDecayCopy) {
24849   // error cases from unit tests
24850   verifyFormat("foo(auto())");
24851   verifyFormat("foo(auto{})");
24852   verifyFormat("foo(auto({}))");
24853   verifyFormat("foo(auto{{}})");
24854 
24855   verifyFormat("foo(auto(1))");
24856   verifyFormat("foo(auto{1})");
24857   verifyFormat("foo(new auto(1))");
24858   verifyFormat("foo(new auto{1})");
24859   verifyFormat("decltype(auto(1)) x;");
24860   verifyFormat("decltype(auto{1}) x;");
24861   verifyFormat("auto(x);");
24862   verifyFormat("auto{x};");
24863   verifyFormat("new auto{x};");
24864   verifyFormat("auto{x} = y;");
24865   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24866                                 // the user's own fault
24867   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24868                                          // clearly the user's own fault
24869   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24870 }
24871 
24872 TEST_F(FormatTest, Cpp20ModulesSupport) {
24873   FormatStyle Style = getLLVMStyle();
24874   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24875   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24876 
24877   verifyFormat("export import foo;", Style);
24878   verifyFormat("export import foo:bar;", Style);
24879   verifyFormat("export import foo.bar;", Style);
24880   verifyFormat("export import foo.bar:baz;", Style);
24881   verifyFormat("export import :bar;", Style);
24882   verifyFormat("export module foo:bar;", Style);
24883   verifyFormat("export module foo;", Style);
24884   verifyFormat("export module foo.bar;", Style);
24885   verifyFormat("export module foo.bar:baz;", Style);
24886   verifyFormat("export import <string_view>;", Style);
24887 
24888   verifyFormat("export type_name var;", Style);
24889   verifyFormat("template <class T> export using A = B<T>;", Style);
24890   verifyFormat("export using A = B;", Style);
24891   verifyFormat("export int func() {\n"
24892                "  foo();\n"
24893                "}",
24894                Style);
24895   verifyFormat("export struct {\n"
24896                "  int foo;\n"
24897                "};",
24898                Style);
24899   verifyFormat("export {\n"
24900                "  int foo;\n"
24901                "};",
24902                Style);
24903   verifyFormat("export export char const *hello() { return \"hello\"; }");
24904 
24905   verifyFormat("import bar;", Style);
24906   verifyFormat("import foo.bar;", Style);
24907   verifyFormat("import foo:bar;", Style);
24908   verifyFormat("import :bar;", Style);
24909   verifyFormat("import <ctime>;", Style);
24910   verifyFormat("import \"header\";", Style);
24911 
24912   verifyFormat("module foo;", Style);
24913   verifyFormat("module foo:bar;", Style);
24914   verifyFormat("module foo.bar;", Style);
24915   verifyFormat("module;", Style);
24916 
24917   verifyFormat("export namespace hi {\n"
24918                "const char *sayhi();\n"
24919                "}",
24920                Style);
24921 
24922   verifyFormat("module :private;", Style);
24923   verifyFormat("import <foo/bar.h>;", Style);
24924   verifyFormat("import foo...bar;", Style);
24925   verifyFormat("import ..........;", Style);
24926   verifyFormat("module foo:private;", Style);
24927   verifyFormat("import a", Style);
24928   verifyFormat("module a", Style);
24929   verifyFormat("export import a", Style);
24930   verifyFormat("export module a", Style);
24931 
24932   verifyFormat("import", Style);
24933   verifyFormat("module", Style);
24934   verifyFormat("export", Style);
24935 }
24936 
24937 TEST_F(FormatTest, CoroutineForCoawait) {
24938   FormatStyle Style = getLLVMStyle();
24939   verifyFormat("for co_await (auto x : range())\n  ;");
24940   verifyFormat("for (auto i : arr) {\n"
24941                "}",
24942                Style);
24943   verifyFormat("for co_await (auto i : arr) {\n"
24944                "}",
24945                Style);
24946   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24947                "}",
24948                Style);
24949 }
24950 
24951 TEST_F(FormatTest, CoroutineCoAwait) {
24952   verifyFormat("int x = co_await foo();");
24953   verifyFormat("int x = (co_await foo());");
24954   verifyFormat("co_await (42);");
24955   verifyFormat("void operator co_await(int);");
24956   verifyFormat("void operator co_await(a);");
24957   verifyFormat("co_await a;");
24958   verifyFormat("co_await missing_await_resume{};");
24959   verifyFormat("co_await a; // comment");
24960   verifyFormat("void test0() { co_await a; }");
24961   verifyFormat("co_await co_await co_await foo();");
24962   verifyFormat("co_await foo().bar();");
24963   verifyFormat("co_await [this]() -> Task { co_return x; }");
24964   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24965                "foo(); }(x, y);");
24966 
24967   FormatStyle Style = getLLVMStyleWithColumns(40);
24968   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24969                "  co_return co_await foo();\n"
24970                "}(x, y);",
24971                Style);
24972   verifyFormat("co_await;");
24973 }
24974 
24975 TEST_F(FormatTest, CoroutineCoYield) {
24976   verifyFormat("int x = co_yield foo();");
24977   verifyFormat("int x = (co_yield foo());");
24978   verifyFormat("co_yield (42);");
24979   verifyFormat("co_yield {42};");
24980   verifyFormat("co_yield 42;");
24981   verifyFormat("co_yield n++;");
24982   verifyFormat("co_yield ++n;");
24983   verifyFormat("co_yield;");
24984 }
24985 
24986 TEST_F(FormatTest, CoroutineCoReturn) {
24987   verifyFormat("co_return (42);");
24988   verifyFormat("co_return;");
24989   verifyFormat("co_return {};");
24990   verifyFormat("co_return x;");
24991   verifyFormat("co_return co_await foo();");
24992   verifyFormat("co_return co_yield foo();");
24993 }
24994 
24995 TEST_F(FormatTest, EmptyShortBlock) {
24996   auto Style = getLLVMStyle();
24997   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24998 
24999   verifyFormat("try {\n"
25000                "  doA();\n"
25001                "} catch (Exception &e) {\n"
25002                "  e.printStackTrace();\n"
25003                "}\n",
25004                Style);
25005 
25006   verifyFormat("try {\n"
25007                "  doA();\n"
25008                "} catch (Exception &e) {}\n",
25009                Style);
25010 }
25011 
25012 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
25013   auto Style = getLLVMStyle();
25014 
25015   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
25016   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
25017   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
25018   verifyFormat("struct Y<[] { return 0; }> {};", Style);
25019 
25020   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
25021   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
25022 }
25023 
25024 TEST_F(FormatTest, InsertBraces) {
25025   FormatStyle Style = getLLVMStyle();
25026   Style.InsertBraces = true;
25027 
25028   verifyFormat("// clang-format off\n"
25029                "// comment\n"
25030                "if (a) f();\n"
25031                "// clang-format on\n"
25032                "if (b) {\n"
25033                "  g();\n"
25034                "}",
25035                "// clang-format off\n"
25036                "// comment\n"
25037                "if (a) f();\n"
25038                "// clang-format on\n"
25039                "if (b) g();",
25040                Style);
25041 
25042   verifyFormat("if (a) {\n"
25043                "  switch (b) {\n"
25044                "  case 1:\n"
25045                "    c = 0;\n"
25046                "    break;\n"
25047                "  default:\n"
25048                "    c = 1;\n"
25049                "  }\n"
25050                "}",
25051                "if (a)\n"
25052                "  switch (b) {\n"
25053                "  case 1:\n"
25054                "    c = 0;\n"
25055                "    break;\n"
25056                "  default:\n"
25057                "    c = 1;\n"
25058                "  }",
25059                Style);
25060 
25061   verifyFormat("for (auto node : nodes) {\n"
25062                "  if (node) {\n"
25063                "    break;\n"
25064                "  }\n"
25065                "}",
25066                "for (auto node : nodes)\n"
25067                "  if (node)\n"
25068                "    break;",
25069                Style);
25070 
25071   verifyFormat("for (auto node : nodes) {\n"
25072                "  if (node)\n"
25073                "}",
25074                "for (auto node : nodes)\n"
25075                "  if (node)",
25076                Style);
25077 
25078   verifyFormat("do {\n"
25079                "  --a;\n"
25080                "} while (a);",
25081                "do\n"
25082                "  --a;\n"
25083                "while (a);",
25084                Style);
25085 
25086   verifyFormat("if (i) {\n"
25087                "  ++i;\n"
25088                "} else {\n"
25089                "  --i;\n"
25090                "}",
25091                "if (i)\n"
25092                "  ++i;\n"
25093                "else {\n"
25094                "  --i;\n"
25095                "}",
25096                Style);
25097 
25098   verifyFormat("void f() {\n"
25099                "  while (j--) {\n"
25100                "    while (i) {\n"
25101                "      --i;\n"
25102                "    }\n"
25103                "  }\n"
25104                "}",
25105                "void f() {\n"
25106                "  while (j--)\n"
25107                "    while (i)\n"
25108                "      --i;\n"
25109                "}",
25110                Style);
25111 
25112   verifyFormat("f({\n"
25113                "  if (a) {\n"
25114                "    g();\n"
25115                "  }\n"
25116                "});",
25117                "f({\n"
25118                "  if (a)\n"
25119                "    g();\n"
25120                "});",
25121                Style);
25122 
25123   verifyFormat("if (a) {\n"
25124                "  f();\n"
25125                "} else if (b) {\n"
25126                "  g();\n"
25127                "} else {\n"
25128                "  h();\n"
25129                "}",
25130                "if (a)\n"
25131                "  f();\n"
25132                "else if (b)\n"
25133                "  g();\n"
25134                "else\n"
25135                "  h();",
25136                Style);
25137 
25138   verifyFormat("if (a) {\n"
25139                "  f();\n"
25140                "}\n"
25141                "// comment\n"
25142                "/* comment */",
25143                "if (a)\n"
25144                "  f();\n"
25145                "// comment\n"
25146                "/* comment */",
25147                Style);
25148 
25149   verifyFormat("if (a) {\n"
25150                "  // foo\n"
25151                "  // bar\n"
25152                "  f();\n"
25153                "}",
25154                "if (a)\n"
25155                "  // foo\n"
25156                "  // bar\n"
25157                "  f();",
25158                Style);
25159 
25160   verifyFormat("if (a) { // comment\n"
25161                "  // comment\n"
25162                "  f();\n"
25163                "}",
25164                "if (a) // comment\n"
25165                "  // comment\n"
25166                "  f();",
25167                Style);
25168 
25169   verifyFormat("if (a) {\n"
25170                "  f(); // comment\n"
25171                "}",
25172                "if (a)\n"
25173                "  f(); // comment",
25174                Style);
25175 
25176   verifyFormat("if (a) {\n"
25177                "  f();\n"
25178                "}\n"
25179                "#undef A\n"
25180                "#undef B",
25181                "if (a)\n"
25182                "  f();\n"
25183                "#undef A\n"
25184                "#undef B",
25185                Style);
25186 
25187   verifyFormat("if (a)\n"
25188                "#ifdef A\n"
25189                "  f();\n"
25190                "#else\n"
25191                "  g();\n"
25192                "#endif",
25193                Style);
25194 
25195   verifyFormat("#if 0\n"
25196                "#elif 1\n"
25197                "#endif\n"
25198                "void f() {\n"
25199                "  if (a) {\n"
25200                "    g();\n"
25201                "  }\n"
25202                "}",
25203                "#if 0\n"
25204                "#elif 1\n"
25205                "#endif\n"
25206                "void f() {\n"
25207                "  if (a) g();\n"
25208                "}",
25209                Style);
25210 
25211   Style.ColumnLimit = 15;
25212 
25213   verifyFormat("#define A     \\\n"
25214                "  if (a)      \\\n"
25215                "    f();",
25216                Style);
25217 
25218   verifyFormat("if (a + b >\n"
25219                "    c) {\n"
25220                "  f();\n"
25221                "}",
25222                "if (a + b > c)\n"
25223                "  f();",
25224                Style);
25225 }
25226 
25227 TEST_F(FormatTest, RemoveBraces) {
25228   FormatStyle Style = getLLVMStyle();
25229   Style.RemoveBracesLLVM = true;
25230 
25231   // The following test cases are fully-braced versions of the examples at
25232   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
25233   // statement-bodies-of-if-else-loop-statements".
25234 
25235   // Omit the braces since the body is simple and clearly associated with the
25236   // `if`.
25237   verifyFormat("if (isa<FunctionDecl>(D))\n"
25238                "  handleFunctionDecl(D);\n"
25239                "else if (isa<VarDecl>(D))\n"
25240                "  handleVarDecl(D);",
25241                "if (isa<FunctionDecl>(D)) {\n"
25242                "  handleFunctionDecl(D);\n"
25243                "} else if (isa<VarDecl>(D)) {\n"
25244                "  handleVarDecl(D);\n"
25245                "}",
25246                Style);
25247 
25248   // Here we document the condition itself and not the body.
25249   verifyFormat("if (isa<VarDecl>(D)) {\n"
25250                "  // It is necessary that we explain the situation with this\n"
25251                "  // surprisingly long comment, so it would be unclear\n"
25252                "  // without the braces whether the following statement is in\n"
25253                "  // the scope of the `if`.\n"
25254                "  // Because the condition is documented, we can't really\n"
25255                "  // hoist this comment that applies to the body above the\n"
25256                "  // `if`.\n"
25257                "  handleOtherDecl(D);\n"
25258                "}",
25259                Style);
25260 
25261   // Use braces on the outer `if` to avoid a potential dangling `else`
25262   // situation.
25263   verifyFormat("if (isa<VarDecl>(D)) {\n"
25264                "  if (shouldProcessAttr(A))\n"
25265                "    handleAttr(A);\n"
25266                "}",
25267                "if (isa<VarDecl>(D)) {\n"
25268                "  if (shouldProcessAttr(A)) {\n"
25269                "    handleAttr(A);\n"
25270                "  }\n"
25271                "}",
25272                Style);
25273 
25274   // Use braces for the `if` block to keep it uniform with the `else` block.
25275   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25276                "  handleFunctionDecl(D);\n"
25277                "} else {\n"
25278                "  // In this `else` case, it is necessary that we explain the\n"
25279                "  // situation with this surprisingly long comment, so it\n"
25280                "  // would be unclear without the braces whether the\n"
25281                "  // following statement is in the scope of the `if`.\n"
25282                "  handleOtherDecl(D);\n"
25283                "}",
25284                Style);
25285 
25286   // This should also omit braces. The `for` loop contains only a single
25287   // statement, so it shouldn't have braces.  The `if` also only contains a
25288   // single simple statement (the `for` loop), so it also should omit braces.
25289   verifyFormat("if (isa<FunctionDecl>(D))\n"
25290                "  for (auto *A : D.attrs())\n"
25291                "    handleAttr(A);",
25292                "if (isa<FunctionDecl>(D)) {\n"
25293                "  for (auto *A : D.attrs()) {\n"
25294                "    handleAttr(A);\n"
25295                "  }\n"
25296                "}",
25297                Style);
25298 
25299   // Use braces for a `do-while` loop and its enclosing statement.
25300   verifyFormat("if (Tok->is(tok::l_brace)) {\n"
25301                "  do {\n"
25302                "    Tok = Tok->Next;\n"
25303                "  } while (Tok);\n"
25304                "}",
25305                Style);
25306 
25307   // Use braces for the outer `if` since the nested `for` is braced.
25308   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25309                "  for (auto *A : D.attrs()) {\n"
25310                "    // In this `for` loop body, it is necessary that we\n"
25311                "    // explain the situation with this surprisingly long\n"
25312                "    // comment, forcing braces on the `for` block.\n"
25313                "    handleAttr(A);\n"
25314                "  }\n"
25315                "}",
25316                Style);
25317 
25318   // Use braces on the outer block because there are more than two levels of
25319   // nesting.
25320   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25321                "  for (auto *A : D.attrs())\n"
25322                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
25323                "      handleAttrOnDecl(D, A, i);\n"
25324                "}",
25325                "if (isa<FunctionDecl>(D)) {\n"
25326                "  for (auto *A : D.attrs()) {\n"
25327                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
25328                "      handleAttrOnDecl(D, A, i);\n"
25329                "    }\n"
25330                "  }\n"
25331                "}",
25332                Style);
25333 
25334   // Use braces on the outer block because of a nested `if`; otherwise the
25335   // compiler would warn: `add explicit braces to avoid dangling else`
25336   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25337                "  if (shouldProcess(D))\n"
25338                "    handleVarDecl(D);\n"
25339                "  else\n"
25340                "    markAsIgnored(D);\n"
25341                "}",
25342                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25343                "  if (shouldProcess(D)) {\n"
25344                "    handleVarDecl(D);\n"
25345                "  } else {\n"
25346                "    markAsIgnored(D);\n"
25347                "  }\n"
25348                "}",
25349                Style);
25350 
25351   verifyFormat("// clang-format off\n"
25352                "// comment\n"
25353                "while (i > 0) { --i; }\n"
25354                "// clang-format on\n"
25355                "while (j < 0)\n"
25356                "  ++j;",
25357                "// clang-format off\n"
25358                "// comment\n"
25359                "while (i > 0) { --i; }\n"
25360                "// clang-format on\n"
25361                "while (j < 0) { ++j; }",
25362                Style);
25363 
25364   verifyFormat("if (a)\n"
25365                "  b; // comment\n"
25366                "else if (c)\n"
25367                "  d; /* comment */\n"
25368                "else\n"
25369                "  e;",
25370                "if (a) {\n"
25371                "  b; // comment\n"
25372                "} else if (c) {\n"
25373                "  d; /* comment */\n"
25374                "} else {\n"
25375                "  e;\n"
25376                "}",
25377                Style);
25378 
25379   verifyFormat("if (a) {\n"
25380                "  b;\n"
25381                "  c;\n"
25382                "} else if (d) {\n"
25383                "  e;\n"
25384                "}",
25385                Style);
25386 
25387   verifyFormat("if (a) {\n"
25388                "#undef NDEBUG\n"
25389                "  b;\n"
25390                "} else {\n"
25391                "  c;\n"
25392                "}",
25393                Style);
25394 
25395   verifyFormat("if (a) {\n"
25396                "  // comment\n"
25397                "} else if (b) {\n"
25398                "  c;\n"
25399                "}",
25400                Style);
25401 
25402   verifyFormat("if (a) {\n"
25403                "  b;\n"
25404                "} else {\n"
25405                "  { c; }\n"
25406                "}",
25407                Style);
25408 
25409   verifyFormat("if (a) {\n"
25410                "  if (b) // comment\n"
25411                "    c;\n"
25412                "} else if (d) {\n"
25413                "  e;\n"
25414                "}",
25415                "if (a) {\n"
25416                "  if (b) { // comment\n"
25417                "    c;\n"
25418                "  }\n"
25419                "} else if (d) {\n"
25420                "  e;\n"
25421                "}",
25422                Style);
25423 
25424   verifyFormat("if (a) {\n"
25425                "  if (b) {\n"
25426                "    c;\n"
25427                "    // comment\n"
25428                "  } else if (d) {\n"
25429                "    e;\n"
25430                "  }\n"
25431                "}",
25432                Style);
25433 
25434   verifyFormat("if (a) {\n"
25435                "  if (b)\n"
25436                "    c;\n"
25437                "}",
25438                "if (a) {\n"
25439                "  if (b) {\n"
25440                "    c;\n"
25441                "  }\n"
25442                "}",
25443                Style);
25444 
25445   verifyFormat("if (a)\n"
25446                "  if (b)\n"
25447                "    c;\n"
25448                "  else\n"
25449                "    d;\n"
25450                "else\n"
25451                "  e;",
25452                "if (a) {\n"
25453                "  if (b) {\n"
25454                "    c;\n"
25455                "  } else {\n"
25456                "    d;\n"
25457                "  }\n"
25458                "} else {\n"
25459                "  e;\n"
25460                "}",
25461                Style);
25462 
25463   verifyFormat("if (a) {\n"
25464                "  // comment\n"
25465                "  if (b)\n"
25466                "    c;\n"
25467                "  else if (d)\n"
25468                "    e;\n"
25469                "} else {\n"
25470                "  g;\n"
25471                "}",
25472                "if (a) {\n"
25473                "  // comment\n"
25474                "  if (b) {\n"
25475                "    c;\n"
25476                "  } else if (d) {\n"
25477                "    e;\n"
25478                "  }\n"
25479                "} else {\n"
25480                "  g;\n"
25481                "}",
25482                Style);
25483 
25484   verifyFormat("if (a)\n"
25485                "  b;\n"
25486                "else if (c)\n"
25487                "  d;\n"
25488                "else\n"
25489                "  e;",
25490                "if (a) {\n"
25491                "  b;\n"
25492                "} else {\n"
25493                "  if (c) {\n"
25494                "    d;\n"
25495                "  } else {\n"
25496                "    e;\n"
25497                "  }\n"
25498                "}",
25499                Style);
25500 
25501   verifyFormat("if (a) {\n"
25502                "  if (b)\n"
25503                "    c;\n"
25504                "  else if (d)\n"
25505                "    e;\n"
25506                "} else {\n"
25507                "  g;\n"
25508                "}",
25509                "if (a) {\n"
25510                "  if (b)\n"
25511                "    c;\n"
25512                "  else {\n"
25513                "    if (d)\n"
25514                "      e;\n"
25515                "  }\n"
25516                "} else {\n"
25517                "  g;\n"
25518                "}",
25519                Style);
25520 
25521   verifyFormat("if (isa<VarDecl>(D)) {\n"
25522                "  for (auto *A : D.attrs())\n"
25523                "    if (shouldProcessAttr(A))\n"
25524                "      handleAttr(A);\n"
25525                "}",
25526                "if (isa<VarDecl>(D)) {\n"
25527                "  for (auto *A : D.attrs()) {\n"
25528                "    if (shouldProcessAttr(A)) {\n"
25529                "      handleAttr(A);\n"
25530                "    }\n"
25531                "  }\n"
25532                "}",
25533                Style);
25534 
25535   verifyFormat("do {\n"
25536                "  ++I;\n"
25537                "} while (hasMore() && Filter(*I));",
25538                "do { ++I; } while (hasMore() && Filter(*I));", Style);
25539 
25540   verifyFormat("if (a)\n"
25541                "  if (b)\n"
25542                "    c;\n"
25543                "  else {\n"
25544                "    if (d)\n"
25545                "      e;\n"
25546                "  }\n"
25547                "else\n"
25548                "  f;",
25549                Style);
25550 
25551   verifyFormat("if (a)\n"
25552                "  if (b)\n"
25553                "    c;\n"
25554                "  else {\n"
25555                "    if (d)\n"
25556                "      e;\n"
25557                "    else if (f)\n"
25558                "      g;\n"
25559                "  }\n"
25560                "else\n"
25561                "  h;",
25562                Style);
25563 
25564   verifyFormat("if (a) {\n"
25565                "  b;\n"
25566                "} else if (c) {\n"
25567                "  d;\n"
25568                "  e;\n"
25569                "}",
25570                "if (a) {\n"
25571                "  b;\n"
25572                "} else {\n"
25573                "  if (c) {\n"
25574                "    d;\n"
25575                "    e;\n"
25576                "  }\n"
25577                "}",
25578                Style);
25579 
25580   verifyFormat("if (a) {\n"
25581                "  b;\n"
25582                "  c;\n"
25583                "} else if (d) {\n"
25584                "  e;\n"
25585                "  f;\n"
25586                "}",
25587                "if (a) {\n"
25588                "  b;\n"
25589                "  c;\n"
25590                "} else {\n"
25591                "  if (d) {\n"
25592                "    e;\n"
25593                "    f;\n"
25594                "  }\n"
25595                "}",
25596                Style);
25597 
25598   verifyFormat("if (a) {\n"
25599                "  b;\n"
25600                "} else if (c) {\n"
25601                "  d;\n"
25602                "} else {\n"
25603                "  e;\n"
25604                "  f;\n"
25605                "}",
25606                "if (a) {\n"
25607                "  b;\n"
25608                "} else {\n"
25609                "  if (c) {\n"
25610                "    d;\n"
25611                "  } else {\n"
25612                "    e;\n"
25613                "    f;\n"
25614                "  }\n"
25615                "}",
25616                Style);
25617 
25618   verifyFormat("if (a) {\n"
25619                "  b;\n"
25620                "} else if (c) {\n"
25621                "  d;\n"
25622                "} else if (e) {\n"
25623                "  f;\n"
25624                "  g;\n"
25625                "}",
25626                "if (a) {\n"
25627                "  b;\n"
25628                "} else {\n"
25629                "  if (c) {\n"
25630                "    d;\n"
25631                "  } else if (e) {\n"
25632                "    f;\n"
25633                "    g;\n"
25634                "  }\n"
25635                "}",
25636                Style);
25637 
25638   verifyFormat("if (a) {\n"
25639                "  if (b)\n"
25640                "    c;\n"
25641                "  else if (d) {\n"
25642                "    e;\n"
25643                "    f;\n"
25644                "  }\n"
25645                "} else {\n"
25646                "  g;\n"
25647                "}",
25648                "if (a) {\n"
25649                "  if (b)\n"
25650                "    c;\n"
25651                "  else {\n"
25652                "    if (d) {\n"
25653                "      e;\n"
25654                "      f;\n"
25655                "    }\n"
25656                "  }\n"
25657                "} else {\n"
25658                "  g;\n"
25659                "}",
25660                Style);
25661 
25662   verifyFormat("if (a)\n"
25663                "  if (b)\n"
25664                "    c;\n"
25665                "  else {\n"
25666                "    if (d) {\n"
25667                "      e;\n"
25668                "      f;\n"
25669                "    }\n"
25670                "  }\n"
25671                "else\n"
25672                "  g;",
25673                Style);
25674 
25675   verifyFormat("if (a) {\n"
25676                "  b;\n"
25677                "  c;\n"
25678                "} else { // comment\n"
25679                "  if (d) {\n"
25680                "    e;\n"
25681                "    f;\n"
25682                "  }\n"
25683                "}",
25684                Style);
25685 
25686   verifyFormat("if (a)\n"
25687                "  b;\n"
25688                "else if (c)\n"
25689                "  while (d)\n"
25690                "    e;\n"
25691                "// comment",
25692                "if (a)\n"
25693                "{\n"
25694                "  b;\n"
25695                "} else if (c) {\n"
25696                "  while (d) {\n"
25697                "    e;\n"
25698                "  }\n"
25699                "}\n"
25700                "// comment",
25701                Style);
25702 
25703   verifyFormat("if (a) {\n"
25704                "  b;\n"
25705                "} else if (c) {\n"
25706                "  d;\n"
25707                "} else {\n"
25708                "  e;\n"
25709                "  g;\n"
25710                "}",
25711                Style);
25712 
25713   verifyFormat("if (a) {\n"
25714                "  b;\n"
25715                "} else if (c) {\n"
25716                "  d;\n"
25717                "} else {\n"
25718                "  e;\n"
25719                "} // comment",
25720                Style);
25721 
25722   verifyFormat("int abs = [](int i) {\n"
25723                "  if (i >= 0)\n"
25724                "    return i;\n"
25725                "  return -i;\n"
25726                "};",
25727                "int abs = [](int i) {\n"
25728                "  if (i >= 0) {\n"
25729                "    return i;\n"
25730                "  }\n"
25731                "  return -i;\n"
25732                "};",
25733                Style);
25734 
25735   verifyFormat("if (a)\n"
25736                "  foo();\n"
25737                "else\n"
25738                "  bar();",
25739                "if (a)\n"
25740                "{\n"
25741                "  foo();\n"
25742                "}\n"
25743                "else\n"
25744                "{\n"
25745                "  bar();\n"
25746                "}",
25747                Style);
25748 
25749   verifyFormat("if (a)\n"
25750                "  foo();\n"
25751                "// comment\n"
25752                "else\n"
25753                "  bar();",
25754                "if (a) {\n"
25755                "  foo();\n"
25756                "}\n"
25757                "// comment\n"
25758                "else {\n"
25759                "  bar();\n"
25760                "}",
25761                Style);
25762 
25763   verifyFormat("if (a) {\n"
25764                "  if (b)\n"
25765                "    c = 1; // comment\n"
25766                "}",
25767                "if (a) {\n"
25768                "  if (b) {\n"
25769                "    c = 1; // comment\n"
25770                "  }\n"
25771                "}",
25772                Style);
25773 
25774   verifyFormat("if (a) {\n"
25775                "Label:\n"
25776                "}",
25777                Style);
25778 
25779   verifyFormat("if (a) {\n"
25780                "Label:\n"
25781                "  f();\n"
25782                "}",
25783                Style);
25784 
25785   verifyFormat("if (a) {\n"
25786                "  f();\n"
25787                "Label:\n"
25788                "}",
25789                Style);
25790 
25791   verifyFormat("if consteval {\n"
25792                "  f();\n"
25793                "} else {\n"
25794                "  g();\n"
25795                "}",
25796                Style);
25797 
25798   verifyFormat("if not consteval {\n"
25799                "  f();\n"
25800                "} else if (a) {\n"
25801                "  g();\n"
25802                "}",
25803                Style);
25804 
25805   verifyFormat("if !consteval {\n"
25806                "  g();\n"
25807                "}",
25808                Style);
25809 
25810   Style.ColumnLimit = 65;
25811   verifyFormat("if (condition) {\n"
25812                "  ff(Indices,\n"
25813                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25814                "} else {\n"
25815                "  ff(Indices,\n"
25816                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25817                "}",
25818                Style);
25819 
25820   Style.ColumnLimit = 20;
25821 
25822   verifyFormat("int i;\n"
25823                "#define FOO(a, b)  \\\n"
25824                "  while (a) {      \\\n"
25825                "    b;             \\\n"
25826                "  }",
25827                Style);
25828 
25829   verifyFormat("int ab = [](int i) {\n"
25830                "  if (i > 0) {\n"
25831                "    i = 12345678 -\n"
25832                "        i;\n"
25833                "  }\n"
25834                "  return i;\n"
25835                "};",
25836                Style);
25837 
25838   verifyFormat("if (a) {\n"
25839                "  b = c + // 1 -\n"
25840                "      d;\n"
25841                "}",
25842                Style);
25843 
25844   verifyFormat("if (a) {\n"
25845                "  b = c >= 0 ? d\n"
25846                "             : e;\n"
25847                "}",
25848                "if (a) {\n"
25849                "  b = c >= 0 ? d : e;\n"
25850                "}",
25851                Style);
25852 
25853   verifyFormat("if (a)\n"
25854                "  b = c > 0 ? d : e;",
25855                "if (a) {\n"
25856                "  b = c > 0 ? d : e;\n"
25857                "}",
25858                Style);
25859 
25860   verifyFormat("if (-b >=\n"
25861                "    c) { // Keep.\n"
25862                "  foo();\n"
25863                "} else {\n"
25864                "  bar();\n"
25865                "}",
25866                "if (-b >= c) { // Keep.\n"
25867                "  foo();\n"
25868                "} else {\n"
25869                "  bar();\n"
25870                "}",
25871                Style);
25872 
25873   verifyFormat("if (a) /* Remove. */\n"
25874                "  f();\n"
25875                "else\n"
25876                "  g();",
25877                "if (a) <% /* Remove. */\n"
25878                "  f();\n"
25879                "%> else <%\n"
25880                "  g();\n"
25881                "%>",
25882                Style);
25883 
25884   verifyFormat("while (\n"
25885                "    !i--) <% // Keep.\n"
25886                "  foo();\n"
25887                "%>",
25888                "while (!i--) <% // Keep.\n"
25889                "  foo();\n"
25890                "%>",
25891                Style);
25892 
25893   verifyFormat("for (int &i : chars)\n"
25894                "  ++i;",
25895                "for (int &i :\n"
25896                "     chars) {\n"
25897                "  ++i;\n"
25898                "}",
25899                Style);
25900 
25901   verifyFormat("if (a)\n"
25902                "  b;\n"
25903                "else if (c) {\n"
25904                "  d;\n"
25905                "  e;\n"
25906                "} else\n"
25907                "  f = g(foo, bar,\n"
25908                "        baz);",
25909                "if (a)\n"
25910                "  b;\n"
25911                "else {\n"
25912                "  if (c) {\n"
25913                "    d;\n"
25914                "    e;\n"
25915                "  } else\n"
25916                "    f = g(foo, bar, baz);\n"
25917                "}",
25918                Style);
25919 
25920   Style.ColumnLimit = 0;
25921   verifyFormat("if (a)\n"
25922                "  b234567890223456789032345678904234567890 = "
25923                "c234567890223456789032345678904234567890;",
25924                "if (a) {\n"
25925                "  b234567890223456789032345678904234567890 = "
25926                "c234567890223456789032345678904234567890;\n"
25927                "}",
25928                Style);
25929 
25930   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
25931   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
25932   Style.BraceWrapping.BeforeElse = true;
25933 
25934   Style.ColumnLimit = 65;
25935 
25936   verifyFormat("if (condition)\n"
25937                "{\n"
25938                "  ff(Indices,\n"
25939                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25940                "}\n"
25941                "else\n"
25942                "{\n"
25943                "  ff(Indices,\n"
25944                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25945                "}",
25946                "if (condition) {\n"
25947                "  ff(Indices,\n"
25948                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25949                "} else {\n"
25950                "  ff(Indices,\n"
25951                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25952                "}",
25953                Style);
25954 
25955   verifyFormat("if (a)\n"
25956                "{ //\n"
25957                "  foo();\n"
25958                "}",
25959                "if (a) { //\n"
25960                "  foo();\n"
25961                "}",
25962                Style);
25963 
25964   Style.ColumnLimit = 20;
25965 
25966   verifyFormat("int ab = [](int i) {\n"
25967                "  if (i > 0)\n"
25968                "  {\n"
25969                "    i = 12345678 -\n"
25970                "        i;\n"
25971                "  }\n"
25972                "  return i;\n"
25973                "};",
25974                "int ab = [](int i) {\n"
25975                "  if (i > 0) {\n"
25976                "    i = 12345678 -\n"
25977                "        i;\n"
25978                "  }\n"
25979                "  return i;\n"
25980                "};",
25981                Style);
25982 
25983   verifyFormat("if (a)\n"
25984                "{\n"
25985                "  b = c + // 1 -\n"
25986                "      d;\n"
25987                "}",
25988                "if (a) {\n"
25989                "  b = c + // 1 -\n"
25990                "      d;\n"
25991                "}",
25992                Style);
25993 
25994   verifyFormat("if (a)\n"
25995                "{\n"
25996                "  b = c >= 0 ? d\n"
25997                "             : e;\n"
25998                "}",
25999                "if (a) {\n"
26000                "  b = c >= 0 ? d : e;\n"
26001                "}",
26002                Style);
26003 
26004   verifyFormat("if (a)\n"
26005                "  b = c > 0 ? d : e;",
26006                "if (a)\n"
26007                "{\n"
26008                "  b = c > 0 ? d : e;\n"
26009                "}",
26010                Style);
26011 
26012   verifyFormat("if (foo + bar <=\n"
26013                "    baz)\n"
26014                "{\n"
26015                "  func(arg1, arg2);\n"
26016                "}",
26017                "if (foo + bar <= baz) {\n"
26018                "  func(arg1, arg2);\n"
26019                "}",
26020                Style);
26021 
26022   verifyFormat("if (foo + bar < baz)\n"
26023                "  func(arg1, arg2);\n"
26024                "else\n"
26025                "  func();",
26026                "if (foo + bar < baz)\n"
26027                "<%\n"
26028                "  func(arg1, arg2);\n"
26029                "%>\n"
26030                "else\n"
26031                "<%\n"
26032                "  func();\n"
26033                "%>",
26034                Style);
26035 
26036   verifyFormat("while (i--)\n"
26037                "<% // Keep.\n"
26038                "  foo();\n"
26039                "%>",
26040                "while (i--) <% // Keep.\n"
26041                "  foo();\n"
26042                "%>",
26043                Style);
26044 
26045   verifyFormat("for (int &i : chars)\n"
26046                "  ++i;",
26047                "for (int &i : chars)\n"
26048                "{\n"
26049                "  ++i;\n"
26050                "}",
26051                Style);
26052 }
26053 
26054 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
26055   auto Style = getLLVMStyle();
26056 
26057   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
26058                     "void functionDecl(int a, int b, int c);";
26059 
26060   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
26061                      "paramF, paramG, paramH, paramI);\n"
26062                      "void functionDecl(int argumentA, int argumentB, int "
26063                      "argumentC, int argumentD, int argumentE);";
26064 
26065   verifyFormat(Short, Style);
26066 
26067   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
26068                       "paramF, paramG, paramH,\n"
26069                       "             paramI);\n"
26070                       "void functionDecl(int argumentA, int argumentB, int "
26071                       "argumentC, int argumentD,\n"
26072                       "                  int argumentE);";
26073 
26074   verifyFormat(NoBreak, Medium, Style);
26075   verifyFormat(NoBreak,
26076                "functionCall(\n"
26077                "    paramA,\n"
26078                "    paramB,\n"
26079                "    paramC,\n"
26080                "    paramD,\n"
26081                "    paramE,\n"
26082                "    paramF,\n"
26083                "    paramG,\n"
26084                "    paramH,\n"
26085                "    paramI\n"
26086                ");\n"
26087                "void functionDecl(\n"
26088                "    int argumentA,\n"
26089                "    int argumentB,\n"
26090                "    int argumentC,\n"
26091                "    int argumentD,\n"
26092                "    int argumentE\n"
26093                ");",
26094                Style);
26095 
26096   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
26097                "                  nestedLongFunctionCall(argument1, "
26098                "argument2, argument3,\n"
26099                "                                         argument4, "
26100                "argument5));",
26101                Style);
26102 
26103   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
26104 
26105   verifyFormat(Short, Style);
26106   verifyFormat(
26107       "functionCall(\n"
26108       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
26109       "paramI\n"
26110       ");\n"
26111       "void functionDecl(\n"
26112       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
26113       "argumentE\n"
26114       ");",
26115       Medium, Style);
26116 
26117   Style.AllowAllArgumentsOnNextLine = false;
26118   Style.AllowAllParametersOfDeclarationOnNextLine = false;
26119 
26120   verifyFormat(Short, Style);
26121   verifyFormat(
26122       "functionCall(\n"
26123       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
26124       "paramI\n"
26125       ");\n"
26126       "void functionDecl(\n"
26127       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
26128       "argumentE\n"
26129       ");",
26130       Medium, Style);
26131 
26132   Style.BinPackArguments = false;
26133   Style.BinPackParameters = false;
26134 
26135   verifyFormat(Short, Style);
26136 
26137   verifyFormat("functionCall(\n"
26138                "    paramA,\n"
26139                "    paramB,\n"
26140                "    paramC,\n"
26141                "    paramD,\n"
26142                "    paramE,\n"
26143                "    paramF,\n"
26144                "    paramG,\n"
26145                "    paramH,\n"
26146                "    paramI\n"
26147                ");\n"
26148                "void functionDecl(\n"
26149                "    int argumentA,\n"
26150                "    int argumentB,\n"
26151                "    int argumentC,\n"
26152                "    int argumentD,\n"
26153                "    int argumentE\n"
26154                ");",
26155                Medium, Style);
26156 
26157   verifyFormat("outerFunctionCall(\n"
26158                "    nestedFunctionCall(argument1),\n"
26159                "    nestedLongFunctionCall(\n"
26160                "        argument1,\n"
26161                "        argument2,\n"
26162                "        argument3,\n"
26163                "        argument4,\n"
26164                "        argument5\n"
26165                "    )\n"
26166                ");",
26167                Style);
26168 
26169   verifyFormat("int a = (int)b;", Style);
26170   verifyFormat("int a = (int)b;",
26171                "int a = (\n"
26172                "    int\n"
26173                ") b;",
26174                Style);
26175 
26176   verifyFormat("return (true);", Style);
26177   verifyFormat("return (true);",
26178                "return (\n"
26179                "    true\n"
26180                ");",
26181                Style);
26182 
26183   verifyFormat("void foo();", Style);
26184   verifyFormat("void foo();",
26185                "void foo(\n"
26186                ");",
26187                Style);
26188 
26189   verifyFormat("void foo() {}", Style);
26190   verifyFormat("void foo() {}",
26191                "void foo(\n"
26192                ") {\n"
26193                "}",
26194                Style);
26195 
26196   verifyFormat("auto string = std::string();", Style);
26197   verifyFormat("auto string = std::string();",
26198                "auto string = std::string(\n"
26199                ");",
26200                Style);
26201 
26202   verifyFormat("void (*functionPointer)() = nullptr;", Style);
26203   verifyFormat("void (*functionPointer)() = nullptr;",
26204                "void (\n"
26205                "    *functionPointer\n"
26206                ")\n"
26207                "(\n"
26208                ") = nullptr;",
26209                Style);
26210 }
26211 
26212 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
26213   auto Style = getLLVMStyle();
26214 
26215   verifyFormat("if (foo()) {\n"
26216                "  return;\n"
26217                "}",
26218                Style);
26219 
26220   verifyFormat("if (quitelongarg !=\n"
26221                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
26222                "comment\n"
26223                "  return;\n"
26224                "}",
26225                Style);
26226 
26227   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
26228 
26229   verifyFormat("if (foo()) {\n"
26230                "  return;\n"
26231                "}",
26232                Style);
26233 
26234   verifyFormat("if (quitelongarg !=\n"
26235                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
26236                "comment\n"
26237                "  return;\n"
26238                "}",
26239                Style);
26240 }
26241 
26242 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
26243   auto Style = getLLVMStyle();
26244 
26245   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
26246                "  doSomething();\n"
26247                "}",
26248                Style);
26249 
26250   verifyFormat("for (int myReallyLongCountVariable = 0; "
26251                "myReallyLongCountVariable < count;\n"
26252                "     myReallyLongCountVariable++) {\n"
26253                "  doSomething();\n"
26254                "}",
26255                Style);
26256 
26257   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
26258 
26259   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
26260                "  doSomething();\n"
26261                "}",
26262                Style);
26263 
26264   verifyFormat("for (int myReallyLongCountVariable = 0; "
26265                "myReallyLongCountVariable < count;\n"
26266                "     myReallyLongCountVariable++) {\n"
26267                "  doSomething();\n"
26268                "}",
26269                Style);
26270 }
26271 
26272 TEST_F(FormatTest, UnderstandsDigraphs) {
26273   verifyFormat("int arr<:5:> = {};");
26274   verifyFormat("int arr[5] = <%%>;");
26275   verifyFormat("int arr<:::qualified_variable:> = {};");
26276   verifyFormat("int arr[::qualified_variable] = <%%>;");
26277   verifyFormat("%:include <header>");
26278   verifyFormat("%:define A x##y");
26279   verifyFormat("#define A x%:%:y");
26280 }
26281 
26282 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
26283   auto Style = getLLVMStyle();
26284   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
26285   Style.AlignConsecutiveAssignments.Enabled = true;
26286   Style.AlignConsecutiveDeclarations.Enabled = true;
26287 
26288   // The AlignArray code is incorrect for non square Arrays and can cause
26289   // crashes, these tests assert that the array is not changed but will
26290   // also act as regression tests for when it is properly fixed
26291   verifyFormat("struct test demo[] = {\n"
26292                "    {1, 2},\n"
26293                "    {3, 4, 5},\n"
26294                "    {6, 7, 8}\n"
26295                "};",
26296                Style);
26297   verifyFormat("struct test demo[] = {\n"
26298                "    {1, 2, 3, 4, 5},\n"
26299                "    {3, 4, 5},\n"
26300                "    {6, 7, 8}\n"
26301                "};",
26302                Style);
26303   verifyFormat("struct test demo[] = {\n"
26304                "    {1, 2, 3, 4, 5},\n"
26305                "    {3, 4, 5},\n"
26306                "    {6, 7, 8, 9, 10, 11, 12}\n"
26307                "};",
26308                Style);
26309   verifyFormat("struct test demo[] = {\n"
26310                "    {1, 2, 3},\n"
26311                "    {3, 4, 5},\n"
26312                "    {6, 7, 8, 9, 10, 11, 12}\n"
26313                "};",
26314                Style);
26315 
26316   verifyFormat("S{\n"
26317                "    {},\n"
26318                "    {},\n"
26319                "    {a, b}\n"
26320                "};",
26321                Style);
26322   verifyFormat("S{\n"
26323                "    {},\n"
26324                "    {},\n"
26325                "    {a, b},\n"
26326                "};",
26327                Style);
26328   verifyFormat("void foo() {\n"
26329                "  auto thing = test{\n"
26330                "      {\n"
26331                "       {13}, {something}, // A\n"
26332                "      }\n"
26333                "  };\n"
26334                "}",
26335                "void foo() {\n"
26336                "  auto thing = test{\n"
26337                "      {\n"
26338                "       {13},\n"
26339                "       {something}, // A\n"
26340                "      }\n"
26341                "  };\n"
26342                "}",
26343                Style);
26344 }
26345 
26346 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
26347   auto Style = getLLVMStyle();
26348   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
26349   Style.AlignConsecutiveAssignments.Enabled = true;
26350   Style.AlignConsecutiveDeclarations.Enabled = true;
26351 
26352   // The AlignArray code is incorrect for non square Arrays and can cause
26353   // crashes, these tests assert that the array is not changed but will
26354   // also act as regression tests for when it is properly fixed
26355   verifyFormat("struct test demo[] = {\n"
26356                "    {1, 2},\n"
26357                "    {3, 4, 5},\n"
26358                "    {6, 7, 8}\n"
26359                "};",
26360                Style);
26361   verifyFormat("struct test demo[] = {\n"
26362                "    {1, 2, 3, 4, 5},\n"
26363                "    {3, 4, 5},\n"
26364                "    {6, 7, 8}\n"
26365                "};",
26366                Style);
26367   verifyFormat("struct test demo[] = {\n"
26368                "    {1, 2, 3, 4, 5},\n"
26369                "    {3, 4, 5},\n"
26370                "    {6, 7, 8, 9, 10, 11, 12}\n"
26371                "};",
26372                Style);
26373   verifyFormat("struct test demo[] = {\n"
26374                "    {1, 2, 3},\n"
26375                "    {3, 4, 5},\n"
26376                "    {6, 7, 8, 9, 10, 11, 12}\n"
26377                "};",
26378                Style);
26379 
26380   verifyFormat("S{\n"
26381                "    {},\n"
26382                "    {},\n"
26383                "    {a, b}\n"
26384                "};",
26385                Style);
26386   verifyFormat("S{\n"
26387                "    {},\n"
26388                "    {},\n"
26389                "    {a, b},\n"
26390                "};",
26391                Style);
26392   verifyFormat("void foo() {\n"
26393                "  auto thing = test{\n"
26394                "      {\n"
26395                "       {13}, {something}, // A\n"
26396                "      }\n"
26397                "  };\n"
26398                "}",
26399                "void foo() {\n"
26400                "  auto thing = test{\n"
26401                "      {\n"
26402                "       {13},\n"
26403                "       {something}, // A\n"
26404                "      }\n"
26405                "  };\n"
26406                "}",
26407                Style);
26408 }
26409 
26410 TEST_F(FormatTest, FormatsVariableTemplates) {
26411   verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
26412   verifyFormat("template <typename T> "
26413                "inline bool var = is_integral_v<T> && is_signed_v<T>;");
26414 }
26415 
26416 } // namespace
26417 } // namespace format
26418 } // namespace clang
26419